<commit_before>/// \file urbi/ustarter.hh

// This file is part of UObject Component Architecture
// Copyright (c) 2007, 2008 Gostai S.A.S.
//
// Permission to use, copy, modify, and redistribute this software for
// non-commercial use is hereby granted.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
// For more information, comments, bug reports: http://www.urbiforge.com

#ifndef URBI_STARTER_HH
# define URBI_STARTER_HH

# include <algorithm>
# include <string>

# include <urbi/fwd.hh>
# include <urbi/export.hh>

/// This macro must be called once for every UObject class.
# define UStartRename(Type, Name)                                       \
  ::urbi::URBIStarter<Type>                                             \
  Name ##  ____URBI_object(std::string(#Name), ::urbi::objectlist)

/// Append connectionID to object name
# define UStartWithID(X)						\
  ::urbi::URBIStarter<X> X ##  ____URBI_object(std::string(#X),		\
					       ::urbi::objectlist,	\
					       true)

/// This macro must be called once for every UObject class.
# define UStart(Type)							\
  UStartRename(Type, Type)

/// This macro must be called once for each UObjectHub class.
# define UStartHub(Type)                                                \
  ::urbi::URBIStarterHub<Type>                                          \
  Type ##  ____URBI_object(std::string(#Type), ::urbi::objecthublist)

namespace urbi
{

  typedef std::list<baseURBIStarter*> UStartlist;
  typedef std::list<baseURBIStarterHub*> UStartlistHub;

  // Two singleton lists to handle the object and hubobject registration.
  EXTERN_STATIC_INSTANCE_EX(UStartlist, objectlist, URBI_SDK_API);
  EXTERN_STATIC_INSTANCE_EX(UStartlistHub, objecthublist, URBI_SDK_API);

  /// URBIStarter base class used to store heterogeneous template
  /// class objects in starterlist.
  class URBI_SDK_API baseURBIStarter
  {
  public:
    baseURBIStarter(const std::string& name, bool local);
    virtual ~baseURBIStarter();

    virtual UObject* getUObject() = 0;

    /// Called before deletion.
    virtual void clean() = 0;
    /// Used to provide a wrapper to initialize objects in starterlist.
    virtual void init(const std::string&) = 0;
    /// Used to provide a copy of a C++ object based on its name.
    virtual void copy(const std::string&) = 0;
    std::string name;
    bool local;
  };

  //! This is the class containing URBI starters
  /** A starter is a class whose job is to start an instance of a particular
   * UObject subclass, resulting in the initialization of this object
   * (registration to the kernel)
   */
  template <class T>
  class URBIStarter
    : public baseURBIStarter
  {
  public:
    URBIStarter(const std::string& name, UStartlist& _slist, bool local);

    virtual ~URBIStarter();

    virtual void clean();

    virtual void copy(const std::string& objname);

    /// Access to the object from the outside.
    virtual UObject* getUObject();

  protected:
    /// Called when the object is ready to be initialized.
    virtual void init(const std::string& objname);

    UStartlist& slist_;
    T* object;
  };

#define SETBACKCASTCTOR(T)			\
  inline					\
  UValue					\
  back_cast(T& t)				\
  {						\
    return UValue(t);				\
  }

SETBACKCASTCTOR(bool)
SETBACKCASTCTOR(int)
SETBACKCASTCTOR(long)
SETBACKCASTCTOR(ufloat)
SETBACKCASTCTOR(UValue)
SETBACKCASTCTOR(char*)
SETBACKCASTCTOR(void*)
SETBACKCASTCTOR(const std::string)
SETBACKCASTCTOR(std::string)
SETBACKCASTCTOR(const UBinary)
SETBACKCASTCTOR(const UList)
SETBACKCASTCTOR(const UObjectStruct)
SETBACKCASTCTOR(const USound)
SETBACKCASTCTOR(const UImage)

  /// URBIStarter base class used to store heterogeneous template
  /// class objects in starterlist
  class URBI_SDK_API baseURBIStarterHub
  {
  public:
    baseURBIStarterHub(const std::string& name);
    virtual ~baseURBIStarterHub();

    /// Used to provide a wrapper to initialize objects in starterlist.
    virtual void init(const std::string&) = 0;
    virtual UObjectHub* getUObjectHub() = 0;
    std::string name;
  };

  //! This is the class containing URBI starters
  /** A starter is a class whose job is to start an instance of a particular
   * UObject subclass, resulting in the initialization of this object
   * (registration to the kernel)
   */
  template <class T>
  class URBIStarterHub
    : public baseURBIStarterHub
  {
  public:
    URBIStarterHub(const std::string& name, UStartlistHub& slist);
    virtual ~URBIStarterHub();

  protected:
    /// Called when the object is ready to be initialized.
    virtual void init(const std::string& objname);

    /// Access to the object from the outside.
    virtual UObjectHub* getUObjectHub();

    UStartlistHub& slist_;
    T* object;
  };

} // end namespace urbi

# include <urbi/ustarter.hxx>

#endif // ! URBI_STARTER_HH
<commit_msg>UStarter, Add missing default values.<commit_after>/// \file urbi/ustarter.hh

// This file is part of UObject Component Architecture
// Copyright (c) 2007, 2008 Gostai S.A.S.
//
// Permission to use, copy, modify, and redistribute this software for
// non-commercial use is hereby granted.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
// For more information, comments, bug reports: http://www.urbiforge.com

#ifndef URBI_STARTER_HH
# define URBI_STARTER_HH

# include <algorithm>
# include <string>

# include <urbi/fwd.hh>
# include <urbi/export.hh>

/// This macro must be called once for every UObject class.
# define UStartRename(Type, Name)                                       \
  ::urbi::URBIStarter<Type>                                             \
  Name ##  ____URBI_object(std::string(#Name), ::urbi::objectlist)

/// Append connectionID to object name
# define UStartWithID(X)						\
  ::urbi::URBIStarter<X> X ##  ____URBI_object(std::string(#X),		\
					       ::urbi::objectlist,	\
					       true)

/// This macro must be called once for every UObject class.
# define UStart(Type)							\
  UStartRename(Type, Type)

/// This macro must be called once for each UObjectHub class.
# define UStartHub(Type)                                                \
  ::urbi::URBIStarterHub<Type>                                          \
  Type ##  ____URBI_object(std::string(#Type), ::urbi::objecthublist)

namespace urbi
{

  typedef std::list<baseURBIStarter*> UStartlist;
  typedef std::list<baseURBIStarterHub*> UStartlistHub;

  // Two singleton lists to handle the object and hubobject registration.
  EXTERN_STATIC_INSTANCE_EX(UStartlist, objectlist, URBI_SDK_API);
  EXTERN_STATIC_INSTANCE_EX(UStartlistHub, objecthublist, URBI_SDK_API);

  /// URBIStarter base class used to store heterogeneous template
  /// class objects in starterlist.
  class URBI_SDK_API baseURBIStarter
  {
  public:
    baseURBIStarter(const std::string& name, bool local = false);
    virtual ~baseURBIStarter();

    virtual UObject* getUObject() = 0;

    /// Called before deletion.
    virtual void clean() = 0;
    /// Used to provide a wrapper to initialize objects in starterlist.
    virtual void init(const std::string&) = 0;
    /// Used to provide a copy of a C++ object based on its name.
    virtual void copy(const std::string&) = 0;
    std::string name;
    bool local;
  };

  //! This is the class containing URBI starters
  /** A starter is a class whose job is to start an instance of a particular
   * UObject subclass, resulting in the initialization of this object
   * (registration to the kernel)
   */
  template <class T>
  class URBIStarter
    : public baseURBIStarter
  {
  public:
    URBIStarter(const std::string& name, UStartlist& _slist, bool local = false);

    virtual ~URBIStarter();

    virtual void clean();

    virtual void copy(const std::string& objname);

    /// Access to the object from the outside.
    virtual UObject* getUObject();

  protected:
    /// Called when the object is ready to be initialized.
    virtual void init(const std::string& objname);

    UStartlist& slist_;
    T* object;
  };

#define SETBACKCASTCTOR(T)			\
  inline					\
  UValue					\
  back_cast(T& t)				\
  {						\
    return UValue(t);				\
  }

SETBACKCASTCTOR(bool)
SETBACKCASTCTOR(int)
SETBACKCASTCTOR(long)
SETBACKCASTCTOR(ufloat)
SETBACKCASTCTOR(UValue)
SETBACKCASTCTOR(char*)
SETBACKCASTCTOR(void*)
SETBACKCASTCTOR(const std::string)
SETBACKCASTCTOR(std::string)
SETBACKCASTCTOR(const UBinary)
SETBACKCASTCTOR(const UList)
SETBACKCASTCTOR(const UObjectStruct)
SETBACKCASTCTOR(const USound)
SETBACKCASTCTOR(const UImage)

  /// URBIStarter base class used to store heterogeneous template
  /// class objects in starterlist
  class URBI_SDK_API baseURBIStarterHub
  {
  public:
    baseURBIStarterHub(const std::string& name);
    virtual ~baseURBIStarterHub();

    /// Used to provide a wrapper to initialize objects in starterlist.
    virtual void init(const std::string&) = 0;
    virtual UObjectHub* getUObjectHub() = 0;
    std::string name;
  };

  //! This is the class containing URBI starters
  /** A starter is a class whose job is to start an instance of a particular
   * UObject subclass, resulting in the initialization of this object
   * (registration to the kernel)
   */
  template <class T>
  class URBIStarterHub
    : public baseURBIStarterHub
  {
  public:
    URBIStarterHub(const std::string& name, UStartlistHub& slist);
    virtual ~URBIStarterHub();

  protected:
    /// Called when the object is ready to be initialized.
    virtual void init(const std::string& objname);

    /// Access to the object from the outside.
    virtual UObjectHub* getUObjectHub();

    UStartlistHub& slist_;
    T* object;
  };

} // end namespace urbi

# include <urbi/ustarter.hxx>

#endif // ! URBI_STARTER_HH
<|endoftext|>


<commit_before>#include <string>
#include "gtest/gtest.h"
#include "StatechartEntryAndExitActions.h"
#include "sc_runner.h"
#include "sc_types.h"

namespace  {

void entryActionsAreExecutedOnEnteringStatechartOnlyIfGuardIsTrue();
void exitActionsAreExecutedOnEnteringStatechartOnlyIfGuardIsTrue();
statechartactions::StatechartEntryAndExitActions* statechart;

//! The timers are managed by a timer service. */
static SctUnitRunner * runner;

class StatechartEntryExitActions : public ::testing::Test{
	protected:
	virtual void SetUp() {
		statechart = new statechartactions::StatechartEntryAndExitActions();
		statechart->init();
		runner = new SctUnitRunner(
			statechart,
			false,
			200
		);
	}
	virtual void TearDown() {
		delete statechart;
		delete runner;
	}
};

void entryActionsAreExecutedOnEnteringStatechartOnlyIfGuardIsTrue(){
	EXPECT_TRUE(statechart->getDefaultSCI()->get_x()== 0l);

	EXPECT_TRUE(statechart->getDefaultSCI()->get_y()== 0l);

	statechart->getDefaultSCI()->set_b(false);

	statechart->enter();

	EXPECT_TRUE(statechart->getDefaultSCI()->get_x()== 2l);

	EXPECT_TRUE(statechart->getDefaultSCI()->get_y()== 3l);

}
void exitActionsAreExecutedOnEnteringStatechartOnlyIfGuardIsTrue(){
	statechart->enter();

	statechart->exit();

	EXPECT_TRUE(statechart->getDefaultSCI()->get_x()== 8l);

	EXPECT_TRUE(statechart->getDefaultSCI()->get_y()== 2l);

}

TEST_F(StatechartEntryExitActions, entryActionsAreExecutedOnEnteringStatechart) {

	EXPECT_TRUE(statechart->getDefaultSCI()->get_x()== 0l);

	EXPECT_TRUE(statechart->getDefaultSCI()->get_y()== 0l);

	statechart->getDefaultSCI()->set_b(true);

	statechart->enter();

	EXPECT_TRUE(statechart->getDefaultSCI()->get_x()== 5l);

	EXPECT_TRUE(statechart->getDefaultSCI()->get_y()== 3l);

}
TEST_F(StatechartEntryExitActions, exitActionsAreExecutedOnEnteringStatechart) {

	statechart->enter();

	statechart->exit();

	EXPECT_TRUE(statechart->getDefaultSCI()->get_x()== 6l);

	EXPECT_TRUE(statechart->getDefaultSCI()->get_y()== 2l);

}

}

