<commit_before>// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/v8.h"

#include "src/version.h"

// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION     3
#define MINOR_VERSION     29
#define BUILD_NUMBER      26
#define PATCH_LEVEL       0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1

// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME            ""

#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif

#define SX(x) #x
#define S(x) SX(x)

#if PATCH_LEVEL > 0
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "."              \
        S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER)                  \
        CANDIDATE_STRING
#endif

namespace v8 {
namespace internal {

int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;

// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
  const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
  const char* is_simulator = " SIMULATOR";
#else
  const char* is_simulator = "";
#endif  // USE_SIMULATOR
  if (GetPatch() > 0) {
    SNPrintF(str, "%d.%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
             is_simulator);
  } else {
    SNPrintF(str, "%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), candidate,
             is_simulator);
  }
}

// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
  if (soname_ == NULL || *soname_ == '\0') {
    // Generate generic SONAME if no specific SONAME is defined.
    const char* candidate = IsCandidate() ? "-candidate" : "";
    if (GetPatch() > 0) {
      SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
    } else {
      SNPrintF(str, "libv8-%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), candidate);
    }
  } else {
    // Use specific SONAME.
    SNPrintF(str, "%s", soname_);
  }
}

} }  // namespace v8::internal
<commit_msg>[Auto-roll] Bump up version to 3.29.28.0<commit_after>// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/v8.h"

#include "src/version.h"

// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION     3
#define MINOR_VERSION     29
#define BUILD_NUMBER      28
#define PATCH_LEVEL       0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1

// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME            ""

#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif

#define SX(x) #x
#define S(x) SX(x)

#if PATCH_LEVEL > 0
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "."              \
        S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER)                  \
        CANDIDATE_STRING
#endif

namespace v8 {
namespace internal {

int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;

// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
  const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
  const char* is_simulator = " SIMULATOR";
#else
  const char* is_simulator = "";
#endif  // USE_SIMULATOR
  if (GetPatch() > 0) {
    SNPrintF(str, "%d.%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
             is_simulator);
  } else {
    SNPrintF(str, "%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), candidate,
             is_simulator);
  }
}

// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
  if (soname_ == NULL || *soname_ == '\0') {
    // Generate generic SONAME if no specific SONAME is defined.
    const char* candidate = IsCandidate() ? "-candidate" : "";
    if (GetPatch() > 0) {
      SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
    } else {
      SNPrintF(str, "libv8-%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), candidate);
    }
  } else {
    // Use specific SONAME.
    SNPrintF(str, "%s", soname_);
  }
}

} }  // namespace v8::internal
<|endoftext|>


<commit_before>#pragma once

#include "constants.hpp"
#include "logger.hpp"
#include "receiver.hpp"
#include "session.hpp"

class connection_manager final {
public:
  connection_manager(void) : timer_(0),
                             session_state_(session::state::none),
                             exit_receiver_starter_(true) {
    timer_ = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    if (timer_) {
      dispatch_source_set_timer(timer_, dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), 1.0 * NSEC_PER_SEC, 0);
      dispatch_source_set_event_handler(timer_, ^{
        auto state = session::get_state();
        if (session_state_ != state) {
          session_state_ = state;

          if (session_state_ == session::state::active) {
            exit_receiver_starter_ = false;
            receiver_starter_thread_ = std::thread([this] { this->receiver_starter_worker(); });

          } else {
            exit_receiver_starter_ = true;
            receiver_starter_thread_.join();
            receiver_.stop();
          }
        }
      });

      dispatch_resume(timer_);
    }
  }

  ~connection_manager(void) {
    exit_receiver_starter_ = true;
    receiver_starter_thread_.join();

    if (timer_) {
      dispatch_release(timer_);
      timer_ = 0;
    }
  }

private:
  void receiver_starter_worker(void) {
    while (!exit_receiver_starter_) {
      try {
        receiver_.start();
        break;
      } catch (...) {
        logger::get_logger().error("failed to start receiver_. retrying...");
      }

      std::this_thread::sleep_for(std::chrono::seconds(1));
    }
  }

  dispatch_source_t timer_;
  session::state session_state_;

  std::thread receiver_starter_thread_;
  volatile bool exit_receiver_starter_;
  receiver receiver_;
};
<commit_msg>remove dispatch_source_t<commit_after>#pragma once

#include "constants.hpp"
#include "logger.hpp"
#include "receiver.hpp"
#include "session.hpp"

class connection_manager final {
public:
  connection_manager(void) : exit_loop_(false),
                             session_state_(session::state::none),
                             exit_receiver_starter_(true) {
    thread_ = std::thread([this] { this->worker(); });
  }

  ~connection_manager(void) {
    exit_loop_ = true;
    exit_receiver_starter_ = true;

    receiver_starter_thread_.join();
    thread_.join();
  }

private:
  void worker(void) {
    while (!exit_loop_) {
      auto state = session::get_state();
      if (session_state_ != state) {
        session_state_ = state;

        if (session_state_ == session::state::active) {
          exit_receiver_starter_ = false;
          receiver_starter_thread_ = std::thread([this] { this->receiver_starter_worker(); });

        } else {
          exit_receiver_starter_ = true;
          receiver_starter_thread_.join();
          receiver_.stop();
        }
      }

      std::this_thread::sleep_for(std::chrono::seconds(1));
    }
  }

  void receiver_starter_worker(void) {
    while (!exit_receiver_starter_) {
      try {
        receiver_.start();
        break;
      } catch (...) {
        logger::get_logger().error("failed to start receiver_. retrying...");
      }

      std::this_thread::sleep_for(std::chrono::seconds(1));
    }
  }

  std::thread thread_;
  volatile bool exit_loop_;

  session::state session_state_;

  std::thread receiver_starter_thread_;
  volatile bool exit_receiver_starter_;
  receiver receiver_;
};
<|endoftext|>


<commit_before>#define FASTLED_INTERNAL
#include "FastLED.h"

FASTLED_USING_NAMESPACE

#if 0

#if defined(FASTLED_AVR) && !defined(TEENSYDUINO) && !defined(LIB8_ATTINY)
extern "C" {
// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
// the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

typedef union { unsigned long _long; uint8_t raw[4]; } tBytesForLong;
// tBytesForLong FastLED_timer0_overflow_count;
volatile unsigned long FastLED_timer0_overflow_count=0;
volatile unsigned long FastLED_timer0_millis = 0;

LIB8STATIC void  __attribute__((always_inline)) fastinc32 (volatile uint32_t & _long) {
  uint8_t b = ++((tBytesForLong&)_long).raw[0];
  if(!b) {
    b = ++((tBytesForLong&)_long).raw[1];
    if(!b) {
      b = ++((tBytesForLong&)_long).raw[2];
      if(!b) {
        ++((tBytesForLong&)_long).raw[3];
      }
    }
  }
}

#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ISR(TIM0_OVF_vect)
#else
ISR(TIMER0_OVF_vect)
#endif
{
  fastinc32(FastLED_timer0_overflow_count);
  // FastLED_timer0_overflow_count++;
}

// there are 1024 microseconds per overflow counter tick.
unsigned long millis()
{
        unsigned long m;
        uint8_t oldSREG = SREG;

        // disable interrupts while we read FastLED_timer0_millis or we might get an
        // inconsistent value (e.g. in the middle of a write to FastLED_timer0_millis)
        cli();
        m = FastLED_timer0_overflow_count;  //._long;
        SREG = oldSREG;

        return (m*(MICROSECONDS_PER_TIMER0_OVERFLOW/8))/(1000/8);
}

unsigned long micros() {
        unsigned long m;
        uint8_t oldSREG = SREG, t;

        cli();
        m = FastLED_timer0_overflow_count; // ._long;
#if defined(TCNT0)
        t = TCNT0;
#elif defined(TCNT0L)
        t = TCNT0L;
#else
        #error TIMER 0 not defined
#endif

#ifdef TIFR0
        if ((TIFR0 & _BV(TOV0)) && (t < 255))
                ++m;
#else
        if ((TIFR & _BV(TOV0)) && (t < 255))
                ++m;
#endif

        SREG = oldSREG;

        return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

void delay(unsigned long ms)
{
        uint16_t start = (uint16_t)micros();

        while (ms > 0) {
                if (((uint16_t)micros() - start) >= 1000) {
                        --ms;
                        start += 1000;
                }
        }
}

#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
void init()
{
  // this needs to be called before setup() or some functions won't
  // work there
  sei();

  // on the ATmega168, timer 0 is also used for fast hardware pwm
  // (using phase-correct PWM would mean that timer 0 overflowed half as often
  // resulting in different millis() behavior on the ATmega8 and ATmega168)
#if defined(TCCR0A) && defined(WGM01)
  sbi(TCCR0A, WGM01);
  sbi(TCCR0A, WGM00);
#endif

  // set timer 0 prescale factor to 64
#if defined(__AVR_ATmega128__)
  // CPU specific: different values for the ATmega128
  sbi(TCCR0, CS02);
#elif defined(TCCR0) && defined(CS01) && defined(CS00)
  // this combination is for the standard atmega8
  sbi(TCCR0, CS01);
  sbi(TCCR0, CS00);
#elif defined(TCCR0B) && defined(CS01) && defined(CS00)
  // this combination is for the standard 168/328/1280/2560
  sbi(TCCR0B, CS01);
  sbi(TCCR0B, CS00);
#elif defined(TCCR0A) && defined(CS01) && defined(CS00)
  // this combination is for the __AVR_ATmega645__ series
  sbi(TCCR0A, CS01);
  sbi(TCCR0A, CS00);
#else
  #error Timer 0 prescale factor 64 not set correctly
#endif

  // enable timer 0 overflow interrupt
#if defined(TIMSK) && defined(TOIE0)
  sbi(TIMSK, TOIE0);
#elif defined(TIMSK0) && defined(TOIE0)
  sbi(TIMSK0, TOIE0);
#else
  #error	Timer 0 overflow interrupt not set correctly
#endif

  // timers 1 and 2 are used for phase-correct hardware pwm
  // this is better for motors as it ensures an even waveform
  // note, however, that fast pwm mode can achieve a frequency of up
  // 8 MHz (with a 16 MHz clock) at 50% duty cycle

#if defined(TCCR1B) && defined(CS11) && defined(CS10)
  TCCR1B = 0;

  // set timer 1 prescale factor to 64
  sbi(TCCR1B, CS11);
#if F_CPU >= 8000000L
  sbi(TCCR1B, CS10);
#endif
#elif defined(TCCR1) && defined(CS11) && defined(CS10)
  sbi(TCCR1, CS11);
#if F_CPU >= 8000000L
  sbi(TCCR1, CS10);
#endif
#endif
  // put timer 1 in 8-bit phase correct pwm mode
#if defined(TCCR1A) && defined(WGM10)
  sbi(TCCR1A, WGM10);
#elif defined(TCCR1)
  #warning this needs to be finished
#endif

  // set timer 2 prescale factor to 64
#if defined(TCCR2) && defined(CS22)
  sbi(TCCR2, CS22);
#elif defined(TCCR2B) && defined(CS22)
  sbi(TCCR2B, CS22);
#else
  #warning Timer 2 not finished (may not be present on this CPU)
#endif

  // configure timer 2 for phase correct pwm (8-bit)
#if defined(TCCR2) && defined(WGM20)
  sbi(TCCR2, WGM20);
#elif defined(TCCR2A) && defined(WGM20)
  sbi(TCCR2A, WGM20);
#else
  #warning Timer 2 not finished (may not be present on this CPU)
#endif

#if defined(TCCR3B) && defined(CS31) && defined(WGM30)
  sbi(TCCR3B, CS31);		// set timer 3 prescale factor to 64
  sbi(TCCR3B, CS30);
  sbi(TCCR3A, WGM30);		// put timer 3 in 8-bit phase correct pwm mode
#endif

#if defined(TCCR4A) && defined(TCCR4B) && defined(TCCR4D) /* beginning of timer4 block for 32U4 and similar */
  sbi(TCCR4B, CS42);		// set timer4 prescale factor to 64
  sbi(TCCR4B, CS41);
  sbi(TCCR4B, CS40);
  sbi(TCCR4D, WGM40);		// put timer 4 in phase- and frequency-correct PWM mode
  sbi(TCCR4A, PWM4A);		// enable PWM mode for comparator OCR4A
  sbi(TCCR4C, PWM4D);		// enable PWM mode for comparator OCR4D
#else /* beginning of timer4 block for ATMEGA1280 and ATMEGA2560 */
#if defined(TCCR4B) && defined(CS41) && defined(WGM40)
  sbi(TCCR4B, CS41);		// set timer 4 prescale factor to 64
  sbi(TCCR4B, CS40);
  sbi(TCCR4A, WGM40);		// put timer 4 in 8-bit phase correct pwm mode
#endif
#endif /* end timer4 block for ATMEGA1280/2560 and similar */

#if defined(TCCR5B) && defined(CS51) && defined(WGM50)
  sbi(TCCR5B, CS51);		// set timer 5 prescale factor to 64
  sbi(TCCR5B, CS50);
  sbi(TCCR5A, WGM50);		// put timer 5 in 8-bit phase correct pwm mode
#endif

#if defined(ADCSRA)
  // set a2d prescale factor to 128
  // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range.
  // XXX: this will not work properly for other clock speeds, and
  // this code should use F_CPU to determine the prescale factor.
  sbi(ADCSRA, ADPS2);
  sbi(ADCSRA, ADPS1);
  sbi(ADCSRA, ADPS0);

  // enable a2d conversions
  sbi(ADCSRA, ADEN);
#endif

  // the bootloader connects pins 0 and 1 to the USART; disconnect them
  // here so they can be used as normal digital i/o; they will be
  // reconnected in Serial.begin()
#if defined(UCSRB)
  UCSRB = 0;
#elif defined(UCSR0B)
  UCSR0B = 0;
#endif
}
};
#endif

#endif

<commit_msg>Update wiring.cpp documentation<commit_after>#define FASTLED_INTERNAL
#include "FastLED.h"

/// @file wiring.cpp
/// Re-implementation of Arduino core functions
/// @deprecated No longer used

FASTLED_USING_NAMESPACE

#if 0

#if defined(FASTLED_AVR) && !defined(TEENSYDUINO) && !defined(LIB8_ATTINY)
extern "C" {
// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
// the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

typedef union { unsigned long _long; uint8_t raw[4]; } tBytesForLong;
// tBytesForLong FastLED_timer0_overflow_count;
volatile unsigned long FastLED_timer0_overflow_count=0;
volatile unsigned long FastLED_timer0_millis = 0;

LIB8STATIC void  __attribute__((always_inline)) fastinc32 (volatile uint32_t & _long) {
  uint8_t b = ++((tBytesForLong&)_long).raw[0];
  if(!b) {
    b = ++((tBytesForLong&)_long).raw[1];
    if(!b) {
      b = ++((tBytesForLong&)_long).raw[2];
      if(!b) {
        ++((tBytesForLong&)_long).raw[3];
      }
    }
  }
}

#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ISR(TIM0_OVF_vect)
#else
ISR(TIMER0_OVF_vect)
#endif
{
  fastinc32(FastLED_timer0_overflow_count);
  // FastLED_timer0_overflow_count++;
}

// there are 1024 microseconds per overflow counter tick.
unsigned long millis()
{
        unsigned long m;
        uint8_t oldSREG = SREG;

        // disable interrupts while we read FastLED_timer0_millis or we might get an
        // inconsistent value (e.g. in the middle of a write to FastLED_timer0_millis)
        cli();
        m = FastLED_timer0_overflow_count;  //._long;
        SREG = oldSREG;

        return (m*(MICROSECONDS_PER_TIMER0_OVERFLOW/8))/(1000/8);
}

unsigned long micros() {
        unsigned long m;
        uint8_t oldSREG = SREG, t;

        cli();
        m = FastLED_timer0_overflow_count; // ._long;
#if defined(TCNT0)
        t = TCNT0;
#elif defined(TCNT0L)
        t = TCNT0L;
#else
        #error TIMER 0 not defined
#endif

#ifdef TIFR0
        if ((TIFR0 & _BV(TOV0)) && (t < 255))
                ++m;
#else
        if ((TIFR & _BV(TOV0)) && (t < 255))
                ++m;
#endif

        SREG = oldSREG;

        return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

void delay(unsigned long ms)
{
        uint16_t start = (uint16_t)micros();

        while (ms > 0) {
                if (((uint16_t)micros() - start) >= 1000) {
                        --ms;
                        start += 1000;
                }
        }
}

#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
void init()
{
  // this needs to be called before setup() or some functions won't
  // work there
  sei();

  // on the ATmega168, timer 0 is also used for fast hardware pwm
  // (using phase-correct PWM would mean that timer 0 overflowed half as often
  // resulting in different millis() behavior on the ATmega8 and ATmega168)
#if defined(TCCR0A) && defined(WGM01)
  sbi(TCCR0A, WGM01);
  sbi(TCCR0A, WGM00);
#endif

  // set timer 0 prescale factor to 64
#if defined(__AVR_ATmega128__)
  // CPU specific: different values for the ATmega128
  sbi(TCCR0, CS02);
#elif defined(TCCR0) && defined(CS01) && defined(CS00)
  // this combination is for the standard atmega8
  sbi(TCCR0, CS01);
  sbi(TCCR0, CS00);
#elif defined(TCCR0B) && defined(CS01) && defined(CS00)
  // this combination is for the standard 168/328/1280/2560
  sbi(TCCR0B, CS01);
  sbi(TCCR0B, CS00);
#elif defined(TCCR0A) && defined(CS01) && defined(CS00)
  // this combination is for the __AVR_ATmega645__ series
  sbi(TCCR0A, CS01);
  sbi(TCCR0A, CS00);
#else
  #error Timer 0 prescale factor 64 not set correctly
#endif

  // enable timer 0 overflow interrupt
#if defined(TIMSK) && defined(TOIE0)
  sbi(TIMSK, TOIE0);
#elif defined(TIMSK0) && defined(TOIE0)
  sbi(TIMSK0, TOIE0);
#else
  #error	Timer 0 overflow interrupt not set correctly
#endif

  // timers 1 and 2 are used for phase-correct hardware pwm
  // this is better for motors as it ensures an even waveform
  // note, however, that fast pwm mode can achieve a frequency of up
  // 8 MHz (with a 16 MHz clock) at 50% duty cycle

#if defined(TCCR1B) && defined(CS11) && defined(CS10)
  TCCR1B = 0;

  // set timer 1 prescale factor to 64
  sbi(TCCR1B, CS11);
#if F_CPU >= 8000000L
  sbi(TCCR1B, CS10);
#endif
#elif defined(TCCR1) && defined(CS11) && defined(CS10)
  sbi(TCCR1, CS11);
#if F_CPU >= 8000000L
  sbi(TCCR1, CS10);
#endif
#endif
  // put timer 1 in 8-bit phase correct pwm mode
#if defined(TCCR1A) && defined(WGM10)
  sbi(TCCR1A, WGM10);
#elif defined(TCCR1)
  #warning this needs to be finished
#endif

  // set timer 2 prescale factor to 64
#if defined(TCCR2) && defined(CS22)
  sbi(TCCR2, CS22);
#elif defined(TCCR2B) && defined(CS22)
  sbi(TCCR2B, CS22);
#else
  #warning Timer 2 not finished (may not be present on this CPU)
#endif

  // configure timer 2 for phase correct pwm (8-bit)
#if defined(TCCR2) && defined(WGM20)
  sbi(TCCR2, WGM20);
#elif defined(TCCR2A) && defined(WGM20)
  sbi(TCCR2A, WGM20);
#else
  #warning Timer 2 not finished (may not be present on this CPU)
#endif

#if defined(TCCR3B) && defined(CS31) && defined(WGM30)
  sbi(TCCR3B, CS31);		// set timer 3 prescale factor to 64
  sbi(TCCR3B, CS30);
  sbi(TCCR3A, WGM30);		// put timer 3 in 8-bit phase correct pwm mode
#endif

#if defined(TCCR4A) && defined(TCCR4B) && defined(TCCR4D) /* beginning of timer4 block for 32U4 and similar */
  sbi(TCCR4B, CS42);		// set timer4 prescale factor to 64
  sbi(TCCR4B, CS41);
  sbi(TCCR4B, CS40);
  sbi(TCCR4D, WGM40);		// put timer 4 in phase- and frequency-correct PWM mode
  sbi(TCCR4A, PWM4A);		// enable PWM mode for comparator OCR4A
  sbi(TCCR4C, PWM4D);		// enable PWM mode for comparator OCR4D
#else /* beginning of timer4 block for ATMEGA1280 and ATMEGA2560 */
#if defined(TCCR4B) && defined(CS41) && defined(WGM40)
  sbi(TCCR4B, CS41);		// set timer 4 prescale factor to 64
  sbi(TCCR4B, CS40);
  sbi(TCCR4A, WGM40);		// put timer 4 in 8-bit phase correct pwm mode
#endif
#endif /* end timer4 block for ATMEGA1280/2560 and similar */

#if defined(TCCR5B) && defined(CS51) && defined(WGM50)
  sbi(TCCR5B, CS51);		// set timer 5 prescale factor to 64
  sbi(TCCR5B, CS50);
  sbi(TCCR5A, WGM50);		// put timer 5 in 8-bit phase correct pwm mode
#endif

#if defined(ADCSRA)
  // set a2d prescale factor to 128
  // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range.
  // XXX: this will not work properly for other clock speeds, and
  // this code should use F_CPU to determine the prescale factor.
  sbi(ADCSRA, ADPS2);
  sbi(ADCSRA, ADPS1);
  sbi(ADCSRA, ADPS0);

  // enable a2d conversions
  sbi(ADCSRA, ADEN);
#endif

  // the bootloader connects pins 0 and 1 to the USART; disconnect them
  // here so they can be used as normal digital i/o; they will be
  // reconnected in Serial.begin()
#if defined(UCSRB)
  UCSRB = 0;
#elif defined(UCSR0B)
  UCSR0B = 0;
#endif
}
};
#endif

#endif

<|endoftext|>


<commit_before>#include <cassert>
#include <cmath>
#include "common/swaglog.h"
#include "common/timing.h"

#include "lsm6ds3_gyro.hpp"

#define DEG2RAD(x) ((x) * M_PI / 180.0)

LSM6DS3_Gyro::LSM6DS3_Gyro(I2CBus *bus) : I2CSensor(bus) {}

int LSM6DS3_Gyro::init(){
  int ret = 0;
  uint8_t buffer[1];

  ret = read_register(LSM6DS3_GYRO_I2C_REG_ID, buffer, 1);
  if(ret < 0){
    LOGE("Reading chip ID failed: %d", ret);
    goto fail;
  }

  if(buffer[0] != LSM6DS3_GYRO_CHIP_ID){
    LOGE("Chip ID wrong. Got: %d, Expected %d", buffer[0], LSM6DS3_GYRO_CHIP_ID);
    ret = -1;
    goto fail;
  }

  // TODO: set scale. Default is +- 250 deg/s
  ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL2_G, LSM6DS3_GYRO_ODR_104HZ);
  if (ret < 0){
    goto fail;
  }

fail:
  return ret;
}

void LSM6DS3_Gyro::get_event(cereal::SensorEventData::Builder &event){

  uint64_t start_time = nanos_since_boot();
  uint8_t buffer[6];
  int len = read_register(LSM6DS3_GYRO_I2C_REG_OUTX_L_G, buffer, sizeof(buffer));
  assert(len == sizeof(buffer));

  float scale = 250.0f / (1 << 15);
  float x = DEG2RAD(read_16_bit(buffer[0], buffer[1]) * scale);
  float y = DEG2RAD(read_16_bit(buffer[2], buffer[3]) * scale);
  float z = DEG2RAD(read_16_bit(buffer[4], buffer[5]) * scale);

  event.setSource(cereal::SensorEventData::SensorSource::LSM6DS3);
  event.setVersion(1);
  event.setSensor(SENSOR_GYRO_UNCALIBRATED);
  event.setType(SENSOR_TYPE_GYROSCOPE_UNCALIBRATED);
  event.setTimestamp(start_time);

  float xyz[] = {y, -x, z};
  kj::ArrayPtr<const float> vs(&xyz[0], 3);

  auto svec = event.initAcceleration();
  svec.setV(vs);
  svec.setStatus(true);

}
<commit_msg>Fix gyro field name<commit_after>#include <cassert>
#include <cmath>
#include "common/swaglog.h"
#include "common/timing.h"

#include "lsm6ds3_gyro.hpp"

#define DEG2RAD(x) ((x) * M_PI / 180.0)

LSM6DS3_Gyro::LSM6DS3_Gyro(I2CBus *bus) : I2CSensor(bus) {}

int LSM6DS3_Gyro::init(){
  int ret = 0;
  uint8_t buffer[1];

  ret = read_register(LSM6DS3_GYRO_I2C_REG_ID, buffer, 1);
  if(ret < 0){
    LOGE("Reading chip ID failed: %d", ret);
    goto fail;
  }

  if(buffer[0] != LSM6DS3_GYRO_CHIP_ID){
    LOGE("Chip ID wrong. Got: %d, Expected %d", buffer[0], LSM6DS3_GYRO_CHIP_ID);
    ret = -1;
    goto fail;
  }

  // TODO: set scale. Default is +- 250 deg/s
  ret = set_register(LSM6DS3_GYRO_I2C_REG_CTRL2_G, LSM6DS3_GYRO_ODR_104HZ);
  if (ret < 0){
    goto fail;
  }

fail:
  return ret;
}

void LSM6DS3_Gyro::get_event(cereal::SensorEventData::Builder &event){

  uint64_t start_time = nanos_since_boot();
  uint8_t buffer[6];
  int len = read_register(LSM6DS3_GYRO_I2C_REG_OUTX_L_G, buffer, sizeof(buffer));
  assert(len == sizeof(buffer));

  float scale = 250.0f / (1 << 15);
  float x = DEG2RAD(read_16_bit(buffer[0], buffer[1]) * scale);
  float y = DEG2RAD(read_16_bit(buffer[2], buffer[3]) * scale);
  float z = DEG2RAD(read_16_bit(buffer[4], buffer[5]) * scale);

  event.setSource(cereal::SensorEventData::SensorSource::LSM6DS3);
  event.setVersion(1);
  event.setSensor(SENSOR_GYRO_UNCALIBRATED);
  event.setType(SENSOR_TYPE_GYROSCOPE_UNCALIBRATED);
  event.setTimestamp(start_time);

  float xyz[] = {y, -x, z};
  kj::ArrayPtr<const float> vs(&xyz[0], 3);

  auto svec = event.initGyroUncalibrated();
  svec.setV(vs);
  svec.setStatus(true);

}
<|endoftext|>


<commit_before>#include <QFile>
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QJsonObject>
#include <QJsonDocument>
#include <QDebug>

#include "offroad_alerts.hpp"
#include "common/params.h"

void cleanStackedWidget(QStackedWidget* swidget) {
  while(swidget->count() > 0) {
    QWidget *w = swidget->widget(0);
    swidget->removeWidget(w);
    w->deleteLater();
  }
}

OffroadAlert::OffroadAlert(QWidget* parent) : QFrame(parent) {
  QVBoxLayout *main_layout = new QVBoxLayout();
  main_layout->setMargin(25);

  alerts_stack = new QStackedWidget();
  main_layout->addWidget(alerts_stack, 1);

  // bottom footer
  QHBoxLayout *footer_layout = new QHBoxLayout();
  main_layout->addLayout(footer_layout);

  QPushButton *dismiss_btn = new QPushButton("Dismiss");
  dismiss_btn->setFixedSize(400, 125);
  footer_layout->addWidget(dismiss_btn, 0, Qt::AlignLeft);

  reboot_btn = new QPushButton("Reboot and Update");
  reboot_btn->setFixedSize(600, 125);
  reboot_btn->setVisible(false);
  footer_layout->addWidget(reboot_btn, 0, Qt::AlignRight);

  QObject::connect(dismiss_btn, SIGNAL(released()), this, SIGNAL(closeAlerts()));
#ifdef __aarch64__
  QObject::connect(reboot_btn, &QPushButton::released, [=]() {std::system("sudo reboot");});
#endif

  setLayout(main_layout);
  setStyleSheet(R"(
    * {
      color: white;
    }
    QFrame {
      border-radius: 30px;
      background-color: #393939;
    }
    QPushButton {
      color: black;
      font-size: 50px;
      font-weight: 500;
      border-radius: 30px;
      background-color: white;
    }
  )");
  main_layout->setMargin(50);
}

void OffroadAlert::refresh() {
  parse_alerts();
  cleanStackedWidget(alerts_stack);

  std::vector<char> bytes = Params().read_db_bytes("UpdateAvailable");
  updateAvailable = bytes.size() && bytes[0] == '1';

  reboot_btn->setVisible(updateAvailable);

  QVBoxLayout *layout = new QVBoxLayout;

  if (updateAvailable) {
    QLabel *title = new QLabel("Update Available");
    title->setStyleSheet(R"(
      font-size: 72px;
    )");
    layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop);

    QString release_notes = QString::fromStdString(Params().get("ReleaseNotes"));
    QLabel *body = new QLabel(release_notes);
    body->setStyleSheet(R"(
      font-size: 48px;
    )");
    layout->addWidget(body, 1, Qt::AlignLeft | Qt::AlignTop);
  } else {
    // TODO: paginate the alerts
    for (const auto &alert : alerts) {
      QLabel *l = new QLabel(alert.text);
      l->setWordWrap(true);
      l->setMargin(60);

      QString style = R"(
        font-size: 48px;
      )";
      style.append("background-color: " + QString(alert.severity ? "#E22C2C" : "#292929"));
      l->setStyleSheet(style);

      layout->addWidget(l, 0, Qt::AlignTop);
    }
    layout->setSpacing(20);
  }
  QWidget *w = new QWidget();
  w->setLayout(layout);
  alerts_stack->addWidget(w);
}

void OffroadAlert::parse_alerts() {
  alerts.clear();

  // TODO: only read this once
  QFile inFile("../controls/lib/alerts_offroad.json");
  inFile.open(QIODevice::ReadOnly | QIODevice::Text);
  QByteArray data = inFile.readAll();
  inFile.close();

  QJsonDocument doc = QJsonDocument::fromJson(data);
  if (doc.isNull()) {
    qDebug() << "Parse failed";
  }

  QJsonObject json = doc.object();
  for (const QString &key : json.keys()) {
    std::vector<char> bytes = Params().read_db_bytes(key.toStdString().c_str());

    if (bytes.size()) {
      QJsonDocument doc_par = QJsonDocument::fromJson(QByteArray(bytes.data(), bytes.size()));
      QJsonObject obj = doc_par.object();
      Alert alert = {obj.value("text").toString(), obj.value("severity").toInt()};
      alerts.push_back(alert);
    }
  }
}
<commit_msg>fix reboot button in offroad alerts<commit_after>#include <QFile>
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QJsonObject>
#include <QJsonDocument>
#include <QDebug>

#include "offroad_alerts.hpp"
#include "common/params.h"
#include "selfdrive/hardware/hw.h"

void cleanStackedWidget(QStackedWidget* swidget) {
  while(swidget->count() > 0) {
    QWidget *w = swidget->widget(0);
    swidget->removeWidget(w);
    w->deleteLater();
  }
}

OffroadAlert::OffroadAlert(QWidget* parent) : QFrame(parent) {
  QVBoxLayout *main_layout = new QVBoxLayout();
  main_layout->setMargin(25);

  alerts_stack = new QStackedWidget();
  main_layout->addWidget(alerts_stack, 1);

  // bottom footer
  QHBoxLayout *footer_layout = new QHBoxLayout();
  main_layout->addLayout(footer_layout);

  QPushButton *dismiss_btn = new QPushButton("Dismiss");
  dismiss_btn->setFixedSize(400, 125);
  footer_layout->addWidget(dismiss_btn, 0, Qt::AlignLeft);

  reboot_btn = new QPushButton("Reboot and Update");
  reboot_btn->setFixedSize(600, 125);
  reboot_btn->setVisible(false);
  footer_layout->addWidget(reboot_btn, 0, Qt::AlignRight);

  QObject::connect(dismiss_btn, SIGNAL(released()), this, SIGNAL(closeAlerts()));
  QObject::connect(reboot_btn, &QPushButton::released, [=]() { Hardware::reboot(); });

  setLayout(main_layout);
  setStyleSheet(R"(
    * {
      color: white;
    }
    QFrame {
      border-radius: 30px;
      background-color: #393939;
    }
    QPushButton {
      color: black;
      font-size: 50px;
      font-weight: 500;
      border-radius: 30px;
      background-color: white;
    }
  )");
  main_layout->setMargin(50);
}

void OffroadAlert::refresh() {
  parse_alerts();
  cleanStackedWidget(alerts_stack);

  std::vector<char> bytes = Params().read_db_bytes("UpdateAvailable");
  updateAvailable = bytes.size() && bytes[0] == '1';

  reboot_btn->setVisible(updateAvailable);

  QVBoxLayout *layout = new QVBoxLayout;

  if (updateAvailable) {
    QLabel *title = new QLabel("Update Available");
    title->setStyleSheet(R"(
      font-size: 72px;
    )");
    layout->addWidget(title, 0, Qt::AlignLeft | Qt::AlignTop);

    QString release_notes = QString::fromStdString(Params().get("ReleaseNotes"));
    QLabel *body = new QLabel(release_notes);
    body->setStyleSheet(R"(
      font-size: 48px;
    )");
    layout->addWidget(body, 1, Qt::AlignLeft | Qt::AlignTop);
  } else {
    // TODO: paginate the alerts
    for (const auto &alert : alerts) {
      QLabel *l = new QLabel(alert.text);
      l->setWordWrap(true);
      l->setMargin(60);

      QString style = R"(
        font-size: 48px;
      )";
      style.append("background-color: " + QString(alert.severity ? "#E22C2C" : "#292929"));
      l->setStyleSheet(style);

      layout->addWidget(l, 0, Qt::AlignTop);
    }
    layout->setSpacing(20);
  }
  QWidget *w = new QWidget();
  w->setLayout(layout);
  alerts_stack->addWidget(w);
}

void OffroadAlert::parse_alerts() {
  alerts.clear();

  // TODO: only read this once
  QFile inFile("../controls/lib/alerts_offroad.json");
  inFile.open(QIODevice::ReadOnly | QIODevice::Text);
  QByteArray data = inFile.readAll();
  inFile.close();

  QJsonDocument doc = QJsonDocument::fromJson(data);
  if (doc.isNull()) {
    qDebug() << "Parse failed";
  }

  QJsonObject json = doc.object();
  for (const QString &key : json.keys()) {
    std::vector<char> bytes = Params().read_db_bytes(key.toStdString().c_str());

    if (bytes.size()) {
      QJsonDocument doc_par = QJsonDocument::fromJson(QByteArray(bytes.data(), bytes.size()));
      QJsonObject obj = doc_par.object();
      Alert alert = {obj.value("text").toString(), obj.value("severity").toInt()};
      alerts.push_back(alert);
    }
  }
}
<|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.

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

#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkExceptionObject.h"
#include <iostream>
#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbExtractROI.h"
#include "itkComplexToRealImageFilter.h"
#include "itkComplexToImaginaryImageFilter.h"
#include "otbImageList.h"
#include "otbImageListToVectorImageFilter.h"

int otbImageFileReaderRADComplexFloatExtract(int argc, char* argv[])
{
  // Verify the number of parameters in the command line
  const char * inputFilename  = argv[1];
  const char * outputFilename = argv[2];

  typedef std::complex<float> InputPixelType;
  typedef std::complex<float> OutputPixelType;

  const unsigned int Dimension = 2;

  typedef otb::Image<InputPixelType,  Dimension> InputImageType;
  typedef otb::Image<OutputPixelType, Dimension> OutputCplxImageType;
  typedef otb::Image<int, Dimension>             OutputScalarImageType;
  typedef otb::VectorImage<int, Dimension>       OutputImageType;
  typedef otb::ImageList<OutputScalarImageType>  ImageListType;

  typedef otb::ImageFileReader<InputImageType>  ReaderType;
  typedef otb::ImageFileWriter<OutputImageType> WriterType;
  typedef itk::ComplexToRealImageFilter<OutputCplxImageType, OutputScalarImageType> RealExtractorType;
  typedef itk::ComplexToImaginaryImageFilter<OutputCplxImageType
, OutputScalarImageType> ImaginaryExtractorType;
  typedef otb::ImageListToVectorImageFilter<ImageListType, OutputImageType>           ListToVectorImageFilterType;

  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();

  reader->SetFileName(inputFilename);
  writer->SetFileName(outputFilename);

  typedef otb::ExtractROI<InputPixelType,
      OutputPixelType>  ExtractROIFilterType;

  ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();

  extractROIFilter->SetInput(reader->GetOutput());

  extractROIFilter->SetStartX(10);
  extractROIFilter->SetStartY(10);
  extractROIFilter->SetSizeX(100);
  extractROIFilter->SetSizeY(100);

  // The rest of the code is here to translate the image complexe into
  // a VectorImage of int which each channel is the real and imagynary part

  RealExtractorType::Pointer realExt = RealExtractorType::New();
  ImaginaryExtractorType::Pointer imgExt = ImaginaryExtractorType::New();

  realExt->SetInput(extractROIFilter->GetOutput());
  imgExt->SetInput(extractROIFilter->GetOutput());

  ImageListType::Pointer imList = ImageListType::New();
  imList->PushBack(realExt->GetOutput());
  imList->PushBack(imgExt->GetOutput());
  ListToVectorImageFilterType::Pointer listCaster = ListToVectorImageFilterType::New();
  listCaster->SetInput(imList);

  writer->SetInput(listCaster->GetOutput());
  writer->Update();

  return EXIT_SUCCESS;
}
<commit_msg>ENH : change test pixeltype from int to float<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.

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

#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkExceptionObject.h"
#include <iostream>
#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbExtractROI.h"
#include "itkComplexToRealImageFilter.h"
#include "itkComplexToImaginaryImageFilter.h"
#include "otbImageList.h"
#include "otbImageListToVectorImageFilter.h"

int otbImageFileReaderRADComplexFloatExtract(int argc, char* argv[])
{
  // Verify the number of parameters in the command line
  const char * inputFilename  = argv[1];
  const char * outputFilename = argv[2];

  typedef std::complex<float> InputPixelType;
  typedef std::complex<float> OutputPixelType;

  const unsigned int Dimension = 2;

  typedef otb::Image<InputPixelType,  Dimension> InputImageType;
  typedef otb::Image<OutputPixelType, Dimension> OutputCplxImageType;
  typedef otb::Image<float, Dimension>             OutputScalarImageType;
  typedef otb::VectorImage<float, Dimension>       OutputImageType;
  typedef otb::ImageList<OutputScalarImageType>  ImageListType;

  typedef otb::ImageFileReader<InputImageType>  ReaderType;
  typedef otb::ImageFileWriter<OutputImageType> WriterType;
  typedef itk::ComplexToRealImageFilter<OutputCplxImageType, OutputScalarImageType> RealExtractorType;
  typedef itk::ComplexToImaginaryImageFilter<OutputCplxImageType
, OutputScalarImageType> ImaginaryExtractorType;
  typedef otb::ImageListToVectorImageFilter<ImageListType, OutputImageType>           ListToVectorImageFilterType;

  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer = WriterType::New();

  reader->SetFileName(inputFilename);
  writer->SetFileName(outputFilename);

  typedef otb::ExtractROI<InputPixelType,
      OutputPixelType>  ExtractROIFilterType;

  ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();

  extractROIFilter->SetInput(reader->GetOutput());

  extractROIFilter->SetStartX(10);
  extractROIFilter->SetStartY(10);
  extractROIFilter->SetSizeX(100);
  extractROIFilter->SetSizeY(100);

  // The rest of the code is here to translate the image complexe into
  // a VectorImage of int which each channel is the real and imagynary part

  RealExtractorType::Pointer realExt = RealExtractorType::New();
  ImaginaryExtractorType::Pointer imgExt = ImaginaryExtractorType::New();

  realExt->SetInput(extractROIFilter->GetOutput());
  imgExt->SetInput(extractROIFilter->GetOutput());

  ImageListType::Pointer imList = ImageListType::New();
  imList->PushBack(realExt->GetOutput());
  imList->PushBack(imgExt->GetOutput());
  ListToVectorImageFilterType::Pointer listCaster = ListToVectorImageFilterType::New();
  listCaster->SetInput(imList);

  writer->SetInput(listCaster->GetOutput());
  writer->Update();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#pragma once
#include "imodel.hpp"
#include "frea/matrix.hpp"
#include "spine/optional.hpp"
#include "spine/treenode.hpp"
#include "boundary.hpp"

namespace beat {
	template <class Types>
	class Narrow;

	namespace g2 {
		struct Point;
		struct Line;
		struct Ray;
		struct Segment;
		struct Circle;
		struct Capsule;
		class AABB;
		struct Triangle;
		class Convex;
		using CTGeo = lubee::Types<Convex, Triangle, AABB, Capsule, Circle, Segment, Ray, Line, Point>;

		template <class T>
		using CID = CID_base<T, CTGeo>;

		using frea::Vec2;
		using AMat32 = frea::Mat_t<float, 3,2, true>;

		struct MdlItr;
		struct IModel;
		using Model_SP = std::shared_ptr<IModel>;
		struct IModel {
			virtual Vec2 im_getCenter() const = 0;
			virtual float im_getArea() const = 0;
			virtual float im_getInertia() const = 0;
			virtual void im_getBVolume(Circle& c) const = 0;
			virtual void im_getBVolume(AABB& a) const = 0;
			virtual void* im_getCore() = 0;
			virtual bool im_isLeaf() const = 0;
			virtual const void* im_getCore() const = 0;
			virtual bool im_refresh(Time_t t) const;
			virtual bool im_canCacheShape() const = 0;
			virtual void* im_getUserData() const = 0;
			//! サポート射像
			/*! 均等でないスケーリングは対応しない、移動は後でオフセット、回転はdirを逆にすれば代用可
				・・との理由で行列変換後の物体に対する射像は無し */
			virtual Vec2 im_support(const Vec2& dir) const = 0;
			//! 図形と点の判定
			virtual bool im_hit(const Vec2& p) const = 0;
			virtual uint32_t im_getCID() const = 0;
			virtual Model_SP im_clone() const = 0;
			virtual Vec2 im_toLocal(const Vec2& v) const;
			virtual Vec2 im_toLocalDir(const Vec2& v) const;
			virtual Vec2 im_toWorld(const Vec2& v) const;
			virtual Vec2 im_toWorldDir(const Vec2& v) const;
			virtual const AMat32& im_getToLocal() const;
			virtual const AMat32& im_getToWorld() const;
			const static AMat32 cs_idMat;
			virtual MdlItr im_getInner() const;
			virtual void im_selfCheck(Time_t t) const;
			bool im_hasInner() const;

			virtual void im_transform(void* dst, const AMat32& m) const = 0;
			virtual std::ostream& im_print(std::ostream& os) const = 0;
		};

		//! TにIModelインタフェースを付加
		template <class T>
		struct Model : Model_base<T, IModel> {
			using base_t = Model_base<T, IModel>;
			using base_t::base_t;

			Model() = default;
			Model(const T& t):
				base_t(t)
			{}
			Model(T&& t):
				base_t(std::move(t))
			{}
			// ------- 各種ルーチンの中継 -------
			Model_SP im_clone() const override {
				return std::make_shared<Model<T>>(static_cast<const T&>(*this));
			}
			void im_transform(void* dst, const AMat32& m) const override {
				*reinterpret_cast<T*>(dst) = *this * m;
			}
			void im_getBVolume(Circle& c) const override {
				c = T::bs_getBCircle();
			}
			void im_getBVolume(AABB& a) const override {
				a = T::bs_getBBox();
			}
			float im_getInertia() const override {
				return T::bs_getInertia();
			}
			float im_getArea() const override {
				return T::bs_getArea();
			}
			Vec2 im_getCenter() const override {
				return T::bs_getCenter();
			}
			Vec2 im_support(const Vec2& dir) const override {
				return T::support(dir);
			}
			bool im_hit(const Vec2& pos) const override {
				return T::hit(pos);
			}
		};

		class ITf;
		class GSimplex;
		class TfLeaf_base;
		struct Types {
			using CTGeo = CTGeo;
			using IModel = IModel;
			using ITf = ITf;
			using TfLeaf_base = TfLeaf_base;
			using GJK = GSimplex;
			using Narrow = ::beat::Narrow<Types>;
		};
	}
}
<commit_msg>IModel(2D): デストラクタをvirtualにし忘れていたのを修正<commit_after>#pragma once
#include "imodel.hpp"
#include "frea/matrix.hpp"
#include "spine/optional.hpp"
#include "spine/treenode.hpp"
#include "boundary.hpp"

namespace beat {
	template <class Types>
	class Narrow;

	namespace g2 {
		struct Point;
		struct Line;
		struct Ray;
		struct Segment;
		struct Circle;
		struct Capsule;
		class AABB;
		struct Triangle;
		class Convex;
		using CTGeo = lubee::Types<Convex, Triangle, AABB, Capsule, Circle, Segment, Ray, Line, Point>;

		template <class T>
		using CID = CID_base<T, CTGeo>;

		using frea::Vec2;
		using AMat32 = frea::Mat_t<float, 3,2, true>;

		struct MdlItr;
		struct IModel;
		using Model_SP = std::shared_ptr<IModel>;
		struct IModel {
			virtual Vec2 im_getCenter() const = 0;
			virtual float im_getArea() const = 0;
			virtual float im_getInertia() const = 0;
			virtual void im_getBVolume(Circle& c) const = 0;
			virtual void im_getBVolume(AABB& a) const = 0;
			virtual void* im_getCore() = 0;
			virtual bool im_isLeaf() const = 0;
			virtual const void* im_getCore() const = 0;
			virtual bool im_refresh(Time_t t) const;
			virtual bool im_canCacheShape() const = 0;
			virtual void* im_getUserData() const = 0;
			//! サポート射像
			/*! 均等でないスケーリングは対応しない、移動は後でオフセット、回転はdirを逆にすれば代用可
				・・との理由で行列変換後の物体に対する射像は無し */
			virtual Vec2 im_support(const Vec2& dir) const = 0;
			//! 図形と点の判定
			virtual bool im_hit(const Vec2& p) const = 0;
			virtual uint32_t im_getCID() const = 0;
			virtual Model_SP im_clone() const = 0;
			virtual Vec2 im_toLocal(const Vec2& v) const;
			virtual Vec2 im_toLocalDir(const Vec2& v) const;
			virtual Vec2 im_toWorld(const Vec2& v) const;
			virtual Vec2 im_toWorldDir(const Vec2& v) const;
			virtual const AMat32& im_getToLocal() const;
			virtual const AMat32& im_getToWorld() const;
			const static AMat32 cs_idMat;
			virtual MdlItr im_getInner() const;
			virtual void im_selfCheck(Time_t t) const;
			bool im_hasInner() const;

			virtual void im_transform(void* dst, const AMat32& m) const = 0;
			virtual std::ostream& im_print(std::ostream& os) const = 0;
			virtual ~IModel() {}
		};

		//! TにIModelインタフェースを付加
		template <class T>
		struct Model : Model_base<T, IModel> {
			using base_t = Model_base<T, IModel>;
			using base_t::base_t;

			Model() = default;
			Model(const T& t):
				base_t(t)
			{}
			Model(T&& t):
				base_t(std::move(t))
			{}
			// ------- 各種ルーチンの中継 -------
			Model_SP im_clone() const override {
				return std::make_shared<Model<T>>(static_cast<const T&>(*this));
			}
			void im_transform(void* dst, const AMat32& m) const override {
				*reinterpret_cast<T*>(dst) = *this * m;
			}
			void im_getBVolume(Circle& c) const override {
				c = T::bs_getBCircle();
			}
			void im_getBVolume(AABB& a) const override {
				a = T::bs_getBBox();
			}
			float im_getInertia() const override {
				return T::bs_getInertia();
			}
			float im_getArea() const override {
				return T::bs_getArea();
			}
			Vec2 im_getCenter() const override {
				return T::bs_getCenter();
			}
			Vec2 im_support(const Vec2& dir) const override {
				return T::support(dir);
			}
			bool im_hit(const Vec2& pos) const override {
				return T::hit(pos);
			}
		};

		class ITf;
		class GSimplex;
		class TfLeaf_base;
		struct Types {
			using CTGeo = CTGeo;
			using IModel = IModel;
			using ITf = ITf;
			using TfLeaf_base = TfLeaf_base;
			using GJK = GSimplex;
			using Narrow = ::beat::Narrow<Types>;
		};
	}
}
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkSurfaceVtkLegacyIO.h"

#include "mitkSurface.h"
#include "mitkIOMimeTypes.h"

#include <vtkPolyDataReader.h>
#include <vtkPolyDataWriter.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkXMLPolyDataWriter.h>
#include <vtkErrorCode.h>
#include <vtkSmartPointer.h>

namespace mitk {

SurfaceVtkLegacyIO::SurfaceVtkLegacyIO()
  : SurfaceVtkIO(Surface::GetStaticNameOfClass(), IOMimeTypes::VTK_POLYDATA_LEGACY_MIMETYPE(), "VTK Legacy PolyData")
{
  this->RegisterService();
}

std::vector<itk::SmartPointer<BaseData> > SurfaceVtkLegacyIO::Read()
{
  mitk::Surface::Pointer output = mitk::Surface::New();

  // The legay vtk reader cannot work with input streams
  const std::string fileName = this->GetLocalFileName();
  vtkSmartPointer<vtkPolyDataReader> reader = vtkSmartPointer<vtkPolyDataReader>::New();
  reader->SetFileName(fileName.c_str());
  reader->Update();

  if ( reader->GetOutput() != NULL )
  {
    output->SetVtkPolyData(reader->GetOutput());
  }
  else
  {
    mitkThrow() << "vtkPolyDataReader error: " << vtkErrorCode::GetStringFromErrorCode(reader->GetErrorCode());
  }

  std::vector<BaseData::Pointer> result;
  result.push_back(output.GetPointer());
  return result;
}

IFileIO::ConfidenceLevel SurfaceVtkLegacyIO::GetReaderConfidenceLevel() const
{
  if (AbstractFileIO::GetReaderConfidenceLevel() == Unsupported) return Unsupported;
  vtkSmartPointer<vtkPolyDataReader> reader = vtkSmartPointer<vtkPolyDataReader>::New();
  reader->SetFileName(this->GetLocalFileName().c_str());
  if (reader->IsFilePolyData())
  {
    return Supported;
  }
  return Unsupported;
}

void SurfaceVtkLegacyIO::Write()
{
  ValidateOutputLocation();

  const Surface* input = dynamic_cast<const Surface*>(this->GetInput());

  const unsigned int timesteps = input->GetTimeGeometry()->CountTimeSteps();
  for(unsigned int t = 0; t < timesteps; ++t)
  {
    std::string fileName;
    vtkSmartPointer<vtkPolyData> polyData = this->GetPolyData(t, fileName);
    vtkSmartPointer<vtkPolyDataWriter> writer = vtkSmartPointer<vtkPolyDataWriter>::New();
    writer->SetInputData(polyData);

    // The legacy vtk poly data writer cannot write to streams
    LocalFile localFile(this);
    writer->SetFileName(localFile.GetFileName().c_str());

    if (writer->Write() == 0 || writer->GetErrorCode() != 0 )
    {
      mitkThrow() << "Error during surface writing" << (writer->GetErrorCode() ?
                                                          std::string(": ") + vtkErrorCode::GetStringFromErrorCode(writer->GetErrorCode()) :
                                                          std::string());
    }

    if (this->GetOutputStream() && input->GetTimeGeometry()->CountTimeSteps() > 1)
    {
      MITK_WARN << "Writing multiple time-steps to output streams is not supported. "
                << "Only the first time-step will be written";
      break;
    }
  }
}

SurfaceVtkLegacyIO* SurfaceVtkLegacyIO::IOClone() const
{
  return new SurfaceVtkLegacyIO(*this);
}

}
<commit_msg>Binary data support for vtk writer<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkSurfaceVtkLegacyIO.h"

#include "mitkSurface.h"
#include "mitkIOMimeTypes.h"

#include <vtkPolyDataReader.h>
#include <vtkPolyDataWriter.h>
#include <vtkXMLPolyDataReader.h>
#include <vtkXMLPolyDataWriter.h>
#include <vtkErrorCode.h>
#include <vtkSmartPointer.h>

namespace mitk {

SurfaceVtkLegacyIO::SurfaceVtkLegacyIO()
  : SurfaceVtkIO(Surface::GetStaticNameOfClass(), IOMimeTypes::VTK_POLYDATA_LEGACY_MIMETYPE(), "VTK Legacy PolyData")
{
  Options defaultOptions;
  defaultOptions["Save as binary file"] = true;
  this->SetDefaultWriterOptions(defaultOptions);
  this->RegisterService();
}

std::vector<itk::SmartPointer<BaseData> > SurfaceVtkLegacyIO::Read()
{
  mitk::Surface::Pointer output = mitk::Surface::New();

  // The legay vtk reader cannot work with input streams
  const std::string fileName = this->GetLocalFileName();
  vtkSmartPointer<vtkPolyDataReader> reader = vtkSmartPointer<vtkPolyDataReader>::New();
  reader->SetFileName(fileName.c_str());
  reader->Update();

  if ( reader->GetOutput() != NULL )
  {
    output->SetVtkPolyData(reader->GetOutput());
  }
  else
  {
    mitkThrow() << "vtkPolyDataReader error: " << vtkErrorCode::GetStringFromErrorCode(reader->GetErrorCode());
  }

  std::vector<BaseData::Pointer> result;
  result.push_back(output.GetPointer());
  return result;
}

IFileIO::ConfidenceLevel SurfaceVtkLegacyIO::GetReaderConfidenceLevel() const
{
  if (AbstractFileIO::GetReaderConfidenceLevel() == Unsupported) return Unsupported;
  vtkSmartPointer<vtkPolyDataReader> reader = vtkSmartPointer<vtkPolyDataReader>::New();
  reader->SetFileName(this->GetLocalFileName().c_str());
  if (reader->IsFilePolyData())
  {
    return Supported;
  }
  return Unsupported;
}

void SurfaceVtkLegacyIO::Write()
{
  ValidateOutputLocation();

  const Surface* input = dynamic_cast<const Surface*>(this->GetInput());

  const unsigned int timesteps = input->GetTimeGeometry()->CountTimeSteps();
  for(unsigned int t = 0; t < timesteps; ++t)
  {
    std::string fileName;
    vtkSmartPointer<vtkPolyData> polyData = this->GetPolyData(t, fileName);
    vtkSmartPointer<vtkPolyDataWriter> writer = vtkSmartPointer<vtkPolyDataWriter>::New();
    writer->SetInputData(polyData);
    if (us::any_cast<bool> (GetWriterOption("Save as binary file")))
    {
      writer->SetFileTypeToBinary();
    }
    // The legacy vtk poly data writer cannot write to streams
    LocalFile localFile(this);
    writer->SetFileName(localFile.GetFileName().c_str());

    if (writer->Write() == 0 || writer->GetErrorCode() != 0 )
    {
      mitkThrow() << "Error during surface writing" << (writer->GetErrorCode() ?
                                                          std::string(": ") + vtkErrorCode::GetStringFromErrorCode(writer->GetErrorCode()) :
                                                          std::string());
    }

    if (this->GetOutputStream() && input->GetTimeGeometry()->CountTimeSteps() > 1)
    {
      MITK_WARN << "Writing multiple time-steps to output streams is not supported. "
                << "Only the first time-step will be written";
      break;
    }
  }
}

SurfaceVtkLegacyIO* SurfaceVtkLegacyIO::IOClone() const
{
  return new SurfaceVtkLegacyIO(*this);
}

}
<|endoftext|>


<commit_before>/*
 * opencog/server/CogServerMain.cc
 *
 * Copyright (C) 2002-2007 Novamente LLC
 * Copyright (C) 2008 by Singularity Institute for Artificial Intelligence
 * All Rights Reserved
 *
 * Written by Andre Senna <senna@vettalabs.com>
 *            Gustavo Gama <gama@vettalabs.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <getopt.h>

#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>

#include <utility>
#include <string>

#include <opencog/server/CogServer.h>
#include <opencog/util/Config.h>
#include <opencog/util/Logger.h>
#include <opencog/util/exceptions.h>
#include <opencog/util/misc.h>

using namespace opencog;
using namespace std;

static const char* DEFAULT_CONFIG_FILENAME = "opencog.conf";
static const char* DEFAULT_CONFIG_PATHS[] =
{
    CONFDIR,
#ifndef WIN32
    "/etc",
#endif // !WIN32
    NULL
};

static const char* DEFAULT_MODULE_PATHS[] =
{
    DATADIR,
    "opencog",
    "../opencog",
#ifndef WIN32
    "/usr/share/opencog",
    "/usr/local/share/opencog",
#endif // !WIN32
    NULL
};

static void usage(const char* progname)
{
    std::cerr << "Usage: " << progname << " [[-c <config-file>]..] [[-DOPTION=\"VALUE\"]..]\n\n";
    std::cerr << "Each config file is loaded sequentially, with the values in \n"
        << " later files overwriting earlier. Then each singular option overrides \n"
        << " options in config files. ";
}

int main(int argc, char *argv[])
{
    static const char *optString = "c:D:h";
    int c = 0;
    vector<string> configFiles;
    vector< pair<string,string> > configPairs;
    string progname = argv[0];
    // parse command line
    while (1) {
        c = getopt (argc, argv, optString);
        /* Detect end of options */
        if (c == -1) {
            break;
        } else if (c == 'c') {
            configFiles.push_back(optarg);
        } else if (c == 'D') {
            // override all previous options, e.g.
            // -DLOG_TO_STDOUT=TRUE
            string text = optarg;
            string value, optionName;
            vector<std::string> strs;
            boost::split(strs, text, boost::is_any_of("=:"));
            optionName = strs[0];
            if (strs.size() > 2) {
                // merge end tokens if more than one separator found
                for (uint i = 1; i < strs.size(); i++)
                    value += strs[i];
            } else if (strs.size() == 1) {
                std::cerr << "No value given for option " << strs[0] << endl;
            } else {
                value = strs[1];
            }
            configPairs.push_back( pair<string,string>(optionName, value) );
        } else {
            // unknown option (or help)
            usage(progname.c_str());
            if (c == 'h')
                exit(0);
            else
                exit(1);
        }

    }
    if (configFiles.size() == 0) {
        cerr << "Searching for config in default locations..." << endl;
        // search for configuration file on default locations
        for (int i = 0; DEFAULT_CONFIG_PATHS[i] != NULL; ++i) {
            boost::filesystem::path configPath(DEFAULT_CONFIG_PATHS[i]);
            configPath /= DEFAULT_CONFIG_FILENAME;
            if (boost::filesystem::exists(configPath)) {
                cerr << "Found " << configPath.string() << endl;
                configFiles.push_back(configPath.string());
            }
        }
    }
    config().reset();
    if (configFiles.size() == 0) {
        cerr << "No config files could be found!" << endl;
        exit(-1);
    }
    // Each config file sequentially overwrites the next
    BOOST_FOREACH (string configFile, configFiles) {
        try {
            config().load(configFile.c_str(), false);
            fprintf(stderr, "loaded configuration from file \"%s\"\n", configFile.c_str());
            break;
        } catch (RuntimeException &e) {
            std::cerr << e.getMessage() << std::endl;
            exit(1);
        }
    }
    // Each specific option
    pair<string,string> optionPair;
    BOOST_FOREACH (optionPair, configPairs) {
        //cerr << optionPair.first << " = " << optionPair.second << endl;
        config().set(optionPair.first, optionPair.second);
    }

    // setup global logger
    logger().setFilename(config()["LOG_FILE"]);
    logger().setLevel(Logger::getLevelFromString(config()["LOG_LEVEL"]));
    logger().setBackTraceLevel(Logger::getLevelFromString(config()["BACK_TRACE_LOG_LEVEL"]));
    logger().setPrintToStdoutFlag(config().get_bool("LOG_TO_STDOUT"));
    //logger().setLevel(Logger::DEBUG);

    CogServer& cogserver = static_cast<CogServer&>(server());

    // Open database *before* loading modules, since the modules
    // might create atoms, and we can't have that happen until
    // storage is open, as otherwise, there will be handle conflicts.
    cogserver.openDatabase();

    // Load modules specified in config
    cogserver.loadModules();
    cogserver.loadSCMModules(DEFAULT_MODULE_PATHS);

    // enable the network server and run the server's main loop
    cogserver.enableNetworkServer();
    cogserver.serverLoop();
    exit(0);
}
<commit_msg>Get the proper locale from the environment; if it's not UTF-8, then force-set it to En_US.utf8<commit_after>/*
 * opencog/server/CogServerMain.cc
 *
 * Copyright (C) 2002-2007 Novamente LLC
 * Copyright (C) 2008 by Singularity Institute for Artificial Intelligence
 * All Rights Reserved
 *
 * Written by Andre Senna <senna@vettalabs.com>
 *            Gustavo Gama <gama@vettalabs.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <getopt.h>
#include <langinfo.h>
#include <locale.h>

#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>

#include <utility>
#include <string>

#include <opencog/server/CogServer.h>
#include <opencog/util/Config.h>
#include <opencog/util/Logger.h>
#include <opencog/util/exceptions.h>
#include <opencog/util/misc.h>

using namespace opencog;
using namespace std;

static const char* DEFAULT_CONFIG_FILENAME = "opencog.conf";
static const char* DEFAULT_CONFIG_PATHS[] =
{
    CONFDIR,
#ifndef WIN32
    "/etc",
#endif // !WIN32
    NULL
};

static const char* DEFAULT_MODULE_PATHS[] =
{
    DATADIR,
    "opencog",
    "../opencog",
#ifndef WIN32
    "/usr/share/opencog",
    "/usr/local/share/opencog",
#endif // !WIN32
    NULL
};

static void usage(const char* progname)
{
    std::cerr << "Usage: " << progname << " [[-c <config-file>]..] [[-DOPTION=\"VALUE\"]..]\n\n";
    std::cerr << "Each config file is loaded sequentially, with the values in \n"
        << " later files overwriting earlier. Then each singular option overrides \n"
        << " options in config files. ";
}

int main(int argc, char *argv[])
{
    // Get the locale from the environment...
    // Perhaps we should someday get it from the config file ???
    setlocale(LC_ALL, "");

    // Check to make sure the current locale is UTF8; if its not,
    // then force-set this to the english utf8 locale
    const char * codeset = nl_langinfo(CODESET);
    if (!strstr(codeset, "UTF") && !strstr(codeset, "utf"))
    {
       fprintf(stderr,
           "%s: Warning: locale %s was not UTF-8; force-setting to en_US.UTF-8\n",
            argv[0], codeset);
       setlocale(LC_CTYPE, "en_US.UTF-8");
    }

    static const char *optString = "c:D:h";
    int c = 0;
    vector<string> configFiles;
    vector< pair<string,string> > configPairs;
    string progname = argv[0];

    // parse command line
    while (1) {
        c = getopt (argc, argv, optString);
        /* Detect end of options */
        if (c == -1) {
            break;
        } else if (c == 'c') {
            configFiles.push_back(optarg);
        } else if (c == 'D') {
            // override all previous options, e.g.
            // -DLOG_TO_STDOUT=TRUE
            string text = optarg;
            string value, optionName;
            vector<std::string> strs;
            boost::split(strs, text, boost::is_any_of("=:"));
            optionName = strs[0];
            if (strs.size() > 2) {
                // merge end tokens if more than one separator found
                for (uint i = 1; i < strs.size(); i++)
                    value += strs[i];
            } else if (strs.size() == 1) {
                std::cerr << "No value given for option " << strs[0] << endl;
            } else {
                value = strs[1];
            }
            configPairs.push_back( pair<string,string>(optionName, value) );
        } else {
            // unknown option (or help)
            usage(progname.c_str());
            if (c == 'h')
                exit(0);
            else
                exit(1);
        }

    }

    if (configFiles.size() == 0) {
        cerr << "Searching for config in default locations..." << endl;
        // search for configuration file on default locations
        for (int i = 0; DEFAULT_CONFIG_PATHS[i] != NULL; ++i) {
            boost::filesystem::path configPath(DEFAULT_CONFIG_PATHS[i]);
            configPath /= DEFAULT_CONFIG_FILENAME;
            if (boost::filesystem::exists(configPath)) {
                cerr << "Found " << configPath.string() << endl;
                configFiles.push_back(configPath.string());
            }
        }
    }
    config().reset();
    if (configFiles.size() == 0) {
        cerr << "No config files could be found!" << endl;
        exit(-1);
    }
    // Each config file sequentially overwrites the next
    BOOST_FOREACH (string configFile, configFiles) {
        try {
            config().load(configFile.c_str(), false);
            fprintf(stderr, "loaded configuration from file \"%s\"\n", configFile.c_str());
            break;
        } catch (RuntimeException &e) {
            std::cerr << e.getMessage() << std::endl;
            exit(1);
        }
    }
    // Each specific option
    pair<string,string> optionPair;
    BOOST_FOREACH (optionPair, configPairs) {
        //cerr << optionPair.first << " = " << optionPair.second << endl;
        config().set(optionPair.first, optionPair.second);
    }

    // setup global logger
    logger().setFilename(config()["LOG_FILE"]);
    logger().setLevel(Logger::getLevelFromString(config()["LOG_LEVEL"]));
    logger().setBackTraceLevel(Logger::getLevelFromString(config()["BACK_TRACE_LOG_LEVEL"]));
    logger().setPrintToStdoutFlag(config().get_bool("LOG_TO_STDOUT"));
    //logger().setLevel(Logger::DEBUG);

    CogServer& cogserver = static_cast<CogServer&>(server());

    // Open database *before* loading modules, since the modules
    // might create atoms, and we can't have that happen until
    // storage is open, as otherwise, there will be handle conflicts.
    cogserver.openDatabase();

    // Load modules specified in config
    cogserver.loadModules();
    cogserver.loadSCMModules(DEFAULT_MODULE_PATHS);

    // enable the network server and run the server's main loop
    cogserver.enableNetworkServer();
    cogserver.serverLoop();
    exit(0);
}
<|endoftext|>


<commit_before>AliAnalysisTaskhCascadeFemto *AddTaskHCascadeFemto ( Bool_t krunMCtruth  = kFALSE,
                                                     Bool_t kusecontainer = kFALSE,
                                                     const char* outfoldersuffix = "pXi",
                                                     const char* outlistsuffix = "wttc",
                                                     Bool_t bCentralTrigger = kTRUE,
                                                     Int_t  fistpart = 1,
                                                     Int_t  secondpart = 2,
                                                     Bool_t kcascadesidebands = kFALSE,
                                                     Bool_t kcascadetightcuts = kTRUE,
                                                     Float_t masswincasc = 0.003, // 0.003 2s 0.008 4s, this always for side bands!!!
                                                     Float_t nsigmatpcpidfirst = 3.,
                                                     Float_t nsigmatpctofpidfirst = 3.,
                                                     Float_t nsigmatpcpidsecdau = 4.,
                                                     Int_t  trackbuffersize = 20200,
                                                     Int_t  multfirstpart = 3000, // 3000 for pions, 1000 ok for protons
                                                     Int_t  multsecondpart= 20,

                                                     Bool_t kapplyttc = kTRUE,
                                                     Float_t dphismin = 0.06,    // 0.04 TPC 0.06 global // 0.045 for pi paper, 0.045 for protons, 0.015 for pi my cut
                                                     Float_t detasmin = 0.15,    // 0.1 TPC  0.15 global

                                                     short nevmixing = 7,

						     Float_t momemtumlimitforTOFPID = 0.8,
                                                     Bool_t kusecrrfindratiocut = kFALSE,
                                                     Bool_t kusetpcip = kFALSE,
                                                     Float_t cutipxy = 0.1,      // TPC 2.4 protons 1. pions GLOBAL 0.1 protons pions
                                                     Float_t cutipz = 0.15,      // TPC 3.2 protons 1. pions GLOBAL 0.15 protons pions
                                                     Float_t minptforprim = 0.7, // 0.7 protons  0.14 pions
                                                     Float_t maxptforprim = 4.,  // 4.  proton s 2.   pions

                                                     Float_t minptforcasc = 0.6,
                                                     Float_t maxptforcasc = 10.,
                                                     Float_t cutipbac = 0.1,     //0.03,
                                                     Bool_t kapplyycutcasc = kFALSE,
                                                     Bool_t kpropagateglobal = kTRUE,
                                                     const char* outlistsubwagon = ""  // "pXi"
                                                   ) {

  // Get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskHCascadeFemto", "No analysis manager found.");
    return 0;
  }

  // Check the analysis type using the event handlers connected to the analysis
  // manager. The availability of MC handler cann also be checked here.
  //==============================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskHCascadeFemto", "This task requires an input event handler");
    return NULL;
  }
  TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"

  //cout << "Found " <<type << " event handler" << endl;

  // Create and configure the task, add it to manager.
  //===========================================================================
  TString combinedName;
  combinedName.Form("TaskhCascadeFemto%s%s", outlistsuffix, outlistsubwagon);
  AliAnalysisTaskhCascadeFemto *task = new AliAnalysisTaskhCascadeFemto(combinedName);

  if(bCentralTrigger)
      task->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral);
  else
      task->SelectCollisionCandidates(AliVEvent::kSemiCentral | AliVEvent::kMB);

  task->SetAnalysisType (type);
  task->SetReadMCTruth(krunMCtruth);
  task->SetUseContainer(kusecontainer);

  task->SetMassHist(500, 1.,1.5);
  if (secondpart == 2) task->SetMassHistGrandmother (350,1.1,1.8);
  else if (secondpart == 3) task->SetMassHistGrandmother (120,1.62, 1.74);

  task->SetCentrality(0., 90.);

  task->SetFirstParticle(fistpart);
  task->SetSecondParticle(secondpart);
  task->SetTrackBufferSize(trackbuffersize);
  task->SetFirstPartMaxMult(multfirstpart);
  task->SetSecondPartMaxMult(multsecondpart);
  task->SetMassWindowCascades(masswincasc);
  task->SetnSigmaTPCPIDfirstParticle(nsigmatpcpidfirst);
  task->SetnSigmaTPCTOFPIDfirstParticle(nsigmatpctofpidfirst);
  task->SetnSigmaTPCPIDsecondParticleDau(nsigmatpcpidsecdau);
  task->SetApplyTtc(kapplyttc);
  task->SetDphisMin(dphismin);
  task->SetDetasMin(detasmin);
  task->SetCascadeSideBands(kcascadesidebands);
  task->SetCascadeTightCuts(kcascadetightcuts);
  task->SetNEventsToMix(nevmixing);
  task->SetMomentumLimitForTOFPID(momemtumlimitforTOFPID);
  task->SetApplyRatioCrRnFindCut(kusecrrfindratiocut);
  task->SetCutOnTPCIP(kusetpcip);
  task->SetIPCutxy(cutipxy);
  task->SetIPCutz(cutipz);
  task->SetMinPtPrim(minptforprim);
  task->SetMaxPtPrim(maxptforprim);
  task->SetMinPtCasc(minptforcasc);
  task->SetMaxPtCasc(maxptforcasc);
  task->SetIPCutBac(cutipbac);
  task->SetApplyYcutCasc(kapplyycutcasc);
  task->SetPropagateGlobal(kpropagateglobal);

  mgr->AddTask(task);

  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
  TString outputfile = AliAnalysisManager::GetCommonFileName();

  outputfile += Form(":PWGCFFEMTO_outputHCascadeTask_%s",outfoldersuffix);
  AliAnalysisDataContainer *cout_pXi  = mgr->CreateContainer(combinedName,  TList::Class(),
                                                               AliAnalysisManager::kOutputContainer,outputfile);

  AliAnalysisDataContainer *cout_pXi2 = mgr->CreateContainer("cfcontCutsXi",
                                                              AliCFContainer::Class(),
                                                              AliAnalysisManager::kOutputContainer,
                                                              outputfile );

  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, cout_pXi);
  mgr->ConnectOutput(task, 2, cout_pXi2);

  if(!task) {
            Error("AddTaskhCascadeFemto","AliAnalysisTaskhCascadeFemto not created!");
            return;
  }

  return task;

}
<commit_msg>Adding suffix to a container to use subwagons<commit_after>AliAnalysisTaskhCascadeFemto *AddTaskHCascadeFemto ( Bool_t krunMCtruth  = kFALSE,
                                                     Bool_t kusecontainer = kFALSE,
                                                     const char* outfoldersuffix = "pXi",
                                                     const char* outlistsuffix = "wttc",
                                                     Bool_t bCentralTrigger = kTRUE,
                                                     Int_t  fistpart = 1,
                                                     Int_t  secondpart = 2,
                                                     Bool_t kcascadesidebands = kFALSE,
                                                     Bool_t kcascadetightcuts = kTRUE,
                                                     Float_t masswincasc = 0.003, // 0.003 2s 0.008 4s, this always for side bands!!!
                                                     Float_t nsigmatpcpidfirst = 3.,
                                                     Float_t nsigmatpctofpidfirst = 3.,
                                                     Float_t nsigmatpcpidsecdau = 4.,
                                                     Int_t  trackbuffersize = 20200,
                                                     Int_t  multfirstpart = 3000, // 3000 for pions, 1000 ok for protons
                                                     Int_t  multsecondpart= 20,

                                                     Bool_t kapplyttc = kTRUE,
                                                     Float_t dphismin = 0.06,    // 0.04 TPC 0.06 global // 0.045 for pi paper, 0.045 for protons, 0.015 for pi my cut
                                                     Float_t detasmin = 0.15,    // 0.1 TPC  0.15 global

                                                     short nevmixing = 7,

						     Float_t momemtumlimitforTOFPID = 0.8,
                                                     Bool_t kusecrrfindratiocut = kFALSE,
                                                     Bool_t kusetpcip = kFALSE,
                                                     Float_t cutipxy = 0.1,      // TPC 2.4 protons 1. pions GLOBAL 0.1 protons pions
                                                     Float_t cutipz = 0.15,      // TPC 3.2 protons 1. pions GLOBAL 0.15 protons pions
                                                     Float_t minptforprim = 0.7, // 0.7 protons  0.14 pions
                                                     Float_t maxptforprim = 4.,  // 4.  proton s 2.   pions

                                                     Float_t minptforcasc = 0.6,
                                                     Float_t maxptforcasc = 10.,
                                                     Float_t cutipbac = 0.1,     //0.03,
                                                     Bool_t kapplyycutcasc = kFALSE,
                                                     Bool_t kpropagateglobal = kTRUE,
                                                     const char* outlistsubwagon = ""  // "pXi"
                                                   ) {

  // Get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskHCascadeFemto", "No analysis manager found.");
    return 0;
  }

  // Check the analysis type using the event handlers connected to the analysis
  // manager. The availability of MC handler cann also be checked here.
  //==============================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskHCascadeFemto", "This task requires an input event handler");
    return NULL;
  }
  TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"

  //cout << "Found " <<type << " event handler" << endl;

  // Create and configure the task, add it to manager.
  //===========================================================================
  TString combinedName;
  combinedName.Form("TaskhCascadeFemto%s%s", outlistsuffix, outlistsubwagon);
  AliAnalysisTaskhCascadeFemto *task = new AliAnalysisTaskhCascadeFemto(combinedName);

  if(bCentralTrigger)
      task->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral);
  else
      task->SelectCollisionCandidates(AliVEvent::kSemiCentral | AliVEvent::kMB);

  task->SetAnalysisType (type);
  task->SetReadMCTruth(krunMCtruth);
  task->SetUseContainer(kusecontainer);

  task->SetMassHist(500, 1.,1.5);
  if (secondpart == 2) task->SetMassHistGrandmother (350,1.1,1.8);
  else if (secondpart == 3) task->SetMassHistGrandmother (120,1.62, 1.74);

  task->SetCentrality(0., 90.);

  task->SetFirstParticle(fistpart);
  task->SetSecondParticle(secondpart);
  task->SetTrackBufferSize(trackbuffersize);
  task->SetFirstPartMaxMult(multfirstpart);
  task->SetSecondPartMaxMult(multsecondpart);
  task->SetMassWindowCascades(masswincasc);
  task->SetnSigmaTPCPIDfirstParticle(nsigmatpcpidfirst);
  task->SetnSigmaTPCTOFPIDfirstParticle(nsigmatpctofpidfirst);
  task->SetnSigmaTPCPIDsecondParticleDau(nsigmatpcpidsecdau);
  task->SetApplyTtc(kapplyttc);
  task->SetDphisMin(dphismin);
  task->SetDetasMin(detasmin);
  task->SetCascadeSideBands(kcascadesidebands);
  task->SetCascadeTightCuts(kcascadetightcuts);
  task->SetNEventsToMix(nevmixing);
  task->SetMomentumLimitForTOFPID(momemtumlimitforTOFPID);
  task->SetApplyRatioCrRnFindCut(kusecrrfindratiocut);
  task->SetCutOnTPCIP(kusetpcip);
  task->SetIPCutxy(cutipxy);
  task->SetIPCutz(cutipz);
  task->SetMinPtPrim(minptforprim);
  task->SetMaxPtPrim(maxptforprim);
  task->SetMinPtCasc(minptforcasc);
  task->SetMaxPtCasc(maxptforcasc);
  task->SetIPCutBac(cutipbac);
  task->SetApplyYcutCasc(kapplyycutcasc);
  task->SetPropagateGlobal(kpropagateglobal);

  mgr->AddTask(task);

  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
  TString outputfile = AliAnalysisManager::GetCommonFileName();

  outputfile += Form(":PWGCFFEMTO_outputHCascadeTask_%s",outfoldersuffix);
  AliAnalysisDataContainer *cout_pXi  = mgr->CreateContainer(combinedName,  TList::Class(),
                                                               AliAnalysisManager::kOutputContainer,outputfile);

  AliAnalysisDataContainer *cout_pXi2 = mgr->CreateContainer(Form("cfcontCutsXi_%s",combinedName),
                                                              AliCFContainer::Class(),
                                                              AliAnalysisManager::kOutputContainer,
                                                              outputfile );

  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, cout_pXi);
  mgr->ConnectOutput(task, 2, cout_pXi2);

  if(!task) {
            Error("AddTaskhCascadeFemto","AliAnalysisTaskhCascadeFemto not created!");
            return;
  }

  return task;

}
<|endoftext|>


<commit_before>#include "P_Link.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1FileSystem.h"
#include "j1Player.h"
#include "j1InputManager.h"

void P_Link::Attack()
{

}

void P_Link::LoadAnimation(const char * path)
{
	p2SString tmp("%s%s", sprites_folder.GetString(), path);

	char* buf = nullptr;
	int size = App->fs->Load(tmp.GetString(), &buf);
	pugi::xml_parse_result result = sprites_file.load_buffer(buf, size);

	if (result == NULL)
	{
		//LOG("Could not load map xml file %s. pugi error: %s", file_name, result.description());
		//ret = false;
	}

	pugi::xml_node info = sprites_file.child("TextureAtlas");
	char* imagepath = (char*)info.attribute("imagePath").as_string();

	character_texture = App->tex->Load(imagepath);

	pugi::xml_node animations = info.first_child();

	char* last_name = nullptr;
	int x = animations.attribute("x").as_int();
	int y = animations.attribute("y").as_int();
	int w = animations.attribute("w").as_int();
	int h = animations.attribute("h").as_int();
	SDL_Rect anim = { x,y,w,h };
	Animation temp_animation;

	char* name = (char*)animations.attribute("name").as_string();
	auto temp = animations;
	last_name = name;
	while (animations) {
		auto temp = animations;
		name = (char*)animations.attribute("name").as_string();
		x = temp.attribute("x").as_int();
		y = temp.attribute("y").as_int();
		w = temp.attribute("w").as_int();
		h = temp.attribute("h").as_int();
		anim = { x,y,w,h };

		if (strcmp(name,last_name)) {
			temp_animation.speed = 0.2;
			sprites_vector->push_back(temp_animation);
			temp_animation.Reset();
			temp_animation.last_frame = 0;
			temp_animation.PushBack(anim);
			last_name = name;
		}
		else {
			temp_animation.PushBack(anim);
		}
		animations = animations.next_sibling();
	}

}

player_event P_Link::GetEvent()
{

	if (doing_script == false) {

		 if (App->inputM->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT) {
			if (App->inputM->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT) {
				movement_direction = move_up_right;
			}
			else if (App->inputM->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT) {
				movement_direction = move_up_left;
			}
			else {
				movement_direction = move_up;

			}
			character_direction = up;
			actual_event = move;
		}

		else if (App->inputM->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT) {
			if (App->inputM->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT) {
				movement_direction = move_down_left;
			}
			else if (App->inputM->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT) {
				movement_direction = move_down_right;
			}
			else {
				movement_direction = move_down;

			}
			character_direction = down;
			actual_event = move;
		}

		else if (App->inputM->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT) {

			movement_direction = move_right;
			character_direction = right;
			actual_event = move;
		}
		else if (App->inputM->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT) {

			movement_direction = move_left;
			character_direction = left;
			actual_event = move;
		}

		else if (App->input->GetKey(SDL_SCANCODE_W) == KEY_REPEAT) {
			if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) {
				movement_direction = move_up_right;
			}
			else if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) {
				movement_direction = move_up_left;
			}
			else {
				movement_direction = move_up;

			}
			character_direction = up;
			actual_event = move;
		}

		else if (App->input->GetKey(SDL_SCANCODE_S) == KEY_REPEAT) {
			if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) {
				movement_direction = move_down_left;
			}
			else if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) {
				movement_direction = move_down_right;
			}
			else {
				movement_direction = move_down;

			}
			character_direction = down;
			actual_event = move;
		}

		else if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) {

			movement_direction = move_right;
			character_direction = right;
			actual_event = move;
		}
		else if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) {

			movement_direction = move_left;
			character_direction = left;
			actual_event = move;
		}
		else {
			movement_direction = move_idle;
			actual_event = idle;

			if (GetLogic() == 424) {
				actual_event = jump;
				doing_script = true;
				LOG("I'm Jumping :DDDD");
			}

		}
		return actual_event;
	}
}<commit_msg>Bug fixed<commit_after>#include "P_Link.h"
#include "j1App.h"
#include "j1Input.h"
#include "j1FileSystem.h"
#include "j1Player.h"
#include "j1InputManager.h"

void P_Link::Attack()
{

}

void P_Link::LoadAnimation(const char * path)
{
	p2SString tmp("%s%s", sprites_folder.GetString(), path);

	char* buf = nullptr;
	int size = App->fs->Load(tmp.GetString(), &buf);
	pugi::xml_parse_result result = sprites_file.load_buffer(buf, size);

	if (result == NULL)
	{
		//LOG("Could not load map xml file %s. pugi error: %s", file_name, result.description());
		//ret = false;
	}

	pugi::xml_node info = sprites_file.child("TextureAtlas");
	char* imagepath = (char*)info.attribute("imagePath").as_string();

	character_texture = App->tex->Load(imagepath);

	pugi::xml_node animations = info.first_child();

	char* last_name = nullptr;
	int x = animations.attribute("x").as_int();
	int y = animations.attribute("y").as_int();
	int w = animations.attribute("w").as_int();
	int h = animations.attribute("h").as_int();
	SDL_Rect anim = { x,y,w,h };
	Animation temp_animation;

	char* name = (char*)animations.attribute("name").as_string();
	auto temp = animations;
	last_name = name;
	while (animations) {
		auto temp = animations;
		name = (char*)animations.attribute("name").as_string();
		x = temp.attribute("x").as_int();
		y = temp.attribute("y").as_int();
		w = temp.attribute("w").as_int();
		h = temp.attribute("h").as_int();
		anim = { x,y,w,h };

		if (strcmp(name,last_name)) {
			temp_animation.speed = 0.2;
			sprites_vector->push_back(temp_animation);
			temp_animation.Reset();
			temp_animation.last_frame = 0;
			temp_animation.PushBack(anim);
			last_name = name;
		}
		else {
			temp_animation.PushBack(anim);
		}
		animations = animations.next_sibling();
	}

}

player_event P_Link::GetEvent()
{

	if (doing_script == false) {

		 if (App->inputM->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT) {
			if (App->inputM->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT) {
				movement_direction = move_up_right;
			}
			else if (App->inputM->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT) {
				movement_direction = move_up_left;
			}
			else {
				movement_direction = move_up;

			}
			character_direction = up;
			actual_event = move;
		}

		else if (App->inputM->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT) {
			if (App->inputM->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT) {
				movement_direction = move_down_left;
			}
			else if (App->inputM->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT) {
				movement_direction = move_down_right;
			}
			else {
				movement_direction = move_down;

			}
			character_direction = down;
			actual_event = move;
		}

		else if (App->inputM->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT) {

			movement_direction = move_right;
			character_direction = right;
			actual_event = move;
		}
		else if (App->inputM->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT) {

			movement_direction = move_left;
			character_direction = left;
			actual_event = move;
		}

		else if (App->input->GetKey(SDL_SCANCODE_W) == KEY_REPEAT) {
			if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) {
				movement_direction = move_up_right;
			}
			else if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) {
				movement_direction = move_up_left;
			}
			else {
				movement_direction = move_up;

			}
			character_direction = up;
			actual_event = move;
		}

		else if (App->input->GetKey(SDL_SCANCODE_S) == KEY_REPEAT) {
			if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) {
				movement_direction = move_down_left;
			}
			else if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) {
				movement_direction = move_down_right;
			}
			else {
				movement_direction = move_down;

			}
			character_direction = down;
			actual_event = move;
		}

		else if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) {

			movement_direction = move_right;
			character_direction = right;
			actual_event = move;
		}
		else if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) {

			movement_direction = move_left;
			character_direction = left;
			actual_event = move;
		}
		else {
			movement_direction = move_idle;
			actual_event = idle;
		}

			if (GetLogic() == 424) {
				actual_event = jump;
				doing_script = true;
				LOG("I'm Jumping :DDDD");
			}

		return actual_event;
	}
}<|endoftext|>