<commit_before>//===--- Availability.cpp - Swift Availability Structures -----------------===//
//
// 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 defines data structures for API availability.
//
//===----------------------------------------------------------------------===//

#include "swift/AST/ASTContext.h"
#include "swift/AST/Attr.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Types.h"
#include "swift/AST/Availability.h"
#include "swift/AST/PlatformKind.h"
#include "swift/AST/TypeWalker.h"
#include <map>

using namespace swift;

AvailabilityContext AvailabilityContext::forDeploymentTarget(ASTContext &Ctx) {
  return AvailabilityContext(
      VersionRange::allGTE(Ctx.LangOpts.getMinPlatformVersion()));
}

namespace {

/// The inferred availability required to access a group of declarations
/// on a single platform.
struct InferredAvailability {
  PlatformAgnosticAvailabilityKind PlatformAgnostic
    = PlatformAgnosticAvailabilityKind::None;

  Optional<llvm::VersionTuple> Introduced;
  Optional<llvm::VersionTuple> Deprecated;
  Optional<llvm::VersionTuple> Obsoleted;
};

/// The type of a function that merges two version tuples.
typedef const llvm::VersionTuple &(*MergeFunction)(
    const llvm::VersionTuple &, const llvm::VersionTuple &);

} // end anonymous namespace

/// Apply a merge function to two optional versions, returning the result
/// in Inferred.
static void
mergeIntoInferredVersion(const Optional<llvm::VersionTuple> &Version,
                         Optional<llvm::VersionTuple> &Inferred,
                         MergeFunction Merge) {
  if (Version.hasValue()) {
    if (Inferred.hasValue()) {
      Inferred = Merge(Inferred.getValue(), Version.getValue());
    } else {
      Inferred = Version;
    }
  }
}

/// Merge an attribute's availability with an existing inferred availability
/// so that the new inferred availability is at least as available as
/// the attribute requires.
static void mergeWithInferredAvailability(const AvailableAttr *Attr,
                                          InferredAvailability &Inferred) {
  Inferred.PlatformAgnostic
    = static_cast<PlatformAgnosticAvailabilityKind>(
      std::max(static_cast<unsigned>(Inferred.PlatformAgnostic),
               static_cast<unsigned>(Attr->getPlatformAgnosticAvailability())));

  // The merge of two introduction versions is the maximum of the two versions.
  mergeIntoInferredVersion(Attr->Introduced, Inferred.Introduced, std::max);

  // The merge of deprecated and obsoleted versions takes the minimum.
  mergeIntoInferredVersion(Attr->Deprecated, Inferred.Deprecated, std::min);
  mergeIntoInferredVersion(Attr->Obsoleted, Inferred.Obsoleted, std::min);
}

/// Create an implicit availability attribute for the given platform
/// and with the inferred availability.
static AvailableAttr *
createAvailableAttr(PlatformKind Platform,
                       const InferredAvailability &Inferred,
                       ASTContext &Context) {

  llvm::VersionTuple Introduced =
      Inferred.Introduced.getValueOr(llvm::VersionTuple());
  llvm::VersionTuple Deprecated =
      Inferred.Deprecated.getValueOr(llvm::VersionTuple());
  llvm::VersionTuple Obsoleted =
      Inferred.Obsoleted.getValueOr(llvm::VersionTuple());

  return new (Context) AvailableAttr(
      SourceLoc(), SourceRange(), Platform,
      /*Message=*/StringRef(),
      /*Rename=*/StringRef(),
        Introduced, /*IntroducedRange=*/SourceRange(),
        Deprecated, /*DeprecatedRange=*/SourceRange(),
        Obsoleted, /*ObsoletedRange=*/SourceRange(),
      Inferred.PlatformAgnostic, /*Implicit=*/true);
}

void AvailabilityInference::applyInferredAvailableAttrs(
    Decl *ToDecl, ArrayRef<const Decl *> InferredFromDecls,
    ASTContext &Context) {

  // Iterate over the declarations and infer required availability on
  // a per-platform basis.
  std::map<PlatformKind, InferredAvailability> Inferred;
  for (const Decl *D : InferredFromDecls) {
    for (const DeclAttribute *Attr : D->getAttrs()) {
      auto *AvAttr = dyn_cast<AvailableAttr>(Attr);
      if (!AvAttr || AvAttr->isInvalid())
        continue;

      mergeWithInferredAvailability(AvAttr, Inferred[AvAttr->Platform]);
    }
  }

  // Create an availability attribute for each observed platform and add
  // to ToDecl.
  DeclAttributes &Attrs = ToDecl->getAttrs();
  for (auto &Pair : Inferred) {
    auto *Attr = createAvailableAttr(Pair.first, Pair.second, Context);
    Attrs.add(Attr);
  }
}

Optional<AvailabilityContext>
AvailabilityInference::annotatedAvailableRange(const Decl *D, ASTContext &Ctx) {
  Optional<AvailabilityContext> AnnotatedRange;

  for (auto Attr : D->getAttrs()) {
    auto *AvailAttr = dyn_cast<AvailableAttr>(Attr);
    if (AvailAttr == nullptr || !AvailAttr->Introduced.hasValue() ||
        !AvailAttr->isActivePlatform(Ctx) ||
        AvailAttr->isLanguageVersionSpecific() ||
        AvailAttr->isPackageDescriptionVersionSpecific()) {
      continue;
    }

    AvailabilityContext AttrRange{
        VersionRange::allGTE(AvailAttr->Introduced.getValue())};

    // If we have multiple introduction versions, we will conservatively
    // assume the worst case scenario. We may want to be more precise here
    // in the future or emit a diagnostic.

    if (AnnotatedRange.hasValue()) {
      AnnotatedRange.getValue().intersectWith(AttrRange);
    } else {
      AnnotatedRange = AttrRange;
    }
  }

  return AnnotatedRange;
}

AvailabilityContext AvailabilityInference::availableRange(const Decl *D,
                                                          ASTContext &Ctx) {
  Optional<AvailabilityContext> AnnotatedRange =
      annotatedAvailableRange(D, Ctx);
  if (AnnotatedRange.hasValue()) {
    return AnnotatedRange.getValue();
  }

  // Unlike other declarations, extensions can be used without referring to them
  // by name (they don't have one) in the source. For this reason, when checking
  // the available range of a declaration we also need to check to see if it is
  // immediately contained in an extension and use the extension's availability
  // if the declaration does not have an explicit @available attribute
  // itself. This check relies on the fact that we cannot have nested
  // extensions.

  DeclContext *DC = D->getDeclContext();
  if (auto *ED = dyn_cast<ExtensionDecl>(DC)) {
    AnnotatedRange = annotatedAvailableRange(ED, Ctx);
    if (AnnotatedRange.hasValue()) {
      return AnnotatedRange.getValue();
    }
  }

  // Treat unannotated declarations as always available.
  return AvailabilityContext::alwaysAvailable();
}

namespace {
/// Infers the availability required to access a type.
class AvailabilityInferenceTypeWalker : public TypeWalker {
public:
  ASTContext &AC;
  AvailabilityContext AvailabilityInfo = AvailabilityContext::alwaysAvailable();

  AvailabilityInferenceTypeWalker(ASTContext &AC) : AC(AC) {}

  Action walkToTypePre(Type ty) override {
    if (auto *nominalDecl = ty->getAnyNominal()) {
      AvailabilityInfo.intersectWith(
          AvailabilityInference::availableRange(nominalDecl, AC));
    }

    return Action::Continue;
  }
};
} // end anonymous namespace

AvailabilityContext AvailabilityInference::inferForType(Type t) {
  AvailabilityInferenceTypeWalker walker(t->getASTContext());
  t.walk(walker);
  return walker.AvailabilityInfo;
}

AvailabilityContext ASTContext::getObjCMetadataUpdateCallbackAvailability() {
  return getSwift50Availability();
}

AvailabilityContext ASTContext::getObjCGetClassHookAvailability() {
  return getSwift50Availability();
}

AvailabilityContext ASTContext::getSwift50Availability() {
  auto target = LangOpts.Target;

  if (target.getArchName() == "arm64e")
    return AvailabilityContext::alwaysAvailable();

  if (target.isMacOSX()) {
    return AvailabilityContext(
                            VersionRange::allGTE(llvm::VersionTuple(10,14,4)));
  } else if (target.isiOS()) {
    return AvailabilityContext(
                            VersionRange::allGTE(llvm::VersionTuple(12,2)));
  } else if (target.isWatchOS()) {
    return AvailabilityContext(
                            VersionRange::allGTE(llvm::VersionTuple(5,2)));
  } else {
    return AvailabilityContext::alwaysAvailable();
  }
}

AvailabilityContext ASTContext::getOpaqueTypeAvailability() {
  return getSwift51Availability();
}

AvailabilityContext ASTContext::getObjCClassStubsAvailability() {
  return getSwift51Availability();
}

AvailabilityContext ASTContext::getSwift51Availability() {
  auto target = LangOpts.Target;

  if (target.getArchName() == "arm64e")
    return AvailabilityContext::alwaysAvailable();

  if (target.isMacOSX()) {
    return AvailabilityContext(
                            VersionRange::allGTE(llvm::VersionTuple(10,15,0)));
  } else if (target.isiOS()) {
    return AvailabilityContext(
                            VersionRange::allGTE(llvm::VersionTuple(13,0,0)));
  } else if (target.isWatchOS()) {
    return AvailabilityContext(
                            VersionRange::allGTE(llvm::VersionTuple(6,0,0)));
  } else {
    return AvailabilityContext::alwaysAvailable();
  }
}

AvailabilityContext ASTContext::getTypesInAbstractMetadataStateAvailability() {
  return getSwift52Availability();
}

AvailabilityContext ASTContext::getPrespecializedGenericMetadataAvailability() {
  return getSwift53Availability();
}

AvailabilityContext ASTContext::getSwift52Availability() {
  auto target = LangOpts.Target;

  if (target.getArchName() == "arm64e")
    return AvailabilityContext::alwaysAvailable();

  if (target.isMacOSX() ) {
    return AvailabilityContext(
        VersionRange::allGTE(llvm::VersionTuple(10, 99, 0)));
  } else if (target.isiOS()) {
    return AvailabilityContext(
        VersionRange::allGTE(llvm::VersionTuple(99, 0, 0)));
  } else if (target.isWatchOS()) {
    return AvailabilityContext(
        VersionRange::allGTE(llvm::VersionTuple(9, 99, 0)));
  } else {
    return AvailabilityContext::alwaysAvailable();
  }
}

AvailabilityContext ASTContext::getSwift53Availability() {
  auto target = LangOpts.Target;

  if (target.isMacOSX() ) {
    return AvailabilityContext(
        VersionRange::allGTE(llvm::VersionTuple(10, 99, 0)));
  } else if (target.isiOS()) {
    return AvailabilityContext(
        VersionRange::allGTE(llvm::VersionTuple(99, 0, 0)));
  } else if (target.isWatchOS()) {
    return AvailabilityContext(
        VersionRange::allGTE(llvm::VersionTuple(9, 99, 0)));
  } else {
    return AvailabilityContext::alwaysAvailable();
  }
}

AvailabilityContext ASTContext::getSwiftFutureAvailability() {
  auto target = LangOpts.Target;

  if (target.isMacOSX() ) {
    return AvailabilityContext(
        VersionRange::allGTE(llvm::VersionTuple(10, 99, 0)));
  } else if (target.isiOS()) {
    return AvailabilityContext(
        VersionRange::allGTE(llvm::VersionTuple(99, 0, 0)));
  } else if (target.isWatchOS()) {
    return AvailabilityContext(
        VersionRange::allGTE(llvm::VersionTuple(9, 99, 0)));
  } else {
    return AvailabilityContext::alwaysAvailable();
  }
}
<commit_msg>Swift 5.3 is always available for arm64e.<commit_after>//===--- Availability.cpp - Swift Availability Structures -----------------===//
//
// 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 defines data structures for API availability.
//
//===----------------------------------------------------------------------===//

#include "swift/AST/ASTContext.h"
#include "swift/AST/Attr.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Types.h"
#include "swift/AST/Availability.h"
#include "swift/AST/PlatformKind.h"
#include "swift/AST/TypeWalker.h"
#include <map>

using namespace swift;

AvailabilityContext AvailabilityContext::forDeploymentTarget(ASTContext &Ctx) {
  return AvailabilityContext(
      VersionRange::allGTE(Ctx.LangOpts.getMinPlatformVersion()));
}

namespace {

/// The inferred availability required to access a group of declarations
/// on a single platform.
struct InferredAvailability {
  PlatformAgnosticAvailabilityKind PlatformAgnostic
    = PlatformAgnosticAvailabilityKind::None;

  Optional<llvm::VersionTuple> Introduced;
  Optional<llvm::VersionTuple> Deprecated;
  Optional<llvm::VersionTuple> Obsoleted;
};

/// The type of a function that merges two version tuples.
typedef const llvm::VersionTuple &(*MergeFunction)(
    const llvm::VersionTuple &, const llvm::VersionTuple &);

} // end anonymous namespace

/// Apply a merge function to two optional versions, returning the result
/// in Inferred.
static void
mergeIntoInferredVersion(const Optional<llvm::VersionTuple> &Version,
                         Optional<llvm::VersionTuple> &Inferred,
                         MergeFunction Merge) {
  if (Version.hasValue()) {
    if (Inferred.hasValue()) {
      Inferred = Merge(Inferred.getValue(), Version.getValue());
    } else {
      Inferred = Version;
    }
  }
}

/// Merge an attribute's availability with an existing inferred availability
/// so that the new inferred availability is at least as available as
/// the attribute requires.
static void mergeWithInferredAvailability(const AvailableAttr *Attr,
                                          InferredAvailability &Inferred) {
  Inferred.PlatformAgnostic
    = static_cast<PlatformAgnosticAvailabilityKind>(
      std::max(static_cast<unsigned>(Inferred.PlatformAgnostic),
               static_cast<unsigned>(Attr->getPlatformAgnosticAvailability())));

  // The merge of two introduction versions is the maximum of the two versions.
  mergeIntoInferredVersion(Attr->Introduced, Inferred.Introduced, std::max);

  // The merge of deprecated and obsoleted versions takes the minimum.
  mergeIntoInferredVersion(Attr->Deprecated, Inferred.Deprecated, std::min);
  mergeIntoInferredVersion(Attr->Obsoleted, Inferred.Obsoleted, std::min);
}

/// Create an implicit availability attribute for the given platform
/// and with the inferred availability.
static AvailableAttr *
createAvailableAttr(PlatformKind Platform,
                       const InferredAvailability &Inferred,
                       ASTContext &Context) {

  llvm::VersionTuple Introduced =
      Inferred.Introduced.getValueOr(llvm::VersionTuple());
  llvm::VersionTuple Deprecated =
      Inferred.Deprecated.getValueOr(llvm::VersionTuple());
  llvm::VersionTuple Obsoleted =
      Inferred.Obsoleted.getValueOr(llvm::VersionTuple());

  return new (Context) AvailableAttr(
      SourceLoc(), SourceRange(), Platform,
      /*Message=*/StringRef(),
      /*Rename=*/StringRef(),
        Introduced, /*IntroducedRange=*/SourceRange(),
        Deprecated, /*DeprecatedRange=*/SourceRange(),
        Obsoleted, /*ObsoletedRange=*/SourceRange(),
      Inferred.PlatformAgnostic, /*Implicit=*/true);
}

void AvailabilityInference::applyInferredAvailableAttrs(
    Decl *ToDecl, ArrayRef<const Decl *> InferredFromDecls,
    ASTContext &Context) {

  // Iterate over the declarations and infer required availability on
  // a per-platform basis.
  std::map<PlatformKind, InferredAvailability> Inferred;
  for (const Decl *D : InferredFromDecls) {
    for (const DeclAttribute *Attr : D->getAttrs()) {
      auto *AvAttr = dyn_cast<AvailableAttr>(Attr);
      if (!AvAttr || AvAttr->isInvalid())
        continue;

      mergeWithInferredAvailability(AvAttr, Inferred[AvAttr->Platform]);
    }
  }

  // Create an availability attribute for each observed platform and add
  // to ToDecl.
  DeclAttributes &Attrs = ToDecl->getAttrs();
  for (auto &Pair : Inferred) {
    auto *Attr = createAvailableAttr(Pair.first, Pair.second, Context);
    Attrs.add(Attr);
  }
}

Optional<AvailabilityContext>
AvailabilityInference::annotatedAvailableRange(const Decl *D, ASTContext &Ctx) {
  Optional<AvailabilityContext> AnnotatedRange;

  for (auto Attr : D->getAttrs()) {
    auto *AvailAttr = dyn_cast<AvailableAttr>(Attr);
    if (AvailAttr == nullptr || !AvailAttr->Introduced.hasValue() ||
        !AvailAttr->isActivePlatform(Ctx) ||
        AvailAttr->isLanguageVersionSpecific() ||
        AvailAttr->isPackageDescriptionVersionSpecific()) {
      continue;
    }

    AvailabilityContext AttrRange{
        VersionRange::allGTE(AvailAttr->Introduced.getValue())};

    // If we have multiple introduction versions, we will conservatively
    // assume the worst case scenario. We may want to be more precise here
    // in the future or emit a diagnostic.

    if (AnnotatedRange.hasValue()) {
      AnnotatedRange.getValue().intersectWith(AttrRange);
    } else {
      AnnotatedRange = AttrRange;
    }
  }

  return AnnotatedRange;
}

AvailabilityContext AvailabilityInference::availableRange(const Decl *D,
                                                          ASTContext &Ctx) {
  Optional<AvailabilityContext> AnnotatedRange =
      annotatedAvailableRange(D, Ctx);
  if (AnnotatedRange.hasValue()) {
    return AnnotatedRange.getValue();
  }

  // Unlike other declarations, extensions can be used without referring to them
  // by name (they don't have one) in the source. For this reason, when checking
  // the available range of a declaration we also need to check to see if it is
  // immediately contained in an extension and use the extension's availability
  // if the declaration does not have an explicit @available attribute
  // itself. This check relies on the fact that we cannot have nested
  // extensions.

  DeclContext *DC = D->getDeclContext();
  if (auto *ED = dyn_cast<ExtensionDecl>(DC)) {
    AnnotatedRange = annotatedAvailableRange(ED, Ctx);
    if (AnnotatedRange.hasValue()) {
      return AnnotatedRange.getValue();
    }
  }

  // Treat unannotated declarations as always available.
  return AvailabilityContext::alwaysAvailable();
}

namespace {
/// Infers the availability required to access a type.
class AvailabilityInferenceTypeWalker : public TypeWalker {
public:
  ASTContext &AC;
  AvailabilityContext AvailabilityInfo = AvailabilityContext::alwaysAvailable();

  AvailabilityInferenceTypeWalker(ASTContext &AC) : AC(AC) {}

  Action walkToTypePre(Type ty) override {
    if (auto *nominalDecl = ty->getAnyNominal()) {
      AvailabilityInfo.intersectWith(
          AvailabilityInference::availableRange(nominalDecl, AC));
    }

    return Action::Continue;
  }
};
} // end anonymous namespace

AvailabilityContext AvailabilityInference::inferForType(Type t) {
  AvailabilityInferenceTypeWalker walker(t->getASTContext());
  t.walk(walker);
  return walker.AvailabilityInfo;
}

AvailabilityContext ASTContext::getObjCMetadataUpdateCallbackAvailability() {
  return getSwift50Availability();
}

AvailabilityContext ASTContext::getObjCGetClassHookAvailability() {
  return getSwift50Availability();
}

AvailabilityContext ASTContext::getSwift50Availability() {
  auto target = LangOpts.Target;

  if (target.getArchName() == "arm64e")
    return AvailabilityContext::alwaysAvailable();

  if (target.isMacOSX()) {
    return AvailabilityContext(
                            VersionRange::allGTE(llvm::VersionTuple(10,14,4)));
  } else if (target.isiOS()) {
    return AvailabilityContext(
                            VersionRange::allGTE(llvm::VersionTuple(12,2)));
  } else if (target.isWatchOS()) {
    return AvailabilityContext(
                            VersionRange::allGTE(llvm::VersionTuple(5,2)));
  } else {
    return AvailabilityContext::alwaysAvailable();
  }
}

AvailabilityContext ASTContext::getOpaqueTypeAvailability() {
  return getSwift51Availability();
}

AvailabilityContext ASTContext::getObjCClassStubsAvailability() {
  return getSwift51Availability();
}

AvailabilityContext ASTContext::getSwift51Availability() {
  auto target = LangOpts.Target;

  if (target.getArchName() == "arm64e")
    return AvailabilityContext::alwaysAvailable();

  if (target.isMacOSX()) {
    return AvailabilityContext(
                            VersionRange::allGTE(llvm::VersionTuple(10,15,0)));
  } else if (target.isiOS()) {
    return AvailabilityContext(
                            VersionRange::allGTE(llvm::VersionTuple(13,0,0)));
  } else if (target.isWatchOS()) {
    return AvailabilityContext(
                            VersionRange::allGTE(llvm::VersionTuple(6,0,0)));
  } else {
    return AvailabilityContext::alwaysAvailable();
  }
}

AvailabilityContext ASTContext::getTypesInAbstractMetadataStateAvailability() {
  return getSwift52Availability();
}

AvailabilityContext ASTContext::getPrespecializedGenericMetadataAvailability() {
  return getSwift53Availability();
}

AvailabilityContext ASTContext::getSwift52Availability() {
  auto target = LangOpts.Target;

  if (target.getArchName() == "arm64e")
    return AvailabilityContext::alwaysAvailable();

  if (target.isMacOSX() ) {
    return AvailabilityContext(
        VersionRange::allGTE(llvm::VersionTuple(10, 99, 0)));
  } else if (target.isiOS()) {
    return AvailabilityContext(
        VersionRange::allGTE(llvm::VersionTuple(99, 0, 0)));
  } else if (target.isWatchOS()) {
    return AvailabilityContext(
        VersionRange::allGTE(llvm::VersionTuple(9, 99, 0)));
  } else {
    return AvailabilityContext::alwaysAvailable();
  }
}

AvailabilityContext ASTContext::getSwift53Availability() {
  auto target = LangOpts.Target;

  if (target.getArchName() == "arm64e")
    return AvailabilityContext::alwaysAvailable();

  if (target.isMacOSX() ) {
    return AvailabilityContext(
        VersionRange::allGTE(llvm::VersionTuple(10, 99, 0)));
  } else if (target.isiOS()) {
    return AvailabilityContext(
        VersionRange::allGTE(llvm::VersionTuple(99, 0, 0)));
  } else if (target.isWatchOS()) {
    return AvailabilityContext(
        VersionRange::allGTE(llvm::VersionTuple(9, 99, 0)));
  } else {
    return AvailabilityContext::alwaysAvailable();
  }
}

AvailabilityContext ASTContext::getSwiftFutureAvailability() {
  auto target = LangOpts.Target;

  if (target.isMacOSX() ) {
    return AvailabilityContext(
        VersionRange::allGTE(llvm::VersionTuple(10, 99, 0)));
  } else if (target.isiOS()) {
    return AvailabilityContext(
        VersionRange::allGTE(llvm::VersionTuple(99, 0, 0)));
  } else if (target.isWatchOS()) {
    return AvailabilityContext(
        VersionRange::allGTE(llvm::VersionTuple(9, 99, 0)));
  } else {
    return AvailabilityContext::alwaysAvailable();
  }
}
<|endoftext|>


<commit_before>#include "joedb/journal/Windows_File.h"
#include "joedb/Exception.h"

namespace joedb
{
 const DWORD Windows_File::desired_access[] =
 {
  GENERIC_READ,
  GENERIC_READ | GENERIC_WRITE,
  GENERIC_READ | GENERIC_WRITE,
  GENERIC_READ | GENERIC_WRITE
 };

 const DWORD Windows_File::share_mode[] =
 {
  FILE_SHARE_READ | FILE_SHARE_WRITE,
  FILE_SHARE_READ,
  FILE_SHARE_READ,
  FILE_SHARE_READ
 };

 const DWORD Windows_File::creation_disposition[] =
 {
  OPEN_EXISTING,
  OPEN_EXISTING,
  CREATE_NEW,
  OPEN_ALWAYS
 };

 /////////////////////////////////////////////////////////////////////////////
 void Windows_File::throw_last_error() const
 /////////////////////////////////////////////////////////////////////////////
 {
  const DWORD last_error = GetLastError();
  LPVOID buffer;

  FormatMessage
  (
   FORMAT_MESSAGE_ALLOCATE_BUFFER |
   FORMAT_MESSAGE_FROM_SYSTEM,
   NULL,
   last_error,
   MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
   (LPTSTR) &buffer,
   0,
   NULL
  );

  std::string s((char *)buffer);

  LocalFree(buffer);

  throw Exception(s);
 }

 /////////////////////////////////////////////////////////////////////////////
 size_t Windows_File::raw_read(char *buffer, size_t size)
 /////////////////////////////////////////////////////////////////////////////
 {
  DWORD result;

  if (ReadFile(file, buffer, DWORD(size), &result, NULL))
   return size_t(result);
  else
   throw_last_error();
 }

 /////////////////////////////////////////////////////////////////////////////
 void Windows_File::raw_write(const char *buffer, size_t size)
 /////////////////////////////////////////////////////////////////////////////
 {
  if (!WriteFile(file, buffer, DWORD(size), NULL, NULL))
   throw_last_error();
 }

 /////////////////////////////////////////////////////////////////////////////
 int Windows_File::seek(int64_t offset)
 /////////////////////////////////////////////////////////////////////////////
 {
  LARGE_INTEGER large_integer;
  large_integer.QuadPart = offset;

  if (SetFilePointerEx(file, large_integer, NULL, FILE_BEGIN))
   return 0;
  else
   return 1;
 }

 /////////////////////////////////////////////////////////////////////////////
 void Windows_File::sync()
 /////////////////////////////////////////////////////////////////////////////
 {
  FlushFileBuffers(file);
 }

 /////////////////////////////////////////////////////////////////////////////
 Windows_File::Windows_File(const char *file_name, Open_Mode mode):
 /////////////////////////////////////////////////////////////////////////////
  file
  (
   CreateFileA
   (
    file_name,
    desired_access[static_cast<size_t>(mode)],
    share_mode[static_cast<size_t>(mode)],
    NULL,
    creation_disposition[static_cast<size_t>(mode)],
    FILE_ATTRIBUTE_NORMAL,
    NULL
   )
  )
 {
  if (file == INVALID_HANDLE_VALUE)
   throw_last_error();

  if (mode == Open_Mode::write_existing_or_create_new)
  {
   if (GetLastError() == 0)
    mode = Open_Mode::create_new;
   else
    mode = Open_Mode::write_existing;
  }

  this->mode = mode;
 }

 /////////////////////////////////////////////////////////////////////////////
 int64_t Windows_File::get_size() const
 /////////////////////////////////////////////////////////////////////////////
 {
  LARGE_INTEGER result;

  if (GetFileSizeEx(file, &result))
   return int64_t(result.QuadPart);
  else
   throw_last_error();
 }

 /////////////////////////////////////////////////////////////////////////////
 Windows_File::~Windows_File()
 /////////////////////////////////////////////////////////////////////////////
 {
  flush();
  CloseHandle(file);
 }
}
<commit_msg>Fix large reads in joedb::Windows_File<commit_after>#include "joedb/journal/Windows_File.h"
#include "joedb/Exception.h"

namespace joedb
{
 const DWORD Windows_File::desired_access[] =
 {
  GENERIC_READ,
  GENERIC_READ | GENERIC_WRITE,
  GENERIC_READ | GENERIC_WRITE,
  GENERIC_READ | GENERIC_WRITE
 };

 const DWORD Windows_File::share_mode[] =
 {
  FILE_SHARE_READ | FILE_SHARE_WRITE,
  FILE_SHARE_READ,
  FILE_SHARE_READ,
  FILE_SHARE_READ
 };

 const DWORD Windows_File::creation_disposition[] =
 {
  OPEN_EXISTING,
  OPEN_EXISTING,
  CREATE_NEW,
  OPEN_ALWAYS
 };

 /////////////////////////////////////////////////////////////////////////////
 void Windows_File::throw_last_error() const
 /////////////////////////////////////////////////////////////////////////////
 {
  const DWORD last_error = GetLastError();
  LPVOID buffer;

  FormatMessage
  (
   FORMAT_MESSAGE_ALLOCATE_BUFFER |
   FORMAT_MESSAGE_FROM_SYSTEM,
   NULL,
   last_error,
   MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
   (LPTSTR) &buffer,
   0,
   NULL
  );

  std::string s((char *)buffer);

  LocalFree(buffer);

  throw Exception(s);
 }

 /////////////////////////////////////////////////////////////////////////////
 size_t Windows_File::raw_read(char *buffer, size_t size)
 /////////////////////////////////////////////////////////////////////////////
 {
  const size_t max_size = 1ULL << 31;

  if (size > max_size)
   size = max_size;

  DWORD result;

  if (ReadFile(file, buffer, DWORD(size), &result, NULL))
   return size_t(result);
  else
   throw_last_error();
 }

 /////////////////////////////////////////////////////////////////////////////
 void Windows_File::raw_write(const char *buffer, size_t size)
 /////////////////////////////////////////////////////////////////////////////
 {
  // TODO: support for large writes
  if (!WriteFile(file, buffer, DWORD(size), NULL, NULL))
   throw_last_error();
 }

 /////////////////////////////////////////////////////////////////////////////
 int Windows_File::seek(int64_t offset)
 /////////////////////////////////////////////////////////////////////////////
 {
  LARGE_INTEGER large_integer;
  large_integer.QuadPart = offset;

  if (SetFilePointerEx(file, large_integer, NULL, FILE_BEGIN))
   return 0;
  else
   return 1;
 }

 /////////////////////////////////////////////////////////////////////////////
 void Windows_File::sync()
 /////////////////////////////////////////////////////////////////////////////
 {
  FlushFileBuffers(file);
 }

 /////////////////////////////////////////////////////////////////////////////
 Windows_File::Windows_File(const char *file_name, Open_Mode mode):
 /////////////////////////////////////////////////////////////////////////////
  file
  (
   CreateFileA
   (
    file_name,
    desired_access[static_cast<size_t>(mode)],
    share_mode[static_cast<size_t>(mode)],
    NULL,
    creation_disposition[static_cast<size_t>(mode)],
    FILE_ATTRIBUTE_NORMAL,
    NULL
   )
  )
 {
  if (file == INVALID_HANDLE_VALUE)
   throw_last_error();

  if (mode == Open_Mode::write_existing_or_create_new)
  {
   if (GetLastError() == 0)
    mode = Open_Mode::create_new;
   else
    mode = Open_Mode::write_existing;
  }

  this->mode = mode;
 }

 /////////////////////////////////////////////////////////////////////////////
 int64_t Windows_File::get_size() const
 /////////////////////////////////////////////////////////////////////////////
 {
  LARGE_INTEGER result;

  if (GetFileSizeEx(file, &result))
   return int64_t(result.QuadPart);
  else
   throw_last_error();
 }

 /////////////////////////////////////////////////////////////////////////////
 Windows_File::~Windows_File()
 /////////////////////////////////////////////////////////////////////////////
 {
  flush();
  CloseHandle(file);
 }
}
<|endoftext|>


<commit_before>/* dtkDistributedServerManagerTorque.cpp ---
 *
 * Author: Julien Wintz
 * Copyright (C) 2008-2011 - Julien Wintz, Inria.
 * Created: Tue May 31 23:10:24 2011 (+0200)
 * Version: $Id$
 * Last-Updated: mar. juin 28 16:21:24 2011 (+0200)
 *           By: Nicolas Niclausse
 *     Update #: 233
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "dtkDistributedCore.h"
#include "dtkDistributedCpu.h"
#include "dtkDistributedGpu.h"
#include "dtkDistributedNode.h"
#include "dtkDistributedServerManager_p.h"
#include "dtkDistributedServerManagerTorque.h"

#include <dtkCore/dtkGlobal.h>
#include <dtkCore/dtkLog.h>

#include <QtCore>
#include <QtXml>

QString dtkDistributedServerManagerTorque::status(void)
{
    QProcess stat; stat.start("pbsnodes", QStringList() << "-x");

    if (!stat.waitForStarted()) {
        dtkCritical() << "Unable to launch stat command";
        return QString();
    }

    if (!stat.waitForFinished()) {
        dtkCritical() << "Unable to completed stat command";
        return QString();
    }

    QString result = "status;" + protocol() +"\n";
    QString data = stat.readAll();
    QDomDocument document; QString error;

    if(!document.setContent(data, false, &error))
      dtkDebug() << "Error retrieving xml output out of torque "  << error;

    QDomNodeList nodes = document.elementsByTagName("Node");
    for(int i = 0; i < nodes.count(); i++) {
      QString np = nodes.item(i).firstChildElement("np").text().simplified();
      QString name = nodes.item(i).firstChildElement("name").text().simplified();
      QString state = nodes.item(i).firstChildElement("state").text().simplified();

      // Each job is coreid/jobid, count the number of "/" to get the number of jobs
      int njobs  = nodes.item(i).firstChildElement("jobs").text().simplified().count("/");
      QString ngpus  = nodes.item(i).firstChildElement("gpus").text().simplified();

      // number of busy GPUs not implemented
      QStringList properties = nodes.item(i).firstChildElement("properties").text().simplified().split(",");

      QStringList outprops;
      QString prop;
      // FIXME: we should read the properties mapping from a file instead of hardcoding it
      outprops << "infiniband=QDR";
      outprops << "ethernet=1G";
      foreach( prop, properties ) {
        if (prop.contains("opteron")) {
          outprops << "arch=opteron";
        } else if (prop.contains("xeon")) {
          outprops << "arch=xeon";
        } else if (prop.contains("C2050")) {
          outprops << "gpu=nvidia-C2050";
        } else if (prop.contains("T10")) {
          outprops << "gpu=nvidia-T10";
        } else if (prop.contains("T10")) {
          outprops << "gpu=nvidia-T10";
        }
      }
      result += name + ";" + np + ";" + QString::number(njobs) + ";" + ngpus + ";0;" + "("+outprops.join(",")+");";
      if (state.contains("job-exclusive")) {
        state="busy";
      } else if (state.contains("free")) {
        state="free";
      } else {
        state="down";
      }
      result += state+"\n";
    }

    result += "endstatus\n";
    return result;
}
<commit_msg>fix format (offset = 4)<commit_after>/* dtkDistributedServerManagerTorque.cpp ---
 *
 * Author: Julien Wintz
 * Copyright (C) 2008-2011 - Julien Wintz, Inria.
 * Created: Tue May 31 23:10:24 2011 (+0200)
 * Version: $Id$
 * Last-Updated: mar. juin 28 16:48:01 2011 (+0200)
 *           By: Nicolas Niclausse
 *     Update #: 236
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "dtkDistributedCore.h"
#include "dtkDistributedCpu.h"
#include "dtkDistributedGpu.h"
#include "dtkDistributedNode.h"
#include "dtkDistributedServerManager_p.h"
#include "dtkDistributedServerManagerTorque.h"

#include <dtkCore/dtkGlobal.h>
#include <dtkCore/dtkLog.h>

#include <QtCore>
#include <QtXml>

QString dtkDistributedServerManagerTorque::status(void)
{
    QProcess stat; stat.start("pbsnodes", QStringList() << "-x");

    if (!stat.waitForStarted()) {
        dtkCritical() << "Unable to launch stat command";
        return QString();
    }

    if (!stat.waitForFinished()) {
        dtkCritical() << "Unable to completed stat command";
        return QString();
    }

    QString result = "status;" + protocol() +"\n";
    QString data = stat.readAll();
    QDomDocument document; QString error;

    if(!document.setContent(data, false, &error))
        dtkDebug() << "Error retrieving xml output out of torque "  << error;

    QDomNodeList nodes = document.elementsByTagName("Node");
    for(int i = 0; i < nodes.count(); i++) {
        QString np = nodes.item(i).firstChildElement("np").text().simplified();
        QString name = nodes.item(i).firstChildElement("name").text().simplified();
        QString state = nodes.item(i).firstChildElement("state").text().simplified();

        // Each job is coreid/jobid, count the number of "/" to get the number of jobs
        int njobs  = nodes.item(i).firstChildElement("jobs").text().simplified().count("/");
        QString ngpus  = nodes.item(i).firstChildElement("gpus").text().simplified();

        // number of busy GPUs not implemented
        QStringList properties = nodes.item(i).firstChildElement("properties").text().simplified().split(",");

        QStringList outprops;
        QString prop;
        // FIXME: we should read the properties mapping from a file instead of hardcoding it
        outprops << "infiniband=QDR";
        outprops << "ethernet=1G";
        foreach( prop, properties ) {
            if (prop.contains("opteron")) {
                outprops << "arch=opteron";
            } else if (prop.contains("xeon")) {
                outprops << "arch=xeon";
            } else if (prop.contains("C2050")) {
                outprops << "gpu=nvidia-C2050";
            } else if (prop.contains("T10")) {
                outprops << "gpu=nvidia-T10";
            } else if (prop.contains("T10")) {
                outprops << "gpu=nvidia-T10";
            }
        }
        result += name + ";" + np + ";" + QString::number(njobs) + ";" + ngpus + ";0;" + "("+outprops.join(",")+");";
        if (state.contains("job-exclusive")) {
            state="busy";
        } else if (state.contains("free")) {
            state="free";
        } else {
            state="down";
        }
        result += state+"\n";
    }

    result += "endstatus\n";
    return result;
}
<|endoftext|>


<commit_before>// This is a personal academic project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/**
* EnemyComponent/AI.
*
* License: Mozilla Public License Version 2.0 (https://www.mozilla.org/en-US/MPL/2.0/ OR See accompanying file LICENSE)
* Authors:
*  - Dan Printzell
*/
#include <hydra/component/aicomponent.hpp>
#include <imgui/imgui.h>

using namespace Hydra::World;
using namespace Hydra::Component;

EnemyComponent::EnemyComponent(IEntity* entity) : IComponent(entity), _enemyID(EnemyTypes::Alien), _position(0,0,0) {}

EnemyComponent::EnemyComponent(IEntity* entity, EnemyTypes enemyID, glm::vec3 pos) : IComponent(entity), _enemyID(enemyID),  _position(pos){
	_velocityX = 0;
	_velocityY = 0;
	_velocityZ = 0;
	_startPosition = glm::vec3(0, 0, 0);
	_patrolPointReached = false;
	_falling = false;
	_pathState = SEARCHING;
	lastTime = 0;

	for (int i = 0; i < WORLD_SIZE; i++)
	{
		for (int j = 0; j < WORLD_SIZE; j++)
		{
			map[i][j] = 0;
		}
	}

	for (int i = 0; i < 20; i++)
	{
		map[10][12+i] = 1;
	}
}

EnemyComponent::~EnemyComponent() { }

void EnemyComponent::tick(TickAction action, float delta) {
	// If you only have one TickAction in 'wantTick' you don't need to check the tickaction here.

	auto enemy = entity->getComponent<Component::TransformComponent>();
	std::shared_ptr<Hydra::World::IEntity> playerEntity = getPlayerComponent();
	auto player = playerEntity->getComponent<Component::PlayerComponent>();

	_velocityX = 0;
	_velocityY = 0;
	_velocityZ = 0;
	_debugState = _pathState;

	if (_startPosition == glm::vec3(0, 0, 0))
	{
		enemy->setPosition(_position);
		_startPosition = enemy->getPosition();
	}

	switch (_enemyID)
	{
		case EnemyTypes::Alien:
		{
			switch (_pathState)
			{
			case SEARCHING:
			{
				if (glm::length(enemy->getPosition() - player->getPosition()) < 10.0f)
				{
					_isAtGoal = true;
					_pathState = ATTACKING;
				}

				_pathFinding->findPath(enemy->getPosition(), player->getPosition(), map);
				_isAtGoal = false;
				if (_pathFinding->foundGoal)
				{
					_targetPos = player->getPosition();
					_pathState = FOUND_GOAL;
				}
			}break;
			case FOUND_GOAL:
			{
				if (!_isAtGoal)
				{
					glm::vec3 targetDistance = _pathFinding->nextPathPos(enemy->getPosition(), getRadius()) - enemy->getPosition();

					angle = atan2(targetDistance.x, targetDistance.z);
					rotation = glm::angleAxis(angle, glm::vec3(0, 1, 0));

					glm::vec3 direction = glm::normalize(targetDistance);

					_velocityX = 0.1f * direction.x;
					_velocityZ = 0.1f * direction.z;

					if (glm::length(_targetPos - enemy->getPosition()) < 7.0f)
					{
						_pathFinding->intializedStartGoal = false;
						_pathFinding->foundGoal = false;
						_pathFinding->clearPathToGoal();
						_pathState = SEARCHING;
					}

					if (glm::length(_targetPos - player->getPosition()) > 7.0f)
					{
						_pathFinding->intializedStartGoal = false;
						_pathFinding->foundGoal = false;
						_pathFinding->clearPathToGoal();
						_pathState = SEARCHING;
					}

					if (glm::length(enemy->getPosition() - player->getPosition()) < 7.0f)
					{
						_isAtGoal = true;
						_pathState = ATTACKING;
					}
				}
			}break;
			case ATTACKING:
			{
				if (glm::length(enemy->getPosition() - player->getPosition()) > 7.0f)
				{
					_pathFinding->intializedStartGoal = false;
					_pathFinding->foundGoal = false;
					_pathFinding->clearPathToGoal();
					_pathState = SEARCHING;
				}
				else
				{
					glm::vec3 playerDir = enemy->getPosition() - player->getPosition();
					angle = glm::degrees(atan2(playerDir.x, playerDir.z));
					rotation = glm::angleAxis(glm::radians(angle), glm::vec3(0, 1, 0));
				}
			}break;
			}

			_position = _position + glm::vec3(_velocityX, _velocityY, _velocityZ);
			enemy->setPosition(_position);
			enemy->setRotation(rotation);

		}break;
		case EnemyTypes::Robot:
		{
			switch (_pathState)
			{
			case SEARCHING:
			{
				if (glm::length(enemy->getPosition() - player->getPosition()) < 10.0f)
				{
					_isAtGoal = true;
					_pathState = ATTACKING;
				}

				_pathFinding->findPath(enemy->getPosition(), player->getPosition(), map);
				_isAtGoal = false;
				if (_pathFinding->foundGoal)
				{
					_targetPos = player->getPosition();
					_pathState = FOUND_GOAL;
				}
			}break;
			case FOUND_GOAL:
			{
				if (!_isAtGoal)
				{
					glm::vec3 targetDistance = _pathFinding->nextPathPos(enemy->getPosition(), getRadius()) - enemy->getPosition();

					angle = atan2(targetDistance.x, targetDistance.z);
					rotation = glm::angleAxis(angle, glm::vec3(0, 1, 0));

					glm::vec3 direction = glm::normalize(targetDistance);

					_velocityX = 0.1f * direction.x;
					_velocityZ = 0.1f * direction.z;

					if (glm::length(_targetPos - enemy->getPosition()) < 7.0f)
					{
						_pathFinding->intializedStartGoal = false;
						_pathFinding->foundGoal = false;
						_pathFinding->clearPathToGoal();
						_pathState = SEARCHING;
					}

					if (glm::length(_targetPos - player->getPosition()) > 7.0f)
					{
						_pathFinding->intializedStartGoal = false;
						_pathFinding->foundGoal = false;
						_pathFinding->clearPathToGoal();
						_pathState = SEARCHING;
					}

					if (glm::length(enemy->getPosition() - player->getPosition()) < 7.0f)
					{
						_isAtGoal = true;
						_pathState = ATTACKING;
					}
				}
			}break;
			case ATTACKING:
			{
				if (glm::length(enemy->getPosition() - player->getPosition()) > 7.0f)
				{
					_pathFinding->intializedStartGoal = false;
					_pathFinding->foundGoal = false;
					_pathFinding->clearPathToGoal();
					_pathState = SEARCHING;
				}
				else
				{
					glm::vec3 playerDir = enemy->getPosition() - player->getPosition();
					angle = glm::degrees(atan2(playerDir.x, playerDir.z));
					rotation = glm::angleAxis(glm::radians(angle), glm::vec3(0, 1, 0));
				}
			}break;
			}

			_position = _position + glm::vec3(_velocityX, _velocityY, _velocityZ);
			enemy->setPosition(_position);
			enemy->setRotation(rotation);

		}break;
		case EnemyTypes::AlienBoss:
		{
			switch (_pathState)
			{
			case SEARCHING:
			{
				if (glm::length(enemy->getPosition() - player->getPosition()) < 10.0f)
				{
					_isAtGoal = true;
					_pathState = ATTACKING;
				}

				_pathFinding->findPath(enemy->getPosition(), player->getPosition(), map);
				_isAtGoal = false;
				if (_pathFinding->foundGoal)
				{
					_targetPos = player->getPosition();
					_pathState = FOUND_GOAL;
				}
			}break;
			case FOUND_GOAL:
			{
				if (!_isAtGoal)
				{
					glm::vec3 targetDistance = _pathFinding->nextPathPos(enemy->getPosition(), getRadius()) - enemy->getPosition();

					angle = atan2(targetDistance.x, targetDistance.z);
					rotation = glm::angleAxis(angle, glm::vec3(0, 1, 0));

					glm::vec3 direction = glm::normalize(targetDistance);

					_velocityX = 0.1f * direction.x;
					_velocityZ = 0.1f * direction.z;

					if (glm::length(_targetPos - enemy->getPosition()) < 7.0f)
					{
						_pathFinding->intializedStartGoal = false;
						_pathFinding->foundGoal = false;
						_pathFinding->clearPathToGoal();
						_pathState = SEARCHING;
					}

					if (glm::length(_targetPos - player->getPosition()) > 7.0f)
					{
						_pathFinding->intializedStartGoal = false;
						_pathFinding->foundGoal = false;
						_pathFinding->clearPathToGoal();
						_pathState = SEARCHING;
					}

					if (glm::length(enemy->getPosition() - player->getPosition()) < 7.0f)
					{
						_isAtGoal = true;
						_pathState = ATTACKING;
					}
				}
			}break;
			case ATTACKING:
			{
				if (glm::length(enemy->getPosition() - player->getPosition()) > 7.0f)
				{
					_pathFinding->intializedStartGoal = false;
					_pathFinding->foundGoal = false;
					_pathFinding->clearPathToGoal();
					_pathState = SEARCHING;
				}
				else
				{
					glm::vec3 playerDir = enemy->getPosition() - player->getPosition();
					angle = glm::degrees(atan2(playerDir.x, playerDir.z));
					rotation = glm::angleAxis(glm::radians(angle), glm::vec3(0, 1, 0));
				}
			}break;
			}

			_position = _position + glm::vec3(_velocityX, _velocityY, _velocityZ);
			enemy->setPosition(_position);
			enemy->setRotation(rotation);

		}break;
	}

	// debug for pathfinding
		int tempX = enemy->getPosition().x;
		int tempZ = enemy->getPosition().z;
		map[tempX][tempZ] = 2;
	//	/*for (int i = 0; i < _pathFinding->_visitedList.size(); i++)
	//	{
	//		map[(int)_pathFinding->_visitedList[i]->m_xcoord][(int)_pathFinding->_visitedList[i]->m_zcoord] = 3;
	//	}
	//	for (int i = 0; i < _pathFinding->_openList.size(); i++)
	//	{
	//		map[(int)_pathFinding->_openList[i]->m_xcoord][(int)_pathFinding->_openList[i]->m_zcoord] = 3;
	//	}
		for (int i = 0; i < _pathFinding->_pathToEnd.size(); i++)
		{
			map[(int)_pathFinding->_pathToEnd[i]->x][(int)_pathFinding->_pathToEnd[i]->z] = 3;
		}
}

glm::vec3 EnemyComponent::getPosition()
{
	auto enemy = entity->getComponent<Component::TransformComponent>();

	return enemy->getPosition();
}

float EnemyComponent::getRadius()
{
	return 1.0f;
}

std::shared_ptr<Hydra::World::IEntity> EnemyComponent::getPlayerComponent()
{
	std::shared_ptr<Hydra::World::IEntity> player;
	auto world = entity->getParent()->getChildren();
	for (size_t i = 0; i < world.size(); i++) {
		if (world[i]->getName() == "Player") {
			player = world[i];
		}
	}
	return player;
}

void EnemyComponent::serialize(nlohmann::json& json) const {
	json = {
		{ "position",{ _position.x, _position.y, _position.z } },
		{ "startPosition",{ _startPosition.x, _startPosition.y, _startPosition.z } },
		{ "velocityX", _velocityX },
		{ "velocityY", _velocityY },
		{ "velocityZ", _velocityZ },
		{ "enemyID", (int)_enemyID },
		{ "pathState", (int)_pathState }
	};
	for (size_t i = 0; i < 64; i++)
	{
		for (size_t j = 0; j < 64; j++)
		{
			json["map"][i][j] = map[i][j];
		}
	}
}

void EnemyComponent::deserialize(nlohmann::json& json) {
	auto& pos = json["position"];
	_position = glm::vec3{ pos[0].get<float>(), pos[1].get<float>(), pos[2].get<float>() };

	auto& startpos = json["startPosition"];
	_startPosition = glm::vec3{ startpos[0].get<float>(), startpos[1].get<float>(), startpos[2].get<float>() };

	_velocityX = json["velocityX"].get<float>();
	_velocityY = json["velocityY"].get<float>();
	_velocityZ = json["velocityZ"].get<float>();

	_enemyID = (EnemyTypes)json["enemyID"].get<int>();
	_pathState = (PathState)json["pathState"].get<int>();
	for (size_t i = 0; i < 64; i++)
	{
		for (size_t j = 0; j < 64; j++)
		{
			map[i][j] = json["map"][i][j].get<int>();
		}
	}
}

// Register UI buttons in the debug UI
// Note: This function won't always be called
void EnemyComponent::registerUI() {
	ImGui::InputFloat("X", &_position.x);
	ImGui::InputFloat("Y", &_position.y);
	ImGui::InputFloat("Z", &_position.z);
	ImGui::InputFloat("startY", &_startPosition.y);
	ImGui::InputInt("pathState", &_debugState);
	ImGui::InputFloat("targetX", &_targetPos.x);
	ImGui::InputFloat("targetY", &_targetPos.y);
	ImGui::InputFloat("targetZ", &_targetPos.z);
	ImGui::Checkbox("isAtGoal", &_isAtGoal);
}

int Hydra::Component::EnemyComponent::getWall(int x, int y)
{
	int result = 0;
	if (map[x][y] == 1)
	{
		result = 1;
	}
	else if (map[x][y] == 2)
	{
		result = 2;
	}
	else if (map[x][y] == 3)
	{
		result = 3;
	}
	return result;
}

<commit_msg>lite snabba fixar<commit_after>// This is a personal academic project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/**
* EnemyComponent/AI.
*
* License: Mozilla Public License Version 2.0 (https://www.mozilla.org/en-US/MPL/2.0/ OR See accompanying file LICENSE)
* Authors:
*  - Dan Printzell
*/
#include <hydra/component/aicomponent.hpp>
#include <imgui/imgui.h>

using namespace Hydra::World;
using namespace Hydra::Component;

EnemyComponent::EnemyComponent(IEntity* entity) : IComponent(entity), _enemyID(EnemyTypes::Alien), _position(0,0,0) {}

EnemyComponent::EnemyComponent(IEntity* entity, EnemyTypes enemyID, glm::vec3 pos) : IComponent(entity), _enemyID(enemyID),  _position(pos){
	_velocityX = 0;
	_velocityY = 0;
	_velocityZ = 0;
	_startPosition = glm::vec3(0, 0, 0);
	_patrolPointReached = false;
	_falling = false;
	_pathState = SEARCHING;
	lastTime = 0;

	for (int i = 0; i < WORLD_SIZE; i++)
	{
		for (int j = 0; j < WORLD_SIZE; j++)
		{
			map[i][j] = 0;
		}
	}

	for (int i = 0; i < 20; i++)
	{
		map[10][12+i] = 1;
	}
}

EnemyComponent::~EnemyComponent() { }

void EnemyComponent::tick(TickAction action, float delta) {
	// If you only have one TickAction in 'wantTick' you don't need to check the tickaction here.

	auto enemy = entity->getComponent<Component::TransformComponent>();
	std::shared_ptr<Hydra::World::IEntity> playerEntity = getPlayerComponent();
	auto player = playerEntity->getComponent<Component::PlayerComponent>();

	_velocityX = 0;
	_velocityY = 0;
	_velocityZ = 0;
	_debugState = _pathState;

	if (_startPosition == glm::vec3(0, 0, 0))
	{
		enemy->setPosition(_position);
		_startPosition = enemy->getPosition();
	}

	switch (_enemyID)
	{
		case EnemyTypes::Alien:
		{
			switch (_pathState)
			{
			case SEARCHING:
			{
				if (glm::length(enemy->getPosition() - player->getPosition()) < 10.0f)
				{
					_isAtGoal = true;
					_pathState = ATTACKING;
				}

				_pathFinding->findPath(enemy->getPosition(), player->getPosition(), map);
				_isAtGoal = false;
				if (_pathFinding->foundGoal)
				{
					_targetPos = player->getPosition();
					_pathState = FOUND_GOAL;
				}
			}break;
			case FOUND_GOAL:
			{
				if (!_isAtGoal)
				{
					glm::vec3 targetDistance = _pathFinding->nextPathPos(enemy->getPosition(), getRadius()) - enemy->getPosition();

					angle = atan2(targetDistance.x, targetDistance.z);
					rotation = glm::angleAxis(angle, glm::vec3(0, 1, 0));

					glm::vec3 direction = glm::normalize(targetDistance);

					_velocityX = 0.1f * direction.x;
					_velocityZ = 0.1f * direction.z;

					if (glm::length(_targetPos - enemy->getPosition()) < 7.0f)
					{
						_pathFinding->intializedStartGoal = false;
						_pathFinding->foundGoal = false;
						_pathFinding->clearPathToGoal();
						_pathState = SEARCHING;
					}

					if (glm::length(_targetPos - player->getPosition()) > 7.0f)
					{
						_pathFinding->intializedStartGoal = false;
						_pathFinding->foundGoal = false;
						_pathFinding->clearPathToGoal();
						_pathState = SEARCHING;
					}

					if (glm::length(enemy->getPosition() - player->getPosition()) < 7.0f)
					{
						_isAtGoal = true;
						_pathState = ATTACKING;
					}
				}
			}break;
			case ATTACKING:
			{
				if (glm::length(enemy->getPosition() - player->getPosition()) > 8.0f)
				{
					_pathFinding->intializedStartGoal = false;
					_pathFinding->foundGoal = false;
					_pathFinding->clearPathToGoal();
					_pathState = SEARCHING;
				}
				else
				{
					glm::vec3 playerDir = player->getPosition() - enemy->getPosition();
					angle = atan2(playerDir.x, playerDir.z);
					rotation = glm::angleAxis(angle, glm::vec3(0, 1, 0));
				}
			}break;
			}

			_position = _position + glm::vec3(_velocityX, _velocityY, _velocityZ);
			enemy->setPosition(_position);
			enemy->setRotation(rotation);

		}break;
		case EnemyTypes::Robot:
		{
			switch (_pathState)
			{
			case SEARCHING:
			{
				if (glm::length(enemy->getPosition() - player->getPosition()) < 10.0f)
				{
					_isAtGoal = true;
					_pathState = ATTACKING;
				}

				_pathFinding->findPath(enemy->getPosition(), player->getPosition(), map);
				_isAtGoal = false;
				if (_pathFinding->foundGoal)
				{
					_targetPos = player->getPosition();
					_pathState = FOUND_GOAL;
				}
			}break;
			case FOUND_GOAL:
			{
				if (!_isAtGoal)
				{
					glm::vec3 targetDistance = _pathFinding->nextPathPos(enemy->getPosition(), getRadius()) - enemy->getPosition();

					angle = atan2(targetDistance.x, targetDistance.z);
					rotation = glm::angleAxis(angle, glm::vec3(0, 1, 0));

					glm::vec3 direction = glm::normalize(targetDistance);

					_velocityX = 0.1f * direction.x;
					_velocityZ = 0.1f * direction.z;

					if (glm::length(_targetPos - enemy->getPosition()) < 7.0f)
					{
						_pathFinding->intializedStartGoal = false;
						_pathFinding->foundGoal = false;
						_pathFinding->clearPathToGoal();
						_pathState = SEARCHING;
					}

					if (glm::length(_targetPos - player->getPosition()) > 7.0f)
					{
						_pathFinding->intializedStartGoal = false;
						_pathFinding->foundGoal = false;
						_pathFinding->clearPathToGoal();
						_pathState = SEARCHING;
					}

					if (glm::length(enemy->getPosition() - player->getPosition()) < 7.0f)
					{
						_isAtGoal = true;
						_pathState = ATTACKING;
					}
				}
			}break;
			case ATTACKING:
			{
				if (glm::length(enemy->getPosition() - player->getPosition()) > 8.0f)
				{
					_pathFinding->intializedStartGoal = false;
					_pathFinding->foundGoal = false;
					_pathFinding->clearPathToGoal();
					_pathState = SEARCHING;
				}
				else
				{
					glm::vec3 playerDir = player->getPosition() - enemy->getPosition();
					angle = atan2(playerDir.x, playerDir.z);
					rotation = glm::angleAxis(angle, glm::vec3(0, 1, 0));
				}
			}break;
			}

			_position = _position + glm::vec3(_velocityX, _velocityY, _velocityZ);
			enemy->setPosition(_position);
			enemy->setRotation(rotation);

		}break;
		case EnemyTypes::AlienBoss:
		{
			switch (_pathState)
			{
			case SEARCHING:
			{
				if (glm::length(enemy->getPosition() - player->getPosition()) < 10.0f)
				{
					_isAtGoal = true;
					_pathState = ATTACKING;
				}

				_pathFinding->findPath(enemy->getPosition(), player->getPosition(), map);
				_isAtGoal = false;
				if (_pathFinding->foundGoal)
				{
					_targetPos = player->getPosition();
					_pathState = FOUND_GOAL;
				}
			}break;
			case FOUND_GOAL:
			{
				if (!_isAtGoal)
				{
					glm::vec3 targetDistance = _pathFinding->nextPathPos(enemy->getPosition(), getRadius()) - enemy->getPosition();

					angle = atan2(targetDistance.x, targetDistance.z);
					rotation = glm::angleAxis(angle, glm::vec3(0, 1, 0));

					glm::vec3 direction = glm::normalize(targetDistance);

					_velocityX = 0.1f * direction.x;
					_velocityZ = 0.1f * direction.z;

					if (glm::length(_targetPos - enemy->getPosition()) < 7.0f)
					{
						_pathFinding->intializedStartGoal = false;
						_pathFinding->foundGoal = false;
						_pathFinding->clearPathToGoal();
						_pathState = SEARCHING;
					}

					if (glm::length(_targetPos - player->getPosition()) > 7.0f)
					{
						_pathFinding->intializedStartGoal = false;
						_pathFinding->foundGoal = false;
						_pathFinding->clearPathToGoal();
						_pathState = SEARCHING;
					}

					if (glm::length(enemy->getPosition() - player->getPosition()) < 7.0f)
					{
						_isAtGoal = true;
						_pathState = ATTACKING;
					}
				}
			}break;
			case ATTACKING:
			{
				if (glm::length(enemy->getPosition() - player->getPosition()) > 8.0f)
				{
					_pathFinding->intializedStartGoal = false;
					_pathFinding->foundGoal = false;
					_pathFinding->clearPathToGoal();
					_pathState = SEARCHING;
				}
				else
				{
					glm::vec3 playerDir = player->getPosition() - enemy->getPosition();
					angle = atan2(playerDir.x, playerDir.z);
					rotation = glm::angleAxis(angle, glm::vec3(0, 1, 0));
				}
			}break;
			}

			_position = _position + glm::vec3(_velocityX, _velocityY, _velocityZ);
			enemy->setPosition(_position);
			enemy->setRotation(rotation);

		}break;
	}

	 //debug for pathfinding
		//int tempX = enemy->getPosition().x;
		//int tempZ = enemy->getPosition().z;
		//map[tempX][tempZ] = 2;
		//for (int i = 0; i < _pathFinding->_visitedList.size(); i++)
		//{
		//	map[(int)_pathFinding->_visitedList[i]->m_xcoord][(int)_pathFinding->_visitedList[i]->m_zcoord] = 3;
		//}
		//for (int i = 0; i < _pathFinding->_openList.size(); i++)
		//{
		//	map[(int)_pathFinding->_openList[i]->m_xcoord][(int)_pathFinding->_openList[i]->m_zcoord] = 3;
		//}
		//for (int i = 0; i < _pathFinding->_pathToEnd.size(); i++)
		//{
		//	map[(int)_pathFinding->_pathToEnd[i]->x][(int)_pathFinding->_pathToEnd[i]->z] = 3;
		//}
}

glm::vec3 EnemyComponent::getPosition()
{
	auto enemy = entity->getComponent<Component::TransformComponent>();

	return enemy->getPosition();
}

float EnemyComponent::getRadius()
{
	return 1.0f;
}

std::shared_ptr<Hydra::World::IEntity> EnemyComponent::getPlayerComponent()
{
	std::shared_ptr<Hydra::World::IEntity> player;
	auto world = entity->getParent()->getChildren();
	for (size_t i = 0; i < world.size(); i++) {
		if (world[i]->getName() == "Player") {
			player = world[i];
		}
	}
	return player;
}

void EnemyComponent::serialize(nlohmann::json& json) const {
	json = {
		{ "position",{ _position.x, _position.y, _position.z } },
		{ "startPosition",{ _startPosition.x, _startPosition.y, _startPosition.z } },
		{ "velocityX", _velocityX },
		{ "velocityY", _velocityY },
		{ "velocityZ", _velocityZ },
		{ "enemyID", (int)_enemyID },
		{ "pathState", (int)_pathState }
	};
	for (size_t i = 0; i < 64; i++)
	{
		for (size_t j = 0; j < 64; j++)
		{
			json["map"][i][j] = map[i][j];
		}
	}
}

void EnemyComponent::deserialize(nlohmann::json& json) {
	auto& pos = json["position"];
	_position = glm::vec3{ pos[0].get<float>(), pos[1].get<float>(), pos[2].get<float>() };

	auto& startpos = json["startPosition"];
	_startPosition = glm::vec3{ startpos[0].get<float>(), startpos[1].get<float>(), startpos[2].get<float>() };

	_velocityX = json["velocityX"].get<float>();
	_velocityY = json["velocityY"].get<float>();
	_velocityZ = json["velocityZ"].get<float>();

	_enemyID = (EnemyTypes)json["enemyID"].get<int>();
	_pathState = (PathState)json["pathState"].get<int>();
	for (size_t i = 0; i < 64; i++)
	{
		for (size_t j = 0; j < 64; j++)
		{
			map[i][j] = json["map"][i][j].get<int>();
		}
	}
}

// Register UI buttons in the debug UI
// Note: This function won't always be called
void EnemyComponent::registerUI() {
	ImGui::InputFloat("X", &_position.x);
	ImGui::InputFloat("Y", &_position.y);
	ImGui::InputFloat("Z", &_position.z);
	ImGui::InputFloat("startY", &_startPosition.y);
	ImGui::InputInt("pathState", &_debugState);
	ImGui::InputFloat("targetX", &_targetPos.x);
	ImGui::InputFloat("targetY", &_targetPos.y);
	ImGui::InputFloat("targetZ", &_targetPos.z);
	ImGui::Checkbox("isAtGoal", &_isAtGoal);
}

int Hydra::Component::EnemyComponent::getWall(int x, int y)
{
	int result = 0;
	if (map[x][y] == 1)
	{
		result = 1;
	}
	else if (map[x][y] == 2)
	{
		result = 2;
	}
	else if (map[x][y] == 3)
	{
		result = 3;
	}
	return result;
}

<|endoftext|>


<commit_before># include <Siv3D.hpp>
# include "asc\AscNovel.hpp"

void Main()
{
	Window::Resize(1280, 720);
	TextureAsset::Register(L"character1", L"character1.png");
	TextureAsset::Register(L"character2", L"character2.png");
	TextureAsset::Register(L"character3", L"character3.png");
	TextureAsset::Register(L"test_message_box", L"test_message_box.png");
	TextureAsset::Register(L"test_choice_box", L"test_choice_box.png");
	FontAsset::Register(L"test_name", 30, L"メイリオ");
	FontAsset::Register(L"test_text", 30, L"メイリオ");

	asc::Novel novel;

	while (System::Update())
	{
		if(Input::Key0.clicked)
			novel.start(0);

		if(Input::Key1.clicked)
			novel.start(1);

		if(Input::Key2.clicked)
			novel.start(2);

		if (Input::Key3.clicked)
			novel.start(3);

		if (Input::Key4.clicked)
			novel.start(4);

		if (Input::Key5.clicked)
			novel.start(5);

		if (Input::Key6.clicked)
			novel.start(6);

		if (Input::Key7.clicked)
			novel.start(7);

		if (Input::Key8.clicked)
			novel.start(8);

		if (Input::Key9.clicked)
			novel.start(9);

		novel.update();

		if(novel.isUpdating())
			novel.draw();
	}
}
<commit_msg>Change FilePath.<commit_after># include <Siv3D.hpp>
# include "asc\AscNovel.hpp"

void Main()
{
	Window::Resize(1280, 720);
	TextureAsset::Register(L"character1", L"Assets/character1.png");
	TextureAsset::Register(L"character2", L"Assets/character2.png");
	TextureAsset::Register(L"character3", L"Assets/character3.png");
	TextureAsset::Register(L"test_message_box", L"Assets/test_message_box.png");
	TextureAsset::Register(L"test_choice_box", L"Assets/test_choice_box.png");
	FontAsset::Register(L"test_name", 30, L"メイリオ");
	FontAsset::Register(L"test_text", 30, L"メイリオ");

	asc::Novel novel;

	while (System::Update())
	{
		if(Input::Key0.clicked)
			novel.start(0);

		if(Input::Key1.clicked)
			novel.start(1);

		if(Input::Key2.clicked)
			novel.start(2);

		if (Input::Key3.clicked)
			novel.start(3);

		if (Input::Key4.clicked)
			novel.start(4);

		if (Input::Key5.clicked)
			novel.start(5);

		if (Input::Key6.clicked)
			novel.start(6);

		if (Input::Key7.clicked)
			novel.start(7);

		if (Input::Key8.clicked)
			novel.start(8);

		if (Input::Key9.clicked)
			novel.start(9);

		novel.update();

		if(novel.isUpdating())
			novel.draw();
	}
}
<|endoftext|>


<commit_before>#include <string>
#include <iostream>
#include <cstring>

#include <boost/format.hpp>

#include "Krystal.h"
#include "Context.h"

#include "template.cs.h"

using namespace std;

int main(int argc, char * argv[]) {
	// make sure we received a filename
	if (argc != 2) {
		cerr << "Usage: ./krystal [FILENAME]" << endl;
		return 255;
	}

	Rakjin::Context context = Rakjin::Context();
	string* fileNameFromArg = new string(argv[1]);
	context.insertIncludedFile(fileNameFromArg);

	Rakjin::KstFile* kstFile = NULL;
	string* fileNameToProcess = context.getUnprocessedFileName();

	do
	{
		try
		{
			// parse file and fill context
			kstFile = new Rakjin::KstFile(fileNameToProcess, context);
		}
		catch (string error)
		{
			cerr << "ERROR: " << error << endl;
			return 255;
		}

		context.markIncludedFileAsProcessed(fileNameToProcess);
		fileNameToProcess = context.getUnprocessedFileName();
	}
	while(fileNameToProcess != NULL);

	cout << *(kstFile->getParsed()); // the last parsed

    delete kstFile;
	return 0;
}

<commit_msg>restructure main loop and try-catch<commit_after>#include <string>
#include <iostream>
#include <cstring>

#include <boost/format.hpp>

#include "Krystal.h"
#include "Context.h"

#include "template.cs.h"

using namespace std;

int main(int argc, char * argv[]) {
	// make sure we received a filename
	if (argc != 2) {
		cerr << "Usage: ./krystal [FILENAME]" << endl;
		return 255;
	}

	Rakjin::Context context = Rakjin::Context();
	string* fileNameFromArg = new string(argv[1]);
	context.insertIncludedFile(fileNameFromArg);

	Rakjin::KstFile* kstFile = NULL;
	string* fileNameToProcess = NULL;

	try
	{
		// process file from argument
		kstFile = new Rakjin::KstFile(fileNameFromArg, context);
		context.markIncludedFileAsProcessed(fileNameFromArg);

		// process including files if any
		for(fileNameToProcess = context.getUnprocessedFileName();
			fileNameToProcess != NULL;
			fileNameToProcess = context.getUnprocessedFileName())
		{
			new Rakjin::KstFile(fileNameToProcess, context);
			context.markIncludedFileAsProcessed(fileNameToProcess);
		}
	}
	catch (string error)
	{
		cerr << "ERROR: " << error << endl;
		return 255;
	}

	cout << *(kstFile->getParsed()); // the first parsed

    delete kstFile;
	return 0;
}

<|endoftext|>


<commit_before>#include <string>
#include <iostream>
#include <cstring>

#include <boost/format.hpp>

#include "Krystal.h"
#include "Context.h"

#include "template.cs.h"

using namespace std;

int main(int argc, char * argv[]) {
	// make sure we received a filename
	if (argc != 2) {
		cerr << "Usage: ./krystal [FILENAME]" << endl;
		return 255;
	}

	Rakjin::Context context = Rakjin::Context();
	string* fileNameFromArg = new string(argv[1]);
	context.insertIncludedFile(fileNameFromArg);

	// try and open the KST file
	Rakjin::KstFile* kstFile = NULL;
	try
	{
		kstFile = new Rakjin::KstFile(argv[1], context);
	}
	catch (string error)
	{
		cerr << "ERROR: " << error << endl;
		return 255;
	}

	cout << *(kstFile->getParsed());

    delete kstFile;
	return 0;
}

<commit_msg>process #include directive in .kst file<commit_after>#include <string>
#include <iostream>
#include <cstring>

#include <boost/format.hpp>

#include "Krystal.h"
#include "Context.h"

#include "template.cs.h"

using namespace std;

int main(int argc, char * argv[]) {
	// make sure we received a filename
	if (argc != 2) {
		cerr << "Usage: ./krystal [FILENAME]" << endl;
		return 255;
	}

	Rakjin::Context context = Rakjin::Context();
	string* fileNameFromArg = new string(argv[1]);
	context.insertIncludedFile(fileNameFromArg);

	// try and open the KST file
	Rakjin::KstFile* kstFile = NULL;
	string* fileName = NULL; //context.getAnUnprocessedFromIncludedFilesMap();

	for(fileName = context.getUnprocessedFileName();
		fileName != NULL;
		fileName = context.getUnprocessedFileName())
	{
		try
		{
			kstFile = new Rakjin::KstFile(fileName->c_str(), context);
		}
		catch (string error)
		{
			cerr << "ERROR: " << error << endl;
			return 255;
		}

		context.markIncludedFileAsProcessed(fileName);
	}

	cout << *(kstFile->getParsed()); // the last parsed

    delete kstFile;
	return 0;
}

<|endoftext|>


<commit_before>/*
Copyright (c) 2016 Teka101

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include <log4cplus/configurator.h>
#include <log4cplus/loggingmacros.h>
#include "Brain.h"
#include "CurlHelpers.h"
#include "MHEHardDevContainer.h"
#include "MHEDatabase.h"
#include "MHEHardware.h"
#include "MHEWeb.h"

int main(int ac, char **av)
{
    MHEDatabase *db = NULL;
    SpeechRecognize *sr = NULL;
    MHEMobileNotify *notify = NULL;
    MHEHardDevContainer *hardDev = NULL;
    MHESpeechService *ss = NULL;
    MHEWeb *ws = NULL;
    boost::program_options::options_description desc("ConfigFile");
    boost::program_options::variables_map vm;
    log4cplus::Logger logger;
    std::string gcmAppId, speechFile, speechLang;
    long curlTimeout;
    float hysteresisMin, hysteresisMax;
    int webPort, brainRefresh;

    log4cplus::PropertyConfigurator::doConfigure("log4cplus.properties");
    logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("Main"));
    desc.add_options()
        ("WebServer.port", boost::program_options::value<int>(&webPort)->default_value(8080))
        ("Brain.refresh", boost::program_options::value<int>(&brainRefresh)->default_value(300))
        ("Notify.gcmAppId", boost::program_options::value<std::string>(&gcmAppId))
        ("General.curlTimeout", boost::program_options::value<long>(&curlTimeout)->default_value(1000L))
        ("General.speechFile", boost::program_options::value<std::string>(&speechFile))
        ("General.speechLang", boost::program_options::value<std::string>(&speechLang))
        ("Heating.hysteresisMin", boost::program_options::value<float>(&hysteresisMin)->default_value(0))
        ("Heating.hysteresisMax", boost::program_options::value<float>(&hysteresisMax)->default_value(0))
        ;
    try
    {
        std::ifstream settings_file("config.ini", std::ifstream::in);
        boost::program_options::store(boost::program_options::parse_config_file(settings_file, desc, true), vm);
        settings_file.close();
    }
    catch (const boost::program_options::unknown_option &e)
    {
        LOG4CPLUS_ERROR(logger, LOG4CPLUS_TEXT("Unkown option: " << e.get_option_name()));
        exit(1);
    }
    boost::program_options::notify(vm);
    LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("Application starting..."));
    LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - General.curlTimeout=" << curlTimeout));
    LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - WebServer.port=" << webPort));
    LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - Brain.refresh=" << brainRefresh));
    LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - Notify.gcmAppId=" << gcmAppId));
    curlInit(curlTimeout);
    try
    {
        db = new MHEDatabase();
        if (logger.isEnabledFor(log4cplus::DEBUG_LOG_LEVEL))
        {
            std::vector<DBCondition> conds = db->getConditions();
            BOOST_FOREACH(DBCondition cond, conds)
            {
                LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - " << (std::string)cond));
            }
            std::vector<DBGraph> graphs = db->getGraphs();
            BOOST_FOREACH(DBGraph graph, graphs)
            {
                LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - " << (std::string)graph));
            }
            std::vector<DBRoom> rooms = db->getRooms();
            BOOST_FOREACH(DBRoom room, rooms)
            {
                LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - " << (std::string)room));
            }
            std::vector<DBRoomGraphCond> roomGraphConds = db->getRoomGraphCondByActiveDaysAndCalendar();
            BOOST_FOREACH(DBRoomGraphCond rgc, roomGraphConds)
            {
                LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - " << (std::string)rgc));
            }
        }

        sr = (speechFile.size() == 0 ? NULL : new SpeechRecognize(speechFile));
        notify = (gcmAppId.size() == 0 ? NULL : new MHEMobileNotify(gcmAppId, db, sr));
        hardDev = new MHEHardDevContainer(*db);
        ss = new MHESpeechService(sr, speechLang);
        ws = new MHEWeb(webPort, db, hardDev, notify, ss);

        if (!ws->isStarted())
            LOG4CPLUS_ERROR(logger, LOG4CPLUS_TEXT("Unable to start web server !"));
        else
        {
            Brain b(db, hardDev, brainRefresh, notify);

            if (hysteresisMin > 0 && hysteresisMax > 0)
		b.setHysteresis(hysteresisMin, hysteresisMax);
            b.start();
        }
        LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("Application stopping..."));
    }
    catch (const boost::thread_interrupted &e)
    {
        LOG4CPLUS_ERROR(logger, LOG4CPLUS_TEXT("Error interrupted thread !"));
    }
    catch (const boost::thread_resource_error &e)
    {
        LOG4CPLUS_ERROR(logger, LOG4CPLUS_TEXT("Error when creating thread: native_error=" << e.native_error()));
    }
    delete ws;
    delete notify;
    delete sr;
    delete ss;
    delete hardDev;
    delete db;
    curlDestroy();
    return 0;
}
<commit_msg>Catch all exceptions<commit_after>/*
Copyright (c) 2016 Teka101

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include <log4cplus/configurator.h>
#include <log4cplus/loggingmacros.h>
#include "Brain.h"
#include "CurlHelpers.h"
#include "MHEHardDevContainer.h"
#include "MHEDatabase.h"
#include "MHEHardware.h"
#include "MHEWeb.h"

int main(int ac, char **av)
{
    MHEDatabase *db = NULL;
    SpeechRecognize *sr = NULL;
    MHEMobileNotify *notify = NULL;
    MHEHardDevContainer *hardDev = NULL;
    MHESpeechService *ss = NULL;
    MHEWeb *ws = NULL;
    boost::program_options::options_description desc("ConfigFile");
    boost::program_options::variables_map vm;
    log4cplus::Logger logger;
    std::string gcmAppId, speechFile, speechLang;
    long curlTimeout;
    float hysteresisMin, hysteresisMax;
    int webPort, brainRefresh;

    log4cplus::PropertyConfigurator::doConfigure("log4cplus.properties");
    logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("Main"));
    desc.add_options()
        ("WebServer.port", boost::program_options::value<int>(&webPort)->default_value(8080))
        ("Brain.refresh", boost::program_options::value<int>(&brainRefresh)->default_value(300))
        ("Notify.gcmAppId", boost::program_options::value<std::string>(&gcmAppId))
        ("General.curlTimeout", boost::program_options::value<long>(&curlTimeout)->default_value(1000L))
        ("General.speechFile", boost::program_options::value<std::string>(&speechFile))
        ("General.speechLang", boost::program_options::value<std::string>(&speechLang))
        ("Heating.hysteresisMin", boost::program_options::value<float>(&hysteresisMin)->default_value(0))
        ("Heating.hysteresisMax", boost::program_options::value<float>(&hysteresisMax)->default_value(0))
        ;
    try
    {
        std::ifstream settings_file("config.ini", std::ifstream::in);
        boost::program_options::store(boost::program_options::parse_config_file(settings_file, desc, true), vm);
        settings_file.close();
    }
    catch (const boost::program_options::unknown_option &e)
    {
        LOG4CPLUS_ERROR(logger, LOG4CPLUS_TEXT("Unkown option: " << e.get_option_name()));
        exit(1);
    }
    boost::program_options::notify(vm);
    LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("Application starting..."));
    LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - General.curlTimeout=" << curlTimeout));
    LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - WebServer.port=" << webPort));
    LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - Brain.refresh=" << brainRefresh));
    LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - Notify.gcmAppId=" << gcmAppId));
    curlInit(curlTimeout);
    try
    {
        db = new MHEDatabase();
        if (logger.isEnabledFor(log4cplus::DEBUG_LOG_LEVEL))
        {
            std::vector<DBCondition> conds = db->getConditions();
            BOOST_FOREACH(DBCondition cond, conds)
            {
                LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - " << (std::string)cond));
            }
            std::vector<DBGraph> graphs = db->getGraphs();
            BOOST_FOREACH(DBGraph graph, graphs)
            {
                LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - " << (std::string)graph));
            }
            std::vector<DBRoom> rooms = db->getRooms();
            BOOST_FOREACH(DBRoom room, rooms)
            {
                LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - " << (std::string)room));
            }
            std::vector<DBRoomGraphCond> roomGraphConds = db->getRoomGraphCondByActiveDaysAndCalendar();
            BOOST_FOREACH(DBRoomGraphCond rgc, roomGraphConds)
            {
                LOG4CPLUS_DEBUG(logger, LOG4CPLUS_TEXT("main - " << (std::string)rgc));
            }
        }

        sr = (speechFile.size() == 0 ? NULL : new SpeechRecognize(speechFile));
        notify = (gcmAppId.size() == 0 ? NULL : new MHEMobileNotify(gcmAppId, db, sr));
        hardDev = new MHEHardDevContainer(*db);
        ss = new MHESpeechService(sr, speechLang);
        ws = new MHEWeb(webPort, db, hardDev, notify, ss);

        if (!ws->isStarted())
            LOG4CPLUS_ERROR(logger, LOG4CPLUS_TEXT("Unable to start web server !"));
        else
        {
            Brain b(db, hardDev, brainRefresh, notify);

            if (hysteresisMin > 0 && hysteresisMax > 0)
		b.setHysteresis(hysteresisMin, hysteresisMax);
            b.start();
        }
        LOG4CPLUS_INFO(logger, LOG4CPLUS_TEXT("Application stopping..."));
    }
    catch (const boost::exception &e)
    {
        LOG4CPLUS_ERROR(logger, LOG4CPLUS_TEXT("Error " << boost::diagnostic_information(e)));
    }
    delete ws;
    delete notify;
    delete sr;
    delete ss;
    delete hardDev;
    delete db;
    curlDestroy();
    return 0;
}
<|endoftext|>


<commit_before>/*
Main Module

This module is where out program will start and where all other modules and functions
are called. It will contain the main loop and will link to the other modules.
 */

 //Libraries to include
 #include <Input/Metering/ADE7753.h>							//ADE7753 communication library
 #include <Output/Screen/Adafruit-GFX-library/Adafruit_GFX.h>	//Library that the sharp memory library extends
 #include <Output/Screen/SharpMemoryLCD/SharpMemoryLcd.h>		//Sharp Memory LCD communication library
 #include <PowerSaving/RocketScreamLibrary/LowPower/h>			//Provides powerful low-power sleep functions

 //User defined modules
 #include "Input/UserInput/UserInput.h"
 #include "Input/Metering/Metering.h"
 #include "Output/Screen/Screen.h"
 #include "Output/LEDs/LED.h"

//Main Loop
void loop() {
	int millisecondsToSleep = 1000;

	sleep(millsecondsToSleep);		//Sleep for the interval
	performActions();
}

//The function we will go to when we want to sleep,
//Will return true if there weren't any errors during the sleep cycle
//Will return false if there was an error generated during the sleep cycle
bool sleep(int milliseconds){

	return true;
}

//The function we will go to when we are awake and we want to perform out actions
//before we go back to sleep.
bool performActions(){

	return true;
}

<commit_msg>Added Visual Refresh Rate Constant<commit_after>/*
Main Module

This module is where out program will start and where all other modules and functions
are called. It will contain the main loop and will link to the other modules.
 */

 //Libraries to include
 #include <Input/Metering/ADE7753.h>							//ADE7753 communication library
 #include <Output/Screen/Adafruit-GFX-library/Adafruit_GFX.h>	//Library that the sharp memory library extends
 #include <Output/Screen/SharpMemoryLCD/SharpMemoryLcd.h>		//Sharp Memory LCD communication library
 #include <PowerSaving/RocketScreamLibrary/LowPower/h>			//Provides powerful low-power sleep functions

 //User defined modules
 #include "Input/UserInput/UserInput.h"
 #include "Input/Metering/Metering.h"
 #include "Output/Screen/Screen.h"
 #include "Output/LED/LED.h"

//Main Loop
void loop() {
	const double VISIONRATE = 60;
	double millisecondsToSleep = ( 1 / VISIONRATE) * 1000; 	//Refresh rate of our eyes is 60Hz, or 16.667 ms.
															//If we want to refresh our

	sleep(millsecondsToSleep);		//Sleep for the interval
	performActions();
}

//The function we will go to when we want to sleep,
//Will return true if there weren't any errors during the sleep cycle
//Will return false if there was an error generated during the sleep cycle
bool sleep(int milliseconds){

	return true;
}

//The function we will go to when we are awake and we want to perform out actions
//before we go back to sleep.
bool performActions(){

	return true;
}

<|endoftext|>