<commit_msg>Update StatechartEntryExitActions.cc<commit_after>#include <string>
#include "gtest/gtest.h"
#include "StatechartEntryAndExitActions.h"
#include "sc_runner.h"
#include "sc_types.h"

namespace  {

void entryActionsAreExecutedOnEnteringStatechartOnlyIfGuardIsTrue();
void exitActionsAreExecutedOnEnteringStatechartOnlyIfGuardIsTrue();
statechartactions::StatechartEntryAndExitActions* statechart;

//! The timers are managed by a timer service. */
static SctUnitRunner * runner;

class StatechartEntryExitActions : public ::testing::Test{
	protected:
	virtual void SetUp() {
		statechart = new statechartactions::StatechartEntryAndExitActions();
		statechart->init();
		runner = new SctUnitRunner(
			statechart,
			false,
			200
		);
	}
	virtual void TearDown() {
		delete statechart;
		delete runner;
	}
};

void entryActionsAreExecutedOnEnteringStatechartOnlyIfGuardIsTrue(){
	EXPECT_TRUE(statechart->getDefaultSCI()->get_x()== 0l);

	EXPECT_TRUE(statechart->getDefaultSCI()->get_y()== 0l);

	statechart->getDefaultSCI()->set_b(false);

	statechart->enter();

	EXPECT_TRUE(statechart->getDefaultSCI()->get_x()== 2l);

	EXPECT_TRUE(statechart->getDefaultSCI()->get_y()== 3l);

}
void exitActionsAreExecutedOnEnteringStatechartOnlyIfGuardIsTrue(){
	statechart->enter();

	statechart->exit();

	EXPECT_TRUE(statechart->getDefaultSCI()->get_x()== 8l);

	EXPECT_TRUE(statechart->getDefaultSCI()->get_y()== 2l);

}

TEST_F(StatechartEntryExitActions, entryActionsAreExecutedOnEnteringStatechart) {

	EXPECT_TRUE(statechart->getDefaultSCI()->get_x()== 0l);

	EXPECT_TRUE(statechart->getDefaultSCI()->get_y()== 0l);

	statechart->getDefaultSCI()->set_b(true);

	statechart->enter();

	EXPECT_TRUE(statechart->getDefaultSCI()->get_x()== 5l);

	EXPECT_TRUE(statechart->getDefaultSCI()->get_y()== 3l);

}
TEST_F(StatechartEntryExitActions, exitActionsAreExecutedOnEnteringStatechart) {

	statechart->enter();

	statechart->exit();

	EXPECT_TRUE(statechart->getDefaultSCI()->get_x()== 6l);

	EXPECT_TRUE(statechart->getDefaultSCI()->get_y()== 2l);

}

}

<|endoftext|>


<commit_before>//===- Version.cpp - Clang Version Number -----------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines several version-related utility functions for Clang.
//
//===----------------------------------------------------------------------===//
#include <cstring>
#include <cstdlib>
using namespace std;

namespace clang {

const char *getClangSubversionPath() {
  static const char *Path = 0;
  if (Path)
    return Path;

  static char URL[] = "$URL$";
  char *End = strstr(URL, "/lib/Basic");
  if (End)
    *End = 0;

  char *Begin = strstr(URL, "cfe/");
  if (Begin) {
    Path = Begin + 4;
    return Path;
  }

  Path = URL;
  return Path;
}

unsigned getClangSubversionRevision() {
#ifndef SVN_REVISION
  // Subversion was not available at build time?
  return 0;
#else
  return strtol(SVN_REVISION, 0, 10);
#endif
}

} // end namespace clang
<commit_msg>Strip off the /clang/tools/clang at the end of the Subversion URL, if it's there<commit_after>//===- Version.cpp - Clang Version Number -----------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines several version-related utility functions for Clang.
//
//===----------------------------------------------------------------------===//
#include <cstring>
#include <cstdlib>
using namespace std;

namespace clang {

const char *getClangSubversionPath() {
  static const char *Path = 0;
  if (Path)
    return Path;

  static char URL[] = "$URL$";
  char *End = strstr(URL, "/lib/Basic");
  if (End)
    *End = 0;

  End = strstr(URL, "/clang/tools/clang");
  if (End)
    *End = 0;

  char *Begin = strstr(URL, "cfe/");
  if (Begin) {
    Path = Begin + 4;
    return Path;
  }

  Path = URL;
  return Path;
}

unsigned getClangSubversionRevision() {
#ifndef SVN_REVISION
  // Subversion was not available at build time?
  return 0;
#else
  return strtol(SVN_REVISION, 0, 10);
#endif
}

} // end namespace clang
<|endoftext|>


<commit_before><commit_msg>Format<commit_after><|endoftext|>


<commit_before><commit_msg>Create CoupledPotential.C<commit_after><|endoftext|>


<commit_before><commit_msg>Fixing a small typo in get_ros_params.cpp<commit_after><|endoftext|>


<commit_before>//===--- TBDGen.cpp - Swift TBD Generation --------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  This file implements the entrypoints into TBD file generation.
//
//===----------------------------------------------------------------------===//

#include "swift/TBDGen/TBDGen.h"

#include "swift/AST/ASTMangler.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/Module.h"
#include "swift/Basic/LLVM.h"
#include "swift/IRGen/LinkEntity.h"
#include "swift/SIL/FormalLinkage.h"
#include "swift/SIL/SILDeclRef.h"
#include "llvm/ADT/StringSet.h"

using namespace swift;
using StringSet = llvm::StringSet<>;

static bool isPrivateDecl(ValueDecl *VD) {
  return getDeclLinkage(VD) != FormalLinkage::PublicUnique;
}

namespace {
class TBDGenVisitor : public ASTVisitor<TBDGenVisitor> {
  StringSet &Symbols;

  void addSymbol(StringRef name) {
    assert(Symbols.insert(name).second && "already inserted");
  }

  void visitValueTypeDecl(NominalTypeDecl *NTD) {
    assert(isa<StructDecl>(NTD) || isa<EnumDecl>(NTD));
    if (isPrivateDecl(NTD))
      return;

    auto declaredType = NTD->getDeclaredType()->getCanonicalType();

    auto vwt = irgen::LinkEntity::forValueWitnessTable(declaredType);
    addSymbol(vwt.mangleAsString());

    visitNominalTypeDecl(NTD);
  }

public:
  TBDGenVisitor(StringSet &symbols) : Symbols(symbols) {}

  void visitMembers(Decl *D) {
    SmallVector<Decl *, 4> members;
    auto addMembers = [&](DeclRange range) {
      for (auto member : range)
        members.push_back(member);
    };
    if (auto ED = dyn_cast<ExtensionDecl>(D))
      addMembers(ED->getMembers());
    else if (auto NTD = dyn_cast<NominalTypeDecl>(D))
      addMembers(NTD->getMembers());

    for (auto member : members) {
      ASTVisitor::visit(member);
    }
  }
  void visitValueDecl(ValueDecl *VD) {
    if (isPrivateDecl(VD))
      return;

    auto declRef = SILDeclRef(VD);
    addSymbol(declRef.mangle());

    visitMembers(VD);
  }
  void visitTypeAliasDecl(TypeAliasDecl *TAD) {
    // any information here is encoded elsewhere
  }
  void visitNominalTypeDecl(NominalTypeDecl *NTD) {
    auto declaredType = NTD->getDeclaredType()->getCanonicalType();

    auto ntDescriptor = irgen::LinkEntity::forNominalTypeDescriptor(NTD);
    addSymbol(ntDescriptor.mangleAsString());

    auto tmd = irgen::LinkEntity::forTypeMetadata(
        declaredType, irgen::TypeMetadataAddress::AddressPoint,
        /*isPattern=*/false);
    addSymbol(tmd.mangleAsString());
    auto tmda = irgen::LinkEntity::forTypeMetadataAccessFunction(declaredType);
    addSymbol(tmda.mangleAsString());

    if (isPrivateDecl(NTD))
      return;

    visitMembers(NTD);
  }
  void visitClassDecl(ClassDecl *CD) {
    if (isPrivateDecl(CD))
      return;

    auto declaredType = CD->getDeclaredType()->getCanonicalType();

    auto tmlcv =
        irgen::LinkEntity::forTypeMetadataLazyCacheVariable(declaredType);
    addSymbol(tmlcv.mangleAsString());

    visitNominalTypeDecl(CD);
  }

  void visitStructDecl(StructDecl *SD) { visitValueTypeDecl(SD); }
  void visitEnumDecl(EnumDecl *ED) { visitValueTypeDecl(ED); }
  void visitProtocolDecl(ProtocolDecl *PD) {
    if (isPrivateDecl(PD))
      return;

    auto pDescriptor = irgen::LinkEntity::forProtocolDescriptor(PD);
    addSymbol(pDescriptor.mangleAsString());

    // There's no relevant information about members of a protocol at individual
    // protocols, each conforming type has to handle them individually.
  }

  void visitVarDecl(VarDecl *VD);

  void visitDecl(Decl *D) { visitMembers(D); }
};
}

void TBDGenVisitor::visitVarDecl(VarDecl *VD) {
  if (isPrivateDecl(VD))
    return;

  // statically/globally stored variables have some special handling.
  if (VD->hasStorage() &&
      (VD->isStatic() || VD->getDeclContext()->isModuleScopeContext())) {
    // The actual variable has a symbol, even when private.
    Mangle::ASTMangler mangler;
    addSymbol(mangler.mangleEntity(VD, false));

    auto accessor = SILDeclRef(VD, SILDeclRef::Kind::GlobalAccessor);
    addSymbol(accessor.mangle());
  }

  visitMembers(VD);
}

void swift::enumeratePublicSymbols(FileUnit *file, StringSet &symbols) {
  SmallVector<Decl *, 16> decls;
  file->getTopLevelDecls(decls);

  TBDGenVisitor visitor(symbols);
  for (auto d : decls)
    visitor.visit(d);
}
<commit_msg>[TBDGen] Side-effects and asserts don't mix.<commit_after>//===--- TBDGen.cpp - Swift TBD Generation --------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  This file implements the entrypoints into TBD file generation.
//
//===----------------------------------------------------------------------===//

#include "swift/TBDGen/TBDGen.h"

#include "swift/AST/ASTMangler.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/Module.h"
#include "swift/Basic/LLVM.h"
#include "swift/IRGen/LinkEntity.h"
#include "swift/SIL/FormalLinkage.h"
#include "swift/SIL/SILDeclRef.h"
#include "llvm/ADT/StringSet.h"

using namespace swift;
using StringSet = llvm::StringSet<>;

static bool isPrivateDecl(ValueDecl *VD) {
  return getDeclLinkage(VD) != FormalLinkage::PublicUnique;
}

namespace {
class TBDGenVisitor : public ASTVisitor<TBDGenVisitor> {
  StringSet &Symbols;

  void addSymbol(StringRef name) {
    auto isNewValue = Symbols.insert(name).second;
    (void)isNewValue;
    assert(isNewValue && "already inserted");
  }

  void visitValueTypeDecl(NominalTypeDecl *NTD) {
    assert(isa<StructDecl>(NTD) || isa<EnumDecl>(NTD));
    if (isPrivateDecl(NTD))
      return;

    auto declaredType = NTD->getDeclaredType()->getCanonicalType();

    auto vwt = irgen::LinkEntity::forValueWitnessTable(declaredType);
    addSymbol(vwt.mangleAsString());

    visitNominalTypeDecl(NTD);
  }

public:
  TBDGenVisitor(StringSet &symbols) : Symbols(symbols) {}

  void visitMembers(Decl *D) {
    SmallVector<Decl *, 4> members;
    auto addMembers = [&](DeclRange range) {
      for (auto member : range)
        members.push_back(member);
    };
    if (auto ED = dyn_cast<ExtensionDecl>(D))
      addMembers(ED->getMembers());
    else if (auto NTD = dyn_cast<NominalTypeDecl>(D))
      addMembers(NTD->getMembers());

    for (auto member : members) {
      ASTVisitor::visit(member);
    }
  }
  void visitValueDecl(ValueDecl *VD) {
    if (isPrivateDecl(VD))
      return;

    auto declRef = SILDeclRef(VD);
    addSymbol(declRef.mangle());

    visitMembers(VD);
  }
  void visitTypeAliasDecl(TypeAliasDecl *TAD) {
    // any information here is encoded elsewhere
  }
  void visitNominalTypeDecl(NominalTypeDecl *NTD) {
    auto declaredType = NTD->getDeclaredType()->getCanonicalType();

    auto ntDescriptor = irgen::LinkEntity::forNominalTypeDescriptor(NTD);
    addSymbol(ntDescriptor.mangleAsString());

    auto tmd = irgen::LinkEntity::forTypeMetadata(
        declaredType, irgen::TypeMetadataAddress::AddressPoint,
        /*isPattern=*/false);
    addSymbol(tmd.mangleAsString());
    auto tmda = irgen::LinkEntity::forTypeMetadataAccessFunction(declaredType);
    addSymbol(tmda.mangleAsString());

    if (isPrivateDecl(NTD))
      return;

    visitMembers(NTD);
  }
  void visitClassDecl(ClassDecl *CD) {
    if (isPrivateDecl(CD))
      return;

    auto declaredType = CD->getDeclaredType()->getCanonicalType();

    auto tmlcv =
        irgen::LinkEntity::forTypeMetadataLazyCacheVariable(declaredType);
    addSymbol(tmlcv.mangleAsString());

    visitNominalTypeDecl(CD);
  }

  void visitStructDecl(StructDecl *SD) { visitValueTypeDecl(SD); }
  void visitEnumDecl(EnumDecl *ED) { visitValueTypeDecl(ED); }
  void visitProtocolDecl(ProtocolDecl *PD) {
    if (isPrivateDecl(PD))
      return;

    auto pDescriptor = irgen::LinkEntity::forProtocolDescriptor(PD);
    addSymbol(pDescriptor.mangleAsString());

    // There's no relevant information about members of a protocol at individual
    // protocols, each conforming type has to handle them individually.
  }

  void visitVarDecl(VarDecl *VD);

  void visitDecl(Decl *D) { visitMembers(D); }
};
}

void TBDGenVisitor::visitVarDecl(VarDecl *VD) {
  if (isPrivateDecl(VD))
    return;

  // statically/globally stored variables have some special handling.
  if (VD->hasStorage() &&
      (VD->isStatic() || VD->getDeclContext()->isModuleScopeContext())) {
    // The actual variable has a symbol, even when private.
    Mangle::ASTMangler mangler;
    addSymbol(mangler.mangleEntity(VD, false));

    auto accessor = SILDeclRef(VD, SILDeclRef::Kind::GlobalAccessor);
    addSymbol(accessor.mangle());
  }

  visitMembers(VD);
}

void swift::enumeratePublicSymbols(FileUnit *file, StringSet &symbols) {
  SmallVector<Decl *, 16> decls;
  file->getTopLevelDecls(decls);

  TBDGenVisitor visitor(symbols);
  for (auto d : decls)
    visitor.visit(d);
}
<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt 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.

=========================================================================*/

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {MSLabeledOutput.tif}
//    OUTPUTS: {OBIAShapeAttribute.txt}
//  Software Guide : EndCommandLineArgs

//  Software Guide : BeginLatex
//
//  This example shows the
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet

// Software Guide : EndCodeSnippet
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkSimpleFilterWatcher.h"

//#include "itkLabelStatisticsKeepNObjectsImageFilter.h"

#include "itkLabelImageToLabelMapFilter.h"
#include "itkStatisticsLabelObject.h"
#include "itkStatisticsLabelMapFilter.h"
#include "itkStatisticsKeepNObjectsLabelMapFilter.h"
#include "itkLabelMapToLabelImageFilter.h"

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

  if( argc != 8 )
    {
    std::cerr << "usage: " << argv[0] << " input input output background nb reverseOrdering attribute" << std::endl;
    // std::cerr << "  : " << std::endl;
    exit(1);
    }

  const int dim = 3;

  typedef unsigned char PixelType;
  typedef itk::Image< PixelType, dim > IType;

  typedef itk::ImageFileReader< IType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );

  ReaderType::Pointer reader2 = ReaderType::New();
  reader2->SetFileName( argv[2] );

  typedef itk::StatisticsLabelObject<PixelType, dim> LabelObjectType;
  typedef  itk::LabelMap< LabelObjectType > LabelMapType;
    typedef  itk::LabelImageToLabelMapFilter< IType, LabelMapType > LabelizerType;

    typedef itk::StatisticsLabelMapFilter< LabelMapType, IType > LabelObjectValuatorType;
  typedef  LabelObjectType::AttributeType AttributeType;
  typedef  itk::StatisticsKeepNObjectsLabelMapFilter< LabelMapType > KeepNObjectsType;
  typedef  itk::LabelMapToLabelImageFilter< LabelMapType, IType > BinarizerType;

     LabelizerType::Pointer labelizer = LabelizerType::New();
  labelizer->SetInput( reader->GetOutput() );
  labelizer->SetBackgroundValue( atoi(argv[4]) );

  LabelObjectValuatorType::Pointer valuator = LabelObjectValuatorType::New();
  valuator->SetInput( labelizer->GetOutput() );
  valuator->SetFeatureImage( reader2->GetOutput() );
  valuator->SetLabelImage( reader->GetOutput() );
  valuator->SetComputeHistogram( false );

  KeepNObjectsType::Pointer opening = KeepNObjectsType::New();
  opening->SetInput( valuator->GetOutput() );
  opening->SetNumberOfObjects( atoi(argv[5]) );
  opening->SetReverseOrdering( atoi(argv[6]) );
  opening->SetAttribute( argv[7] );

   BinarizerType::Pointer binarizer = BinarizerType::New();
  binarizer->SetInput( opening->GetOutput() );

  /*
  typedef itk::LabelStatisticsKeepNObjectsImageFilter< IType, IType > LabelOpeningType;
  LabelOpeningType::Pointer opening = LabelOpeningType::New();
  opening->SetInput( reader->GetOutput() );
  opening->SetFeatureImage( reader2->GetOutput() );
  opening->SetBackgroundValue( atoi(argv[4]) );
  opening->SetNumberOfObjects( atoi(argv[5]) );
  opening->SetReverseOrdering( atoi(argv[6]) );
  opening->SetAttribute( argv[7] );
  itk::SimpleFilterWatcher watcher(opening, "filter");
*/
  typedef itk::ImageFileWriter< IType > WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetInput( binarizer->GetOutput() );
  writer->SetFileName( argv[3] );
  writer->Update();
  return 0;
}

<commit_msg>COMP: Fixing conflicting names in Software Guide Generation<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt 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.

=========================================================================*/

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {MSLabeledOutput.tif}
//    OUTPUTS: {OBIAShapeAttribute1.txt}
//  Software Guide : EndCommandLineArgs

//  Software Guide : BeginLatex
//
//  This example shows the
//
//  Software Guide : EndLatex

// Software Guide : BeginCodeSnippet

// Software Guide : EndCodeSnippet
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkSimpleFilterWatcher.h"

//#include "itkLabelStatisticsKeepNObjectsImageFilter.h"

#include "itkLabelImageToLabelMapFilter.h"
#include "itkStatisticsLabelObject.h"
#include "itkStatisticsLabelMapFilter.h"
#include "itkStatisticsKeepNObjectsLabelMapFilter.h"
#include "itkLabelMapToLabelImageFilter.h"

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

  if( argc != 8 )
    {
    std::cerr << "usage: " << argv[0] << " input input output background nb reverseOrdering attribute" << std::endl;
    // std::cerr << "  : " << std::endl;
    exit(1);
    }

  const int dim = 3;

  typedef unsigned char PixelType;
  typedef itk::Image< PixelType, dim > IType;

  typedef itk::ImageFileReader< IType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );

  ReaderType::Pointer reader2 = ReaderType::New();
  reader2->SetFileName( argv[2] );

  typedef itk::StatisticsLabelObject<PixelType, dim> LabelObjectType;
  typedef  itk::LabelMap< LabelObjectType > LabelMapType;
    typedef  itk::LabelImageToLabelMapFilter< IType, LabelMapType > LabelizerType;

    typedef itk::StatisticsLabelMapFilter< LabelMapType, IType > LabelObjectValuatorType;
  typedef  LabelObjectType::AttributeType AttributeType;
  typedef  itk::StatisticsKeepNObjectsLabelMapFilter< LabelMapType > KeepNObjectsType;
  typedef  itk::LabelMapToLabelImageFilter< LabelMapType, IType > BinarizerType;

     LabelizerType::Pointer labelizer = LabelizerType::New();
  labelizer->SetInput( reader->GetOutput() );
  labelizer->SetBackgroundValue( atoi(argv[4]) );

  LabelObjectValuatorType::Pointer valuator = LabelObjectValuatorType::New();
  valuator->SetInput( labelizer->GetOutput() );
  valuator->SetFeatureImage( reader2->GetOutput() );
  valuator->SetLabelImage( reader->GetOutput() );
  valuator->SetComputeHistogram( false );

  KeepNObjectsType::Pointer opening = KeepNObjectsType::New();
  opening->SetInput( valuator->GetOutput() );
  opening->SetNumberOfObjects( atoi(argv[5]) );
  opening->SetReverseOrdering( atoi(argv[6]) );
  opening->SetAttribute( argv[7] );

   BinarizerType::Pointer binarizer = BinarizerType::New();
  binarizer->SetInput( opening->GetOutput() );

  /*
  typedef itk::LabelStatisticsKeepNObjectsImageFilter< IType, IType > LabelOpeningType;
  LabelOpeningType::Pointer opening = LabelOpeningType::New();
  opening->SetInput( reader->GetOutput() );
  opening->SetFeatureImage( reader2->GetOutput() );
  opening->SetBackgroundValue( atoi(argv[4]) );
  opening->SetNumberOfObjects( atoi(argv[5]) );
  opening->SetReverseOrdering( atoi(argv[6]) );
  opening->SetAttribute( argv[7] );
  itk::SimpleFilterWatcher watcher(opening, "filter");
*/
  typedef itk::ImageFileWriter< IType > WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetInput( binarizer->GetOutput() );
  writer->SetFileName( argv[3] );
  writer->Update();
  return 0;
}

<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkAbstractGraph.cxx

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

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

=========================================================================*/
/*----------------------------------------------------------------------------
 Copyright (c) Sandia Corporation
 See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/

#include "vtkAbstractGraph.h"
#include "vtkCellData.h"
#include "vtkGenericCell.h"
#include "vtkGraphIdList.h"
#include "vtkIdList.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkLine.h"
#include "vtkVertexLinks.h"
#include "vtkPointData.h"
#include "vtkPointLocator.h"
#include "vtkPoints.h"

#include <vtkstd/algorithm> // for sorting

//
// Standard functions
//

double vtkAbstractGraph::DefaultPoint[3] = {0, 0, 0};

vtkCxxRevisionMacro(vtkAbstractGraph, "1.6");

//----------------------------------------------------------------------------
vtkAbstractGraph::vtkAbstractGraph()
{
  this->Line = vtkLine::New();

  this->Information->Set(vtkDataObject::DATA_EXTENT_TYPE(), VTK_PIECES_EXTENT);
  this->Information->Set(vtkDataObject::DATA_PIECE_NUMBER(), -1);
  this->Information->Set(vtkDataObject::DATA_NUMBER_OF_PIECES(), 1);
  this->Information->Set(vtkDataObject::DATA_NUMBER_OF_GHOST_LEVELS(), 0);
}

//----------------------------------------------------------------------------
vtkAbstractGraph::~vtkAbstractGraph()
{
  if (this->Line)
    {
    this->Line->Delete();
    this->Line = NULL;
    }
}

//----------------------------------------------------------------------------
void vtkAbstractGraph::Initialize()
{
  this->Line->Delete();
  this->Line = vtkLine::New();
}

void vtkAbstractGraph::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}

//----------------------------------------------------------------------------
void vtkAbstractGraph::ShallowCopy(vtkDataObject *dataObject)
{
  // Do superclass
  this->Superclass::ShallowCopy(dataObject);
}

//----------------------------------------------------------------------------
void vtkAbstractGraph::DeepCopy(vtkDataObject *dataObject)
{
  // Do superclass
  this->Superclass::DeepCopy(dataObject);
}

//----------------------------------------------------------------------------
double* vtkAbstractGraph::GetPoint(vtkIdType ptId)
{
  if (this->Points)
    {
    return this->Points->GetPoint(ptId);
    }
  return this->DefaultPoint;
}

//----------------------------------------------------------------------------
void vtkAbstractGraph::GetPoint(vtkIdType ptId, double x[3])
{
  if (this->Points)
    {
    this->Points->GetPoint(ptId, x);
    }
  else
    {
    for (int i = 0; i < 3; i++)
      {
      x[i] = this->DefaultPoint[i];
      }
    }
}

//----------------------------------------------------------------------------
vtkPoints* vtkAbstractGraph::GetPoints()
{
  if (!this->Points)
    {
    this->Points = vtkPoints::New();
    }
  if (this->Points->GetNumberOfPoints() != this->GetNumberOfVertices())
    {
    this->Points->SetNumberOfPoints(this->GetNumberOfVertices());
    for (vtkIdType i = 0; i < this->GetNumberOfVertices(); i++)
      {
      this->Points->SetPoint(i, 0, 0, 0);
      }
    }
  return this->Points;
}

//----------------------------------------------------------------------------
vtkCell* vtkAbstractGraph::GetCell(vtkIdType cellId)
{
  double x[3];
  this->GetPoint(this->GetSourceVertex(cellId), x);
  this->Line->Points->SetPoint(0, x);
  this->GetPoint(this->GetTargetVertex(cellId), x);
  this->Line->Points->SetPoint(1, x);

  this->Line->PointIds->SetId(0, this->GetSourceVertex(cellId));
  this->Line->PointIds->SetId(1, this->GetTargetVertex(cellId));
  return this->Line;
}

//----------------------------------------------------------------------------
void vtkAbstractGraph::GetCell(vtkIdType cellId, vtkGenericCell * cell)
{
  cell->SetCellType(VTK_LINE);

  cell->Points->SetNumberOfPoints(2);
  double x[3];
  this->GetPoint(this->GetSourceVertex(cellId), x);
  cell->Points->SetPoint(0, x);
  this->GetPoint(this->GetTargetVertex(cellId), x);
  cell->Points->SetPoint(1, x);

  cell->PointIds->SetNumberOfIds(2);
  cell->PointIds->SetId(0, this->GetSourceVertex(cellId));
  cell->PointIds->SetId(1, this->GetTargetVertex(cellId));
}

//----------------------------------------------------------------------------
int vtkAbstractGraph::GetCellType(vtkIdType vtkNotUsed(cellId))
{
  return VTK_LINE;
}

//----------------------------------------------------------------------------
void vtkAbstractGraph::GetCellPoints(vtkIdType cellId, vtkIdList* ptIds)
{
  ptIds->Reset();
  ptIds->InsertNextId(this->GetSourceVertex(cellId));
  ptIds->InsertNextId(this->GetTargetVertex(cellId));
}

void vtkAbstractGraph::GetPointCells(vtkIdType ptId, vtkIdList* cellIds)
{
  cellIds->Reset();
  vtkGraphIdList* graphIds = vtkGraphIdList::New();
  this->GetIncidentEdges(ptId, graphIds);
  for (vtkIdType i = 0; i < graphIds->GetNumberOfIds(); i++)
    {
    cellIds->InsertNextId(graphIds->GetId(i));
    }
}

//----------------------------------------------------------------------------
vtkAbstractGraph* vtkAbstractGraph::GetData(vtkInformation* info)
{
  return info? vtkAbstractGraph::SafeDownCast(info->Get(DATA_OBJECT())) : 0;
}

//----------------------------------------------------------------------------
vtkAbstractGraph* vtkAbstractGraph::GetData(vtkInformationVector* v, int i)
{
  return vtkAbstractGraph::GetData(v->GetInformationObject(i));
}

<commit_msg>BUG: vtkAbstractGraph Initialize() should call parent class's Initialize().<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkAbstractGraph.cxx

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

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

=========================================================================*/
/*----------------------------------------------------------------------------
 Copyright (c) Sandia Corporation
 See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/

#include "vtkAbstractGraph.h"
#include "vtkCellData.h"
#include "vtkGenericCell.h"
#include "vtkGraphIdList.h"
#include "vtkIdList.h"
#include "vtkIdTypeArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkLine.h"
#include "vtkVertexLinks.h"
#include "vtkPointData.h"
#include "vtkPointLocator.h"
#include "vtkPoints.h"

#include <vtkstd/algorithm> // for sorting

//
// Standard functions
//

double vtkAbstractGraph::DefaultPoint[3] = {0, 0, 0};

vtkCxxRevisionMacro(vtkAbstractGraph, "1.7");

//----------------------------------------------------------------------------
vtkAbstractGraph::vtkAbstractGraph()
{
  this->Line = vtkLine::New();

  this->Information->Set(vtkDataObject::DATA_EXTENT_TYPE(), VTK_PIECES_EXTENT);
  this->Information->Set(vtkDataObject::DATA_PIECE_NUMBER(), -1);
  this->Information->Set(vtkDataObject::DATA_NUMBER_OF_PIECES(), 1);
  this->Information->Set(vtkDataObject::DATA_NUMBER_OF_GHOST_LEVELS(), 0);
}

//----------------------------------------------------------------------------
vtkAbstractGraph::~vtkAbstractGraph()
{
  if (this->Line)
    {
    this->Line->Delete();
    this->Line = NULL;
    }
}

//----------------------------------------------------------------------------
void vtkAbstractGraph::Initialize()
{
  this->Superclass::Initialize();
  this->Line->Delete();
  this->Line = vtkLine::New();
}

void vtkAbstractGraph::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}

//----------------------------------------------------------------------------
void vtkAbstractGraph::ShallowCopy(vtkDataObject *dataObject)
{
  // Do superclass
  this->Superclass::ShallowCopy(dataObject);
}

//----------------------------------------------------------------------------
void vtkAbstractGraph::DeepCopy(vtkDataObject *dataObject)
{
  // Do superclass
  this->Superclass::DeepCopy(dataObject);
}

//----------------------------------------------------------------------------
double* vtkAbstractGraph::GetPoint(vtkIdType ptId)
{
  if (this->Points)
    {
    return this->Points->GetPoint(ptId);
    }
  return this->DefaultPoint;
}

//----------------------------------------------------------------------------
void vtkAbstractGraph::GetPoint(vtkIdType ptId, double x[3])
{
  if (this->Points)
    {
    this->Points->GetPoint(ptId, x);
    }
  else
    {
    for (int i = 0; i < 3; i++)
      {
      x[i] = this->DefaultPoint[i];
      }
    }
}

//----------------------------------------------------------------------------
vtkPoints* vtkAbstractGraph::GetPoints()
{
  if (!this->Points)
    {
    this->Points = vtkPoints::New();
    }
  if (this->Points->GetNumberOfPoints() != this->GetNumberOfVertices())
    {
    this->Points->SetNumberOfPoints(this->GetNumberOfVertices());
    for (vtkIdType i = 0; i < this->GetNumberOfVertices(); i++)
      {
      this->Points->SetPoint(i, 0, 0, 0);
      }
    }
  return this->Points;
}

//----------------------------------------------------------------------------
vtkCell* vtkAbstractGraph::GetCell(vtkIdType cellId)
{
  double x[3];
  this->GetPoint(this->GetSourceVertex(cellId), x);
  this->Line->Points->SetPoint(0, x);
  this->GetPoint(this->GetTargetVertex(cellId), x);
  this->Line->Points->SetPoint(1, x);

  this->Line->PointIds->SetId(0, this->GetSourceVertex(cellId));
  this->Line->PointIds->SetId(1, this->GetTargetVertex(cellId));
  return this->Line;
}

//----------------------------------------------------------------------------
void vtkAbstractGraph::GetCell(vtkIdType cellId, vtkGenericCell * cell)
{
  cell->SetCellType(VTK_LINE);

  cell->Points->SetNumberOfPoints(2);
  double x[3];
  this->GetPoint(this->GetSourceVertex(cellId), x);
  cell->Points->SetPoint(0, x);
  this->GetPoint(this->GetTargetVertex(cellId), x);
  cell->Points->SetPoint(1, x);

  cell->PointIds->SetNumberOfIds(2);
  cell->PointIds->SetId(0, this->GetSourceVertex(cellId));
  cell->PointIds->SetId(1, this->GetTargetVertex(cellId));
}

//----------------------------------------------------------------------------
int vtkAbstractGraph::GetCellType(vtkIdType vtkNotUsed(cellId))
{
  return VTK_LINE;
}

//----------------------------------------------------------------------------
void vtkAbstractGraph::GetCellPoints(vtkIdType cellId, vtkIdList* ptIds)
{
  ptIds->Reset();
  ptIds->InsertNextId(this->GetSourceVertex(cellId));
  ptIds->InsertNextId(this->GetTargetVertex(cellId));
}

void vtkAbstractGraph::GetPointCells(vtkIdType ptId, vtkIdList* cellIds)
{
  cellIds->Reset();
  vtkGraphIdList* graphIds = vtkGraphIdList::New();
  this->GetIncidentEdges(ptId, graphIds);
  for (vtkIdType i = 0; i < graphIds->GetNumberOfIds(); i++)
    {
    cellIds->InsertNextId(graphIds->GetId(i));
    }
}

//----------------------------------------------------------------------------
vtkAbstractGraph* vtkAbstractGraph::GetData(vtkInformation* info)
{
  return info? vtkAbstractGraph::SafeDownCast(info->Get(DATA_OBJECT())) : 0;
}

//----------------------------------------------------------------------------
vtkAbstractGraph* vtkAbstractGraph::GetData(vtkInformationVector* v, int i)
{
  return vtkAbstractGraph::GetData(v->GetInformationObject(i));
}

<|endoftext|>


<commit_before>#include "Maze.h"

#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <time.h>
#include <queue>
#include <vector>

#include "Constants.h"
#include "Parameters.h"
#include "Tile.h"

namespace sim {

Maze::Maze(int width, int height, std::string mazeFileDirPath, std::string mazeFile) {

    // Misc errand - seed the random number generator
    srand(time(NULL));

    // Initialize the tile positions
    for (int x = 0; x < width; x++){
        std::vector<Tile> col;
        for (int y = 0; y < height; y++){
            Tile tile;
            tile.setPos(x, y);
            col.push_back(tile);
        }
        m_maze.push_back(col);
    }

    // Initialize the tile wall values and tile neighbors by either loading
    // an existing maze file or randomly generating a valid maze
    if (mazeFile == "") {

        std::cout << "No maze file provided. Generating random maze..." << std::endl;

        randomize();
        while (!(solveShortestPath().at(0) && solveShortestPath().at(1))) {
            randomize();
        }

        // Optional - can be used to generate more maze files
        saveMaze(mazeFileDirPath += "/auto_generated_maze.maz");
    }
    else {

        // Complete path to the given mazefile
        std::string path = mazeFileDirPath += mazeFile;

        // Check to see if the file exists
        std::fstream file(path.c_str());

        if (file){

            // Load the maze given by mazefile
            loadMaze(path);

            // Ensures that the maze is solvable
            if (!solveShortestPath().at(0)){
                std::cout << "Unsolvable Maze detected. Generating solvable maze..." << std::endl;
                while (!(solveShortestPath().at(0) && solveShortestPath().at(1))) {
                    randomize();
                }
            }
        }
        else{

            // If the file doesn't exist, generate a random maze file
            std::cout << "File \"" << path << "\" not found. Generating random maze..." << std::endl;
            randomize();
            while (!(solveShortestPath().at(0) && solveShortestPath().at(1))){
                randomize();
            }
        }
    }

    // Increment the passes for the starting position
    m_maze.at(0).at(0).incrementPasses();
}

Maze::~Maze()
{ }

int Maze::getWidth(){
    return m_maze.size();
}

int Maze::getHeight(){
    if (m_maze.size() > 0){
        return m_maze.at(0).size();
    }
    return 0;
}

Tile* Maze::getTile(int x, int y){
    return &m_maze.at(x).at(y);
}

void Maze::resetColors(int curX, int curY){
    for (int x = 0; x < getWidth(); x++){
        for (int y = 0; y < getHeight(); y++){
            getTile(x, y)->resetPasses();
        }
    }
    getTile(curX, curY)->incrementPasses();
}

void Maze::randomize(){

    // Declare width and height locally to reduce function calls
    int width = getWidth();
    int height = getHeight();

    // Percentage chance any one wall will exist
    float wallProb = 0.40;

    for (int x = 0; x < width; x++){
        for (int y = 0; y < height; y++){
            for (int k = 0; k < 4; k++){
                bool wallExists = (rand() <= (RAND_MAX * wallProb));
                switch (k){
                    case NORTH:
                        if (y + 1 < height){
                            getTile(x, y+1)->setWall(SOUTH, wallExists);
                            getTile(x, y)->setWall(NORTH, wallExists);
                        }
                        else {
                            getTile(x, y)->setWall(NORTH, true);
                        }
                        break;
                    case EAST:
                        if (x + 1 < width){
                            getTile(x+1, y)->setWall(WEST, wallExists);
                            getTile(x, y)->setWall(EAST, wallExists);
                        }
                        else {
                            getTile(x, y)->setWall(EAST, true);
                        }
                        break;
                    case SOUTH:
                        if (y > 0){
                            getTile(x, y-1)->setWall(NORTH, wallExists);
                            getTile(x, y)->setWall(SOUTH, wallExists);
                        }
                        else {
                            getTile(x, y)->setWall(SOUTH, true);
                        }
                        break;
                    case WEST:
                        if (x > 0){
                            getTile(x-1, y)->setWall(EAST, wallExists);
                            getTile(x, y)->setWall(WEST, wallExists);
                        }
                        else {
                            getTile(x, y)->setWall(WEST, true);
                        }
                        break;
                }
            }
        }
    }

	for (int x = 0; x < width-1; x++){ // Go Through all the pegs and make sure at least one wall
									   // exists per peg.  Makes the maze more regulation compliant
		for (int y = 0; y < height-1; y++){
			if (!getTile(x, y)->isWall(NORTH) &&
				!getTile(x, y)->isWall(EAST) &&			// If wall does not exist up, down, left, right
				!getTile(x + 1, y + 1)->isWall(WEST) && // from peg, add a peg in a random direction
				!getTile(x + 1, y + 1)->isWall(SOUTH)){
				switch (rand() / (RAND_MAX / 4 + 1)){
					case NORTH:
						getTile(x+1, y+1)->setWall(WEST, 1);
						getTile(x, y + 1)->setWall(EAST, 1);
						break;
					case EAST:
						getTile(x + 1, y + 1)->setWall(SOUTH, 1);
						getTile(x + 1, y)->setWall(NORTH, 1);
						break;
					case SOUTH:
						getTile(x,y)->setWall(EAST, 1);
						getTile(x+1,y)->setWall(WEST, 1);
						break;
					case WEST:
						getTile(x, y)->setWall(NORTH, 1);
						getTile(x, y + 1)->setWall(SOUTH, 1);
						break;
				}
			}
		}
	}

    // Ensures that the middle is hallowed out
    if (width % 2 == 0){
        if (height % 2 == 0){
            getTile(width/2-1, height/2-1)->setWall(NORTH, false);
            getTile(width/2-1, height/2)->setWall(SOUTH, false);
            getTile(width/2, height/2-1)->setWall(NORTH, false);
            getTile(width/2, height/2)->setWall(SOUTH, false);
            getTile(width/2-1, height/2-1)->setWall(EAST, false);
            getTile(width/2, height/2-1)->setWall(WEST, false);
        }
        getTile(width/2-1, height/2)->setWall(EAST, false);
        getTile(width/2, height/2)->setWall(WEST, false);

    }
    if (height % 2 == 0){
        getTile(width/2, height/2-1)->setWall(NORTH, false);
        getTile(width/2, height/2)->setWall(SOUTH, false);
    }

    // Once the walls are assigned, we can assign neighbors
    assignNeighbors();
}

void Maze::saveMaze(std::string mazeFile){

    // Create the stream
    std::ofstream file(mazeFile.c_str());

    if (file.is_open()){

        // Very primitive, but will work
        for (int x = 0; x <  getWidth(); x++){
            for (int y = 0; y < getHeight(); y++){
                file << x << " " << y;
                for (int k = 0; k < 4; k++){
                    file << " " << (getTile(x, y)->isWall(k) ? 1 : 0);
                }
                file << std::endl;
            }
        }

        file.close();
    }
}

void Maze::loadMaze(std::string mazeFile){

    // Create the stream
    std::ifstream file(mazeFile.c_str());

    // Initialize a string variable
    std::string line("");

    if (file.is_open()){

        // Very primitive, but will work
        while (getline(file, line)){
            std::istringstream iss(line);
            std::vector<std::string> tokens;
            copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(),
                 std::back_inserter<std::vector<std::string> >(tokens));
            for (int i = 0; i < 4; i++){ // Set the values of all of the walls
                getTile(atoi(tokens.at(0).c_str()), atoi(tokens.at(1).c_str()))
                      ->setWall(i, atoi(tokens.at(2+i).c_str()));
            }
        }

        file.close();

        // Once the walls are assigned, we can assign neighbors
        assignNeighbors();
    }
}

void Maze::assignNeighbors(){
    for (int x = 0; x < getWidth(); x++){
        for (int y = 0; y < getHeight(); y++){

            Tile* tile = getTile(x, y);

            // First we ensure that we have a fresh (empty) list
            tile->resetNeighbors();

            // Then we assign new neighbors
            if (!tile->isWall(NORTH)){
                tile->addNeighbor(getTile(x, y+1));
            }
            if (!tile->isWall(EAST)){
                tile->addNeighbor(getTile(x+1, y));
            }
            if (!tile->isWall(SOUTH)){
                tile->addNeighbor(getTile(x, y-1));
            }
            if (!tile->isWall(WEST)){
                tile->addNeighbor(getTile(x-1, y));
            }
        }
    }
}

void Maze::printDistances(){
    std::cout << std::endl;
    for (int y = getHeight()-1; y >= 0; y--){
        for (int x = 0; x < getWidth(); x++){
            if (getTile(x, y)->getDistance() < 100){
                std::cout << " ";
                if (getTile(x, y)->getDistance() < 10){
                    std::cout << " ";
                }
            }
            std::cout << getTile(x, y)->getDistance() << " ";
        }
        std::cout << std::endl;
    }
}

std::vector<bool> Maze::solveShortestPath(){

    // Solves the maze, assigns tiles that are part of the shortest path
    std::vector<Tile*> sp = findPathToCenter();
    for (int i = 0; i < sp.size(); i++){
        getTile(sp.at(i)->getX(), sp.at(i)->getY())->setPosp(true);
    }

    // Returns whether or not the maze is solvable and whether or not
    // it satisfies the minimum number of steps
    std::vector<bool> conditions;
    conditions.push_back(getClosestCenterTile()->getDistance() < MAX_DISTANCE);
    conditions.push_back(getClosestCenterTile()->getDistance() > MIN_MAZE_STEPS);
    return conditions;
}

std::vector<Tile*> Maze::findPath(int x1, int y1, int x2, int y2){
    setDistancesFrom(x1, x2);
    return backtrace(getTile(x2, y2));
}

std::vector<Tile*> Maze::findPathToCenter(){
    setDistancesFrom(0, 0);
    return backtrace(getClosestCenterTile());
}

std::vector<Tile*> Maze::backtrace(Tile* end){

    // The vector to hold the solution nodes
    std::vector<Tile*> path;

    // Start at the ending node and simply trace back through the values
    std::queue<Tile*> queue;
    queue.push(end);
    path.push_back(end);

    while (!queue.empty()){
        Tile* node = queue.front();
        queue.pop(); // Removes the element
        std::vector<Tile*> neighbors = node->getNeighbors();
        for (int i = 0; i < neighbors.size(); i++){
            if (neighbors.at(i)->getDistance() == node->getDistance() - 1){
                path.push_back(neighbors.at(i));
                queue.push(neighbors.at(i));
            }
        }
    }

    return path;
}

void Maze::setDistancesFrom(int x, int y){

    // Ensure that the nodes are fresh every time this function is called
    for (int x = 0; x < getWidth(); x++){
        for (int y = 0; y < getHeight(); y++){
            Tile* tile = getTile(x, y);
            tile->setDistance(MAX_DISTANCE);
            tile->setExplored(false);
            tile->setPosp(false);
        }
    }

    // Queue for BFS
    std::queue<Tile*> queue;
    queue.push(getTile(x, y));
    getTile(x, y)->setDistance(0);
    getTile(x, y)->setExplored(true);

    while (!queue.empty()){
        Tile* node = queue.front();
        queue.pop(); // Removes the element
        std::vector<Tile*> neighbors = node->getNeighbors();
        for (int i = 0; i < neighbors.size(); i++){
            if (!neighbors.at(i)->getExplored()){
                neighbors.at(i)->setDistance(node->getDistance() + 1);
                queue.push(neighbors.at(i));
                neighbors.at(i)->setExplored(true);
            }
        }
    }
}

Tile* Maze::getClosestCenterTile(){

    if (getWidth() > 0 && getHeight() > 0){

        int midWidth = getWidth()/2;
        int midHeight = getHeight()/2;
        Tile* closest = getTile(midWidth, midHeight);

        if (getWidth() % 2 == 0){
            if (getTile(midWidth-1, midHeight)->getDistance() < closest->getDistance()){
                closest = getTile(midWidth-1, midHeight);
            }
        }
        if (getHeight() % 2 == 0){
            if (getTile(midWidth, midHeight-1)->getDistance() < closest->getDistance()){
                closest = getTile(midWidth, midHeight-1);
            }
        }
        if (getWidth() % 2 == 0 && getHeight() % 2 == 0){
            if (getTile(midWidth-1, midHeight-1)->getDistance() < closest->getDistance()){
                closest = getTile(midWidth-1, midHeight-1);
            }
        }

        return closest;
    }

    // If either the width or the height is zero return NULL
    return NULL;
}

} // namespace sim
<commit_msg>Made change to be more like surrounding code<commit_after>#include "Maze.h"

#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <time.h>
#include <queue>
#include <vector>

#include "Constants.h"
#include "Parameters.h"
#include "Tile.h"

namespace sim {

Maze::Maze(int width, int height, std::string mazeFileDirPath, std::string mazeFile) {

    // Misc errand - seed the random number generator
    srand(time(NULL));

    // Initialize the tile positions
    for (int x = 0; x < width; x++){
        std::vector<Tile> col;
        for (int y = 0; y < height; y++){
            Tile tile;
            tile.setPos(x, y);
            col.push_back(tile);
        }
        m_maze.push_back(col);
    }

    // Initialize the tile wall values and tile neighbors by either loading
    // an existing maze file or randomly generating a valid maze
    if (mazeFile == "") {

        std::cout << "No maze file provided. Generating random maze..." << std::endl;

        randomize();
        while (!(solveShortestPath().at(0) && solveShortestPath().at(1))) {
            randomize();
        }

        // Optional - can be used to generate more maze files
        saveMaze(mazeFileDirPath += "/auto_generated_maze.maz");
    }
    else {

        // Complete path to the given mazefile
        std::string path = mazeFileDirPath += mazeFile;

        // Check to see if the file exists
        std::fstream file(path.c_str());

        if (file){

            // Load the maze given by mazefile
            loadMaze(path);

            // Ensures that the maze is solvable
            if (!solveShortestPath().at(0)){
                std::cout << "Unsolvable Maze detected. Generating solvable maze..." << std::endl;
                while (!(solveShortestPath().at(0) && solveShortestPath().at(1))) {
                    randomize();
                }
            }
        }
        else{

            // If the file doesn't exist, generate a random maze file
            std::cout << "File \"" << path << "\" not found. Generating random maze..." << std::endl;
            randomize();
            while (!(solveShortestPath().at(0) && solveShortestPath().at(1))){
                randomize();
            }
        }
    }

    // Increment the passes for the starting position
    m_maze.at(0).at(0).incrementPasses();
}

Maze::~Maze()
{ }

int Maze::getWidth(){
    return m_maze.size();
}

int Maze::getHeight(){
    if (m_maze.size() > 0){
        return m_maze.at(0).size();
    }
    return 0;
}

Tile* Maze::getTile(int x, int y){
    return &m_maze.at(x).at(y);
}

void Maze::resetColors(int curX, int curY){
    for (int x = 0; x < getWidth(); x++){
        for (int y = 0; y < getHeight(); y++){
            getTile(x, y)->resetPasses();
        }
    }
    getTile(curX, curY)->incrementPasses();
}

void Maze::randomize(){

    // Declare width and height locally to reduce function calls
    int width = getWidth();
    int height = getHeight();

    // Percentage chance any one wall will exist
    float wallProb = 0.40;

    for (int x = 0; x < width; x++){
        for (int y = 0; y < height; y++){
            for (int k = 0; k < 4; k++){
                bool wallExists = (rand() <= (RAND_MAX * wallProb));
                switch (k){
                    case NORTH:
                        if (y + 1 < height){
                            getTile(x, y+1)->setWall(SOUTH, wallExists);
                            getTile(x, y)->setWall(NORTH, wallExists);
                        }
                        else {
                            getTile(x, y)->setWall(NORTH, true);
                        }
                        break;
                    case EAST:
                        if (x + 1 < width){
                            getTile(x+1, y)->setWall(WEST, wallExists);
                            getTile(x, y)->setWall(EAST, wallExists);
                        }
                        else {
                            getTile(x, y)->setWall(EAST, true);
                        }
                        break;
                    case SOUTH:
                        if (y > 0){
                            getTile(x, y-1)->setWall(NORTH, wallExists);
                            getTile(x, y)->setWall(SOUTH, wallExists);
                        }
                        else {
                            getTile(x, y)->setWall(SOUTH, true);
                        }
                        break;
                    case WEST:
                        if (x > 0){
                            getTile(x-1, y)->setWall(EAST, wallExists);
                            getTile(x, y)->setWall(WEST, wallExists);
                        }
                        else {
                            getTile(x, y)->setWall(WEST, true);
                        }
                        break;
                }
            }
        }
    }

	for (int x = 0; x < width-1; x++){ // Go Through all the pegs and make sure at least one wall
									   // exists per peg.  Makes the maze more regulation compliant
		for (int y = 0; y < height-1; y++){
			if (!getTile(x, y)->isWall(NORTH) &&
				!getTile(x, y)->isWall(EAST) &&			// If wall does not exist up, down, left, right
				!getTile(x + 1, y + 1)->isWall(WEST) && // from peg, add a peg in a random direction
				!getTile(x + 1, y + 1)->isWall(SOUTH)){
				switch (rand() / (RAND_MAX / 4 + 1)){
					case NORTH:
						getTile(x + 1, y + 1)->setWall(WEST, true);
						getTile(x, y + 1)->setWall(EAST, true);
						break;
					case EAST:
						getTile(x + 1, y + 1)->setWall(SOUTH, true);
						getTile(x + 1, y)->setWall(NORTH, true);
						break;
					case SOUTH:
						getTile(x,y)->setWall(EAST, true);
						getTile(x + 1,y)->setWall(WEST, true);
						break;
					case WEST:
						getTile(x, y)->setWall(NORTH, true);
						getTile(x, y + 1)->setWall(SOUTH, true);
						break;
				}
			}
		}
	}

    // Ensures that the middle is hallowed out
    if (width % 2 == 0){
        if (height % 2 == 0){
            getTile(width/2-1, height/2-1)->setWall(NORTH, false);
            getTile(width/2-1, height/2)->setWall(SOUTH, false);
            getTile(width/2, height/2-1)->setWall(NORTH, false);
            getTile(width/2, height/2)->setWall(SOUTH, false);
            getTile(width/2-1, height/2-1)->setWall(EAST, false);
            getTile(width/2, height/2-1)->setWall(WEST, false);
        }
        getTile(width/2-1, height/2)->setWall(EAST, false);
        getTile(width/2, height/2)->setWall(WEST, false);

    }
    if (height % 2 == 0){
        getTile(width/2, height/2-1)->setWall(NORTH, false);
        getTile(width/2, height/2)->setWall(SOUTH, false);
    }

    // Once the walls are assigned, we can assign neighbors
    assignNeighbors();
}

void Maze::saveMaze(std::string mazeFile){

    // Create the stream
    std::ofstream file(mazeFile.c_str());

    if (file.is_open()){

        // Very primitive, but will work
        for (int x = 0; x <  getWidth(); x++){
            for (int y = 0; y < getHeight(); y++){
                file << x << " " << y;
                for (int k = 0; k < 4; k++){
                    file << " " << (getTile(x, y)->isWall(k) ? 1 : 0);
                }
                file << std::endl;
            }
        }

        file.close();
    }
}

void Maze::loadMaze(std::string mazeFile){

    // Create the stream
    std::ifstream file(mazeFile.c_str());

    // Initialize a string variable
    std::string line("");

    if (file.is_open()){

        // Very primitive, but will work
        while (getline(file, line)){
            std::istringstream iss(line);
            std::vector<std::string> tokens;
            copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(),
                 std::back_inserter<std::vector<std::string> >(tokens));
            for (int i = 0; i < 4; i++){ // Set the values of all of the walls
                getTile(atoi(tokens.at(0).c_str()), atoi(tokens.at(1).c_str()))
                      ->setWall(i, atoi(tokens.at(2+i).c_str()));
            }
        }

        file.close();

        // Once the walls are assigned, we can assign neighbors
        assignNeighbors();
    }
}

void Maze::assignNeighbors(){
    for (int x = 0; x < getWidth(); x++){
        for (int y = 0; y < getHeight(); y++){

            Tile* tile = getTile(x, y);

            // First we ensure that we have a fresh (empty) list
            tile->resetNeighbors();

            // Then we assign new neighbors
            if (!tile->isWall(NORTH)){
                tile->addNeighbor(getTile(x, y+1));
            }
            if (!tile->isWall(EAST)){
                tile->addNeighbor(getTile(x+1, y));
            }
            if (!tile->isWall(SOUTH)){
                tile->addNeighbor(getTile(x, y-1));
            }
            if (!tile->isWall(WEST)){
                tile->addNeighbor(getTile(x-1, y));
            }
        }
    }
}

void Maze::printDistances(){
    std::cout << std::endl;
    for (int y = getHeight()-1; y >= 0; y--){
        for (int x = 0; x < getWidth(); x++){
            if (getTile(x, y)->getDistance() < 100){
                std::cout << " ";
                if (getTile(x, y)->getDistance() < 10){
                    std::cout << " ";
                }
            }
            std::cout << getTile(x, y)->getDistance() << " ";
        }
        std::cout << std::endl;
    }
}

std::vector<bool> Maze::solveShortestPath(){

    // Solves the maze, assigns tiles that are part of the shortest path
    std::vector<Tile*> sp = findPathToCenter();
    for (int i = 0; i < sp.size(); i++){
        getTile(sp.at(i)->getX(), sp.at(i)->getY())->setPosp(true);
    }

    // Returns whether or not the maze is solvable and whether or not
    // it satisfies the minimum number of steps
    std::vector<bool> conditions;
    conditions.push_back(getClosestCenterTile()->getDistance() < MAX_DISTANCE);
    conditions.push_back(getClosestCenterTile()->getDistance() > MIN_MAZE_STEPS);
    return conditions;
}

std::vector<Tile*> Maze::findPath(int x1, int y1, int x2, int y2){
    setDistancesFrom(x1, x2);
    return backtrace(getTile(x2, y2));
}

std::vector<Tile*> Maze::findPathToCenter(){
    setDistancesFrom(0, 0);
    return backtrace(getClosestCenterTile());
}

std::vector<Tile*> Maze::backtrace(Tile* end){

    // The vector to hold the solution nodes
    std::vector<Tile*> path;

    // Start at the ending node and simply trace back through the values
    std::queue<Tile*> queue;
    queue.push(end);
    path.push_back(end);

    while (!queue.empty()){
        Tile* node = queue.front();
        queue.pop(); // Removes the element
        std::vector<Tile*> neighbors = node->getNeighbors();
        for (int i = 0; i < neighbors.size(); i++){
            if (neighbors.at(i)->getDistance() == node->getDistance() - 1){
                path.push_back(neighbors.at(i));
                queue.push(neighbors.at(i));
            }
        }
    }

    return path;
}

void Maze::setDistancesFrom(int x, int y){

    // Ensure that the nodes are fresh every time this function is called
    for (int x = 0; x < getWidth(); x++){
        for (int y = 0; y < getHeight(); y++){
            Tile* tile = getTile(x, y);
            tile->setDistance(MAX_DISTANCE);
            tile->setExplored(false);
            tile->setPosp(false);
        }
    }

    // Queue for BFS
    std::queue<Tile*> queue;
    queue.push(getTile(x, y));
    getTile(x, y)->setDistance(0);
    getTile(x, y)->setExplored(true);

    while (!queue.empty()){
        Tile* node = queue.front();
        queue.pop(); // Removes the element
        std::vector<Tile*> neighbors = node->getNeighbors();
        for (int i = 0; i < neighbors.size(); i++){
            if (!neighbors.at(i)->getExplored()){
                neighbors.at(i)->setDistance(node->getDistance() + 1);
                queue.push(neighbors.at(i));
                neighbors.at(i)->setExplored(true);
            }
        }
    }
}

Tile* Maze::getClosestCenterTile(){

    if (getWidth() > 0 && getHeight() > 0){

        int midWidth = getWidth()/2;
        int midHeight = getHeight()/2;
        Tile* closest = getTile(midWidth, midHeight);

        if (getWidth() % 2 == 0){
            if (getTile(midWidth-1, midHeight)->getDistance() < closest->getDistance()){
                closest = getTile(midWidth-1, midHeight);
            }
        }
        if (getHeight() % 2 == 0){
            if (getTile(midWidth, midHeight-1)->getDistance() < closest->getDistance()){
                closest = getTile(midWidth, midHeight-1);
            }
        }
        if (getWidth() % 2 == 0 && getHeight() % 2 == 0){
            if (getTile(midWidth-1, midHeight-1)->getDistance() < closest->getDistance()){
                closest = getTile(midWidth-1, midHeight-1);
            }
        }

        return closest;
    }

    // If either the width or the height is zero return NULL
    return NULL;
}

} // namespace sim
<|endoftext|>


<commit_before>/**
 * \file dcs/system/posix_process.hpp
 *
 * \brief Class to create and manage a process in POSIX-compliant systems.
 *
 * \author Marco Guazzone (marco.guazzone@gmail.com)
 *
 *

 *
 * Copyright (C) 2012       Marco Guazzone
 *                          [Distributed Computing System (DCS) Group,
 *                           Computer Science Institute,
 *                           Department of Science and Technological Innovation,
 *                           University of Piemonte Orientale,
 *                           Alessandria (Italy)]
 *
 * This file is part of dcsxx-commons.
 *
 * dcsxx-commons is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * dcsxx-commons 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with dcsxx-commons.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef DCS_SYSTEM_POSIX_PROCESS_HPP
#define DCS_SYSTEM_POSIX_PROCESS_HPP

//TODO: How to check for a POSIX-compliant system?
//
//FIXME: It seems this is not the best way to check for a POSIX-compliant system
//#if _POSIX_C_SOURCE < 1 && !_XOPEN_SOURCE && !_POSIX_SOURCE
//# error "Unable to find a POSIX compliant system."
//#endif // _POSIX_C_SOURCE

#include <cerrno>
#include <cstddef>
#include <cstring>
#include <dcs/debug.hpp>
#include <dcs/exception.hpp>
#include <dcs/logging.hpp>
#include <dcs/system/process_status_category.hpp>
#include <fcntl.h>
#include <iterator>
#include <sstream>
#include <stdexcept>
#include <string>
#include <sys/resource.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>

namespace dcs { namespace system {

class posix_process
{
	private: static const unsigned int zzz_secs_ = 5;

	public: explicit posix_process(::std::string const& cmd)
	: cmd_(cmd),
//	  args_(),
	  async_(false),
	  pid_(-1),
	  status_(undefined_process_status),
	  sig_(-1),
	  exit_status_(EXIT_SUCCESS)
	{
	}

//	public: template <typename FwdIterT>
//			posix_process(::std::string const& cmd, FwdIterT arg_first, FwdIterT arg_last)
//	: cmd_(cmd),
//	  args_(arg_first, arg_last),
//	  async_(false),
//	  status_(undefined_status),
//	  sig_(-1),
//	  exit_status_(EXIT_SUCCESS)
//	{
//	}

	public: ~posix_process()
	{
		// Wait for child termination to prevent zombies
		try
		{
			this->wait();
		}
		catch (...)
		{
			::std::ostringstream oss;
			oss << "Failed to wait for command '" << cmd_ << "'";
			dcs::log_error(DCS_LOGGING_AT, oss.str());
		}
	}

	public: void asynch(bool val)
	{
		async_ = val;
	}

	public: template <typename FwdIterT>
			void run(FwdIterT arg_first, FwdIterT arg_last)
	{
		::pid_t pid = ::fork();

		if (pid == -1)
		{
			::std::ostringstream oss;
			oss << "Call to fork(2) failed for command '" << cmd_ << "': " << ::strerror(errno);

			DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
		}

		if (pid == 0)
		{
			// The child

			// Get the maximum number of files this process is allowed to open
#if defined(F_MAXFD)
			int maxdescs = ::fcntl(-1, F_MAXFD, 0);
			if (maxdescs == -1)
			{
# if defined(_SC_OPEN_MAX)
            	maxdescs = ::sysconf(_SC_OPEN_MAX);
# else // _SC_OPEN_MAX
				::rlimit limit;
				if (::getrlimit(RLIMIT_NOFILE, &limit) < 0)
				{
					::std::ostringstream oss;
					oss << "Call to getrlimit(2) failed for command '" << cmd_ << "': " << ::strerror(errno);

					DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
				}
				maxdescs = limit.rlim_cur;
# endif // _SC_OPEN_MAX
			}
#else // F_MAXFD
# if defined(_SC_OPEN_MAX)
			int maxdescs = ::sysconf(_SC_OPEN_MAX);
# else // _SC_OPEN_MAX
			::rlimit limit;
			if (::getrlimit(RLIMIT_NOFILE, &limit) < 0)
			{
				::std::ostringstream oss;
				oss << "Call to getrlimit(2) failed for command '" << cmd_ << "': " << ::strerror(errno);

				DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
			}
			maxdescs = limit.rlim_cur;
# endif // _SC_OPEN_MAX
#endif // F_MAXFD
			if (maxdescs == -1)
			{
				maxdescs = 1024;
			}

			// Check if the command already has path information
			::std::string cmd_path;
			::std::string cmd_name;
			typename ::std::string::size_type pos;
			pos = cmd_.find_last_of('/');
			if (pos != ::std::string::npos)
			{
				cmd_path = cmd_.substr(0, pos);
				cmd_name = cmd_.substr(pos+1);
			}

			// Populate the argument list
			::std::size_t nargs = ::std::distance(arg_first, arg_last)+2;
			char** argv = new char*[nargs];
			argv[0] = new char[cmd_name.size()+1];
			::std::strncpy(argv[0], cmd_name.c_str(), cmd_name.size()+1); // by convention, the first argument is always the command name
			::std::size_t i(1);
			while (arg_first != arg_last)
			{
				argv[i] = new char[arg_first->size()+1];
				::std::strncpy(argv[i], arg_first->c_str(), arg_first->size()+1);
				++arg_first;
				++i;
			}
			argv[i] = 0; // The array of pointers must be terminated by a NULL pointer.

			// Close unused file descriptors
			for (int fd = 0; fd < maxdescs; ++fd)
			{
#ifdef DCS_DEBUG
				// Keep standard error open for debug
				if (fd != STDERR_FILENO)
				{
					::close(fd);
				}
#else // DCS_DEBUG
				::close(fd);
#endif // DCS_DEBUG
			}

			// Run the command
			::execvp(cmd_.c_str(), argv);

			// Actually we should delete argv and envp data. As we must not
			// call any non-async-signal-safe functions though we simply exit.
			::write(STDERR_FILENO, "execvp() failed\n", 17);
			_exit(EXIT_FAILURE);
		}

		// The parent

		pid_ = pid;
		status_ = running_process_status;

		if (!async_)
		{
			this->wait();
		}
	}

	public: void wait()
	{
		int wstatus;

		if (::waitpid(pid_, &wstatus, WUNTRACED | WCONTINUED) == -1)
		{
			::std::ostringstream oss;
			oss << "Call to waitpid(2) failed for command '" << cmd_ << "': " << ::strerror(errno);

			DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
		}

		if (WIFEXITED(wstatus))
		{
			exit_status_ = WEXITSTATUS(wstatus);
			if (exit_status_ != EXIT_SUCCESS)
			{
				status_ = failed_process_status;

				::std::ostringstream oss;
				oss << "Command '" << cmd_ << "' exited with status: " << exit_status_;
				dcs::log_warn(DCS_LOGGING_AT, oss.str());
			}
			else
			{
				status_ = terminated_process_status;
			}
		}
		else if (WIFSTOPPED(wstatus))
		{
			status_ = stopped_process_status;
			sig_ = WSTOPSIG(wstatus);
		}
		else if (WIFCONTINUED(wstatus))
		{
			status_ = resumed_process_status;
		}
		else if (WIFSIGNALED(wstatus))
		{
			sig_ = WTERMSIG(wstatus);
			status_ = aborted_process_status;

			::std::ostringstream oss;
			oss << "Command '" << cmd_ << "' signaled with signal: " << sig_;
			dcs::log_warn(DCS_LOGGING_AT, oss.str());
		}
		else
		{
			status_ = aborted_process_status;

			::std::ostringstream oss;
			oss << "Command '" << cmd_ << "' failed for an unknown reason";
			dcs::log_error(DCS_LOGGING_AT, oss.str());
		}
	}

	public: process_status_category status() const
	{
		return status_;
	}

	public: void stop()
	{
		// pre: process must be running
		DCS_ASSERT(status_ == running_process_status,
				   DCS_EXCEPTION_THROW(::std::runtime_error,
									   "Cannot stop a process that is not running"));

		this->kill(SIGSTOP);
	}

	public: void resume()
	{
		// pre: process must have been stopped
		DCS_ASSERT(status_ == stopped_process_status,
				   DCS_EXCEPTION_THROW(::std::runtime_error,
									   "Cannot resume a process that has not been stopped"));

		this->kill(SIGCONT);
	}

	public: void terminate()
	{
		// pre: process must be running
		DCS_ASSERT(status_ == running_process_status,
				   DCS_EXCEPTION_THROW(::std::runtime_error,
									   "Cannot stop a process that is not running"));

		this->kill(SIGTERM);
		::sleep(zzz_secs_);
		if (this->alive())
		{
			this->kill(SIGKILL);
		}
		this->wait();
	}

	public: bool alive() const
	{
		if (::kill(pid_, 0) == -1)
		{
			if (errno != ESRCH)
			{
				::std::ostringstream oss;
				oss << "Call to kill(2) failed for command '" << cmd_ << "' and signal 0: " << ::strerror(errno);

				DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
			}

			return false;
		}

		return true;
	}

	public: void kill(int sig)
	{
		// pre: sig >= 0
		DCS_ASSERT(sig >= 0,
				   DCS_EXCEPTION_THROW(::std::invalid_argument,
									   "Invalid signal number"));

		// signal 0 has a special meaning: it can be used to check if a process
		// exists without actually sending any signal to it.
		// To send such a signal, use method \c exist.
		if (sig == 0)
		{
			return;
		}

		if (::kill(pid_, sig) == -1)
		{
			::std::ostringstream oss;
			oss << "Call to kill(2) failed for command '" << cmd_ << "' and signal " << sig << ": " << ::strerror(errno);

			DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
		}

		sig_ = sig;
		switch (sig)
		{
			case SIGCONT:
				status_ = resumed_process_status;
				break;
			case SIGSTOP:
				status_ = stopped_process_status;
				break;
			case SIGTERM:
			case SIGKILL:
				status_ = terminated_process_status;
				break;
			case SIGINT:
				status_ = aborted_process_status;
				break;
			default:
				::sleep(zzz_secs_);
				if (!this->alive())
				{
					status_ = aborted_process_status;
				}
				break;
		}
	}

	private: ::std::string cmd_; ///< The command path
//	private: ::std::vector< ::std::string > args_; ///< The list of command arguments
	private: bool async_; ///< A \c true value means that the parent does not block to wait for child termination
	private: ::pid_t pid_; ///< The process identifier
	private: process_status_category status_; ///< The current status of this process
	private: int sig_; ///< The last signal sent to this process
	private: int exit_status_; ///< The exit status of this process
}; // posix_process

}} // Namespace dcs::system

#endif // DCS_SYSTEM_POSIX_PROCESS_HPP
<commit_msg>(change:minor) Improved error message in case of execution failure.<commit_after>/**
 * \file dcs/system/posix_process.hpp
 *
 * \brief Class to create and manage a process in POSIX-compliant systems.
 *
 * \author Marco Guazzone (marco.guazzone@gmail.com)
 *
 *

 *
 * Copyright (C) 2012       Marco Guazzone
 *                          [Distributed Computing System (DCS) Group,
 *                           Computer Science Institute,
 *                           Department of Science and Technological Innovation,
 *                           University of Piemonte Orientale,
 *                           Alessandria (Italy)]
 *
 * This file is part of dcsxx-commons.
 *
 * dcsxx-commons is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * dcsxx-commons 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with dcsxx-commons.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef DCS_SYSTEM_POSIX_PROCESS_HPP
#define DCS_SYSTEM_POSIX_PROCESS_HPP

//TODO: How to check for a POSIX-compliant system?
//
//FIXME: It seems this is not the best way to check for a POSIX-compliant system
//#if _POSIX_C_SOURCE < 1 && !_XOPEN_SOURCE && !_POSIX_SOURCE
//# error "Unable to find a POSIX compliant system."
//#endif // _POSIX_C_SOURCE

#include <cerrno>
#include <cstddef>
#include <cstring>
#include <dcs/debug.hpp>
#include <dcs/exception.hpp>
#include <dcs/logging.hpp>
#include <dcs/system/process_status_category.hpp>
#include <fcntl.h>
#include <iterator>
#include <sstream>
#include <stdexcept>
#include <string>
#include <sys/resource.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <vector>

namespace dcs { namespace system {

class posix_process
{
	private: static const unsigned int zzz_secs_ = 5;

	public: explicit posix_process(::std::string const& cmd)
	: cmd_(cmd),
//	  args_(),
	  async_(false),
	  pid_(-1),
	  status_(undefined_process_status),
	  sig_(-1),
	  exit_status_(EXIT_SUCCESS)
	{
	}

//	public: template <typename FwdIterT>
//			posix_process(::std::string const& cmd, FwdIterT arg_first, FwdIterT arg_last)
//	: cmd_(cmd),
//	  args_(arg_first, arg_last),
//	  async_(false),
//	  status_(undefined_status),
//	  sig_(-1),
//	  exit_status_(EXIT_SUCCESS)
//	{
//	}

	public: ~posix_process()
	{
		// Wait for child termination to prevent zombies
		try
		{
			this->wait();
		}
		catch (...)
		{
			::std::ostringstream oss;
			oss << "Failed to wait for command '" << cmd_ << "'";
			dcs::log_error(DCS_LOGGING_AT, oss.str());
		}
	}

	public: void asynch(bool val)
	{
		async_ = val;
	}

	public: template <typename FwdIterT>
			void run(FwdIterT arg_first, FwdIterT arg_last)
	{
		::pid_t pid = ::fork();

		if (pid == -1)
		{
			::std::ostringstream oss;
			oss << "Call to fork(2) failed for command '" << cmd_ << "': " << ::strerror(errno);

			DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
		}

		if (pid == 0)
		{
			// The child

			// Get the maximum number of files this process is allowed to open
#if defined(F_MAXFD)
			int maxdescs = ::fcntl(-1, F_MAXFD, 0);
			if (maxdescs == -1)
			{
# if defined(_SC_OPEN_MAX)
            	maxdescs = ::sysconf(_SC_OPEN_MAX);
# else // _SC_OPEN_MAX
				::rlimit limit;
				if (::getrlimit(RLIMIT_NOFILE, &limit) < 0)
				{
					::std::ostringstream oss;
					oss << "Call to getrlimit(2) failed for command '" << cmd_ << "': " << ::strerror(errno);

					DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
				}
				maxdescs = limit.rlim_cur;
# endif // _SC_OPEN_MAX
			}
#else // F_MAXFD
# if defined(_SC_OPEN_MAX)
			int maxdescs = ::sysconf(_SC_OPEN_MAX);
# else // _SC_OPEN_MAX
			::rlimit limit;
			if (::getrlimit(RLIMIT_NOFILE, &limit) < 0)
			{
				::std::ostringstream oss;
				oss << "Call to getrlimit(2) failed for command '" << cmd_ << "': " << ::strerror(errno);

				DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
			}
			maxdescs = limit.rlim_cur;
# endif // _SC_OPEN_MAX
#endif // F_MAXFD
			if (maxdescs == -1)
			{
				maxdescs = 1024;
			}

			// Check if the command already has path information
			::std::string cmd_path;
			::std::string cmd_name;
			typename ::std::string::size_type pos;
			pos = cmd_.find_last_of('/');
			if (pos != ::std::string::npos)
			{
				cmd_path = cmd_.substr(0, pos);
				cmd_name = cmd_.substr(pos+1);
			}

			// Populate the argument list
			::std::size_t nargs = ::std::distance(arg_first, arg_last)+2;
			char** argv = new char*[nargs];
			argv[0] = new char[cmd_name.size()+1];
			::std::strncpy(argv[0], cmd_name.c_str(), cmd_name.size()+1); // by convention, the first argument is always the command name
			::std::size_t i(1);
			while (arg_first != arg_last)
			{
				argv[i] = new char[arg_first->size()+1];
				::std::strncpy(argv[i], arg_first->c_str(), arg_first->size()+1);
				++arg_first;
				++i;
			}
			argv[i] = 0; // The array of pointers must be terminated by a NULL pointer.

			// Close unused file descriptors
			for (int fd = 0; fd < maxdescs; ++fd)
			{
#ifdef DCS_DEBUG
				// Keep standard error open for debug
				if (fd != STDERR_FILENO)
				{
					::close(fd);
				}
#else // DCS_DEBUG
				::close(fd);
#endif // DCS_DEBUG
			}

			// Run the command
			DCS_DEBUG_TRACE("Going to run: " << cmd_ << ::dcs::debug::to_string(argv, argv+nargs-1) );
			::execvp(cmd_.c_str(), argv);

			// Actually we should delete argv and envp data. As we must not
			// call any non-async-signal-safe functions though we simply exit.
			::std::ostringstream oss;
			oss << "Call to execvp(3) failed for command '" << cmd_ << "': " << ::strerror(errno) << ::std::endl;
			::std::size_t count(oss.str().size());
			::write(STDERR_FILENO, oss.str().c_str(), count);
			::_exit(EXIT_FAILURE);
		}

		// The parent

		pid_ = pid;
		status_ = running_process_status;

		if (!async_)
		{
			this->wait();
		}
	}

	public: void wait()
	{
		int wstatus;

		if (::waitpid(pid_, &wstatus, WUNTRACED | WCONTINUED) == -1)
		{
			::std::ostringstream oss;
			oss << "Call to waitpid(2) failed for command '" << cmd_ << "': " << ::strerror(errno);

			DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
		}

		if (WIFEXITED(wstatus))
		{
			exit_status_ = WEXITSTATUS(wstatus);
			if (exit_status_ != EXIT_SUCCESS)
			{
				status_ = failed_process_status;

				::std::ostringstream oss;
				oss << "Command '" << cmd_ << "' exited with status: " << exit_status_;
				dcs::log_warn(DCS_LOGGING_AT, oss.str());
			}
			else
			{
				status_ = terminated_process_status;
			}
		}
		else if (WIFSTOPPED(wstatus))
		{
			status_ = stopped_process_status;
			sig_ = WSTOPSIG(wstatus);
		}
		else if (WIFCONTINUED(wstatus))
		{
			status_ = resumed_process_status;
		}
		else if (WIFSIGNALED(wstatus))
		{
			sig_ = WTERMSIG(wstatus);
			status_ = aborted_process_status;

			::std::ostringstream oss;
			oss << "Command '" << cmd_ << "' signaled with signal: " << sig_;
			dcs::log_warn(DCS_LOGGING_AT, oss.str());
		}
		else
		{
			status_ = aborted_process_status;

			::std::ostringstream oss;
			oss << "Command '" << cmd_ << "' failed for an unknown reason";
			dcs::log_error(DCS_LOGGING_AT, oss.str());
		}
	}

	public: process_status_category status() const
	{
		return status_;
	}

	public: void stop()
	{
		// pre: process must be running
		DCS_ASSERT(status_ == running_process_status,
				   DCS_EXCEPTION_THROW(::std::runtime_error,
									   "Cannot stop a process that is not running"));

		this->kill(SIGSTOP);
	}

	public: void resume()
	{
		// pre: process must have been stopped
		DCS_ASSERT(status_ == stopped_process_status,
				   DCS_EXCEPTION_THROW(::std::runtime_error,
									   "Cannot resume a process that has not been stopped"));

		this->kill(SIGCONT);
	}

	public: void terminate()
	{
		// pre: process must be running
		DCS_ASSERT(status_ == running_process_status,
				   DCS_EXCEPTION_THROW(::std::runtime_error,
									   "Cannot stop a process that is not running"));

		this->kill(SIGTERM);
		::sleep(zzz_secs_);
		if (this->alive())
		{
			this->kill(SIGKILL);
		}
		this->wait();
	}

	public: bool alive() const
	{
		if (::kill(pid_, 0) == -1)
		{
			if (errno != ESRCH)
			{
				::std::ostringstream oss;
				oss << "Call to kill(2) failed for command '" << cmd_ << "' and signal 0: " << ::strerror(errno);

				DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
			}

			return false;
		}

		return true;
	}

	public: void kill(int sig)
	{
		// pre: sig >= 0
		DCS_ASSERT(sig >= 0,
				   DCS_EXCEPTION_THROW(::std::invalid_argument,
									   "Invalid signal number"));

		// signal 0 has a special meaning: it can be used to check if a process
		// exists without actually sending any signal to it.
		// To send such a signal, use method \c exist.
		if (sig == 0)
		{
			return;
		}

		if (::kill(pid_, sig) == -1)
		{
			::std::ostringstream oss;
			oss << "Call to kill(2) failed for command '" << cmd_ << "' and signal " << sig << ": " << ::strerror(errno);

			DCS_EXCEPTION_THROW(::std::runtime_error, oss.str());
		}

		sig_ = sig;
		switch (sig)
		{
			case SIGCONT:
				status_ = resumed_process_status;
				break;
			case SIGSTOP:
				status_ = stopped_process_status;
				break;
			case SIGTERM:
			case SIGKILL:
				status_ = terminated_process_status;
				break;
			case SIGINT:
				status_ = aborted_process_status;
				break;
			default:
				::sleep(zzz_secs_);
				if (!this->alive())
				{
					status_ = aborted_process_status;
				}
				break;
		}
	}

	private: ::std::string cmd_; ///< The command path
//	private: ::std::vector< ::std::string > args_; ///< The list of command arguments
	private: bool async_; ///< A \c true value means that the parent does not block to wait for child termination
	private: ::pid_t pid_; ///< The process identifier
	private: process_status_category status_; ///< The current status of this process
	private: int sig_; ///< The last signal sent to this process
	private: int exit_status_; ///< The exit status of this process
}; // posix_process

}} // Namespace dcs::system

#endif // DCS_SYSTEM_POSIX_PROCESS_HPP
<|endoftext|>


<commit_before>// Copyright (C) 2014 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp

// Interface inspirée de la SFML par Laurent Gomila

#pragma once

#ifndef NAZARA_EVENT_HPP
#define NAZARA_EVENT_HPP

#include <Nazara/Utility/Keyboard.hpp>
#include <Nazara/Utility/Mouse.hpp>

struct NzEvent
{
	// Utilisé par:
	// -nzEventType_KeyPressed
	// -nzEventType_KeyReleased
	struct KeyEvent
	{
		NzKeyboard::Key code;
		bool alt;
		bool control;
		bool repeated;
		bool shift;
		bool system;
	};

	// Utilisé par:
	// -nzEventType_MouseButtonDoubleClicked
	// -nzEventType_MouseButtonPressed
	struct MouseButtonEvent
	{
		NzMouse::Button button;
		unsigned int x;
		unsigned int y;
	};

	// Utilisé par:
	// -nzEventType_MouseMoved
	struct MouseMoveEvent
	{
		int deltaX;
		int deltaY;
		unsigned int x;
		unsigned int y;
	};

	// Utilisé par:
	// -nzEventType_MouseWheelMoved
	struct MouseWheelEvent
	{
		float delta;
	};

	// Utilisé par:
	// -nzEventType_Moved
	struct PositionEvent
	{
		int x;
		int y;
	};

	// Utilisé par:
	// -nzEventType_Resized
	struct SizeEvent
	{
		unsigned int height;
		unsigned int width;
	};

	// Utilisé par:
	// -nzEventType_TextEntered
	struct TextEvent
	{
		bool repeated;
		char32_t character;
	};

	nzEventType type;

	union
	{
		// Utilisé par:
		// -nzEventType_KeyPressed
		// -nzEventType_KeyReleased
		KeyEvent key;

		// Utilisé par:
		// -nzEventType_MouseButtonDoubleClicked
		// -nzEventType_MouseButtonPressed
		MouseButtonEvent mouseButton;

		// Utilisé par:
		// -nzEventType_MouseMoved
		MouseMoveEvent mouseMove;

		// Utilisé par:
		// -nzEventType_MouseWheelMoved
		MouseWheelEvent mouseWheel;

		// Utilisé par:
		// -nzEventType_Moved
		PositionEvent position;

		// Utilisé par:
		// -nzEventType_Resized
		SizeEvent size;

		// Utilisé par:
		// -nzEventType_TextEntered
		TextEvent text;
	};
};

#endif // NAZARA_EVENT_HPP
<commit_msg>Fixed missing include<commit_after>// Copyright (C) 2014 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp

// Interface inspirée de la SFML par Laurent Gomila

#pragma once

#ifndef NAZARA_EVENT_HPP
#define NAZARA_EVENT_HPP

#include <Nazara/Utility/Enums.hpp>
#include <Nazara/Utility/Keyboard.hpp>
#include <Nazara/Utility/Mouse.hpp>

struct NzEvent
{
	// Utilisé par:
	// -nzEventType_KeyPressed
	// -nzEventType_KeyReleased
	struct KeyEvent
	{
		NzKeyboard::Key code;
		bool alt;
		bool control;
		bool repeated;
		bool shift;
		bool system;
	};

	// Utilisé par:
	// -nzEventType_MouseButtonDoubleClicked
	// -nzEventType_MouseButtonPressed
	struct MouseButtonEvent
	{
		NzMouse::Button button;
		unsigned int x;
		unsigned int y;
	};

	// Utilisé par:
	// -nzEventType_MouseMoved
	struct MouseMoveEvent
	{
		int deltaX;
		int deltaY;
		unsigned int x;
		unsigned int y;
	};

	// Utilisé par:
	// -nzEventType_MouseWheelMoved
	struct MouseWheelEvent
	{
		float delta;
	};

	// Utilisé par:
	// -nzEventType_Moved
	struct PositionEvent
	{
		int x;
		int y;
	};

	// Utilisé par:
	// -nzEventType_Resized
	struct SizeEvent
	{
		unsigned int height;
		unsigned int width;
	};

	// Utilisé par:
	// -nzEventType_TextEntered
	struct TextEvent
	{
		bool repeated;
		char32_t character;
	};

	nzEventType type;

	union
	{
		// Utilisé par:
		// -nzEventType_KeyPressed
		// -nzEventType_KeyReleased
		KeyEvent key;

		// Utilisé par:
		// -nzEventType_MouseButtonDoubleClicked
		// -nzEventType_MouseButtonPressed
		MouseButtonEvent mouseButton;

		// Utilisé par:
		// -nzEventType_MouseMoved
		MouseMoveEvent mouseMove;

		// Utilisé par:
		// -nzEventType_MouseWheelMoved
		MouseWheelEvent mouseWheel;

		// Utilisé par:
		// -nzEventType_Moved
		PositionEvent position;

		// Utilisé par:
		// -nzEventType_Resized
		SizeEvent size;

		// Utilisé par:
		// -nzEventType_TextEntered
		TextEvent text;
	};
};

#endif // NAZARA_EVENT_HPP
<|endoftext|>