<commit_before>// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "key.h"

#include "crypto/hmac_sha512.h"
#include "crypto/rfc6979_hmac_sha256.h"
#include "eccryptoverify.h"
#include "pubkey.h"
#include "random.h"

#include <secp256k1.h>
#include "ecwrapper.h"

//! anonymous namespace
namespace {

class CSecp256k1Init {
public:
    CSecp256k1Init() {
        secp256k1_start(SECP256K1_START_SIGN);
    }
    ~CSecp256k1Init() {
        secp256k1_stop();
    }
};
static CSecp256k1Init instance_of_csecp256k1;

} // anon namespace

bool CKey::Check(const unsigned char *vch) {
    return eccrypto::Check(vch);
}

void CKey::MakeNewKey(bool fCompressedIn) {
    do {
        GetRandBytes(vch, sizeof(vch));
    } while (!Check(vch));
    fValid = true;
    fCompressed = fCompressedIn;
}

bool CKey::SetPrivKey(const CPrivKey &privkey, bool fCompressedIn) {
    if (!secp256k1_ec_privkey_import((unsigned char*)begin(), &privkey[0], privkey.size()))
        return false;
    fCompressed = fCompressedIn;
    fValid = true;
    return true;
}

CPrivKey CKey::GetPrivKey() const {
    assert(fValid);
    CPrivKey privkey;
    int privkeylen, ret;
    privkey.resize(279);
    privkeylen = 279;
    ret = secp256k1_ec_privkey_export(begin(), (unsigned char*)&privkey[0], &privkeylen, fCompressed);
    assert(ret);
    privkey.resize(privkeylen);
    return privkey;
}

CPubKey CKey::GetPubKey() const {
    assert(fValid);
    CPubKey result;
    int clen = 65;
    int ret = secp256k1_ec_pubkey_create((unsigned char*)result.begin(), &clen, begin(), fCompressed);
    assert((int)result.size() == clen);
    assert(ret);
    assert(result.IsValid());
    return result;
}

bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig, uint32_t test_case) const {
    if (!fValid)
        return false;
    vchSig.resize(72);
    RFC6979_HMAC_SHA256 prng(begin(), 32, (unsigned char*)&hash, 32);
    do {
        uint256 nonce;
        prng.Generate((unsigned char*)&nonce, 32);
        nonce += test_case;
        int nSigLen = 72;
        int ret = secp256k1_ecdsa_sign((const unsigned char*)&hash, 32, (unsigned char*)&vchSig[0], &nSigLen, begin(), (unsigned char*)&nonce);
        vchSig.resize(nSigLen);
        nonce = 0;
        if (ret)
            return true;
    } while(true);
}

bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
    if (!fValid)
        return false;
    vchSig.resize(65);
    int rec = -1;
    RFC6979_HMAC_SHA256 prng(begin(), 32, (unsigned char*)&hash, 32);
    do {
        uint256 nonce;
        prng.Generate((unsigned char*)&nonce, 32);
        int ret = secp256k1_ecdsa_sign_compact((const unsigned char*)&hash, 32, &vchSig[1], begin(), (unsigned char*)&nonce, &rec);
        nonce = 0;
        if (ret)
            break;
    } while(true);
    assert(rec != -1);
    vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
    return true;
}

bool CKey::Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck=false) {
    if (!secp256k1_ec_privkey_import((unsigned char*)begin(), &privkey[0], privkey.size()))
        return false;
    fCompressed = vchPubKey.IsCompressed();
    fValid = true;

    if (fSkipCheck)
        return true;

    if (GetPubKey() != vchPubKey)
        return false;

    return true;
}

bool CKey::Derive(CKey& keyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const {
    assert(IsValid());
    assert(IsCompressed());
    unsigned char out[64];
    LockObject(out);
    if ((nChild >> 31) == 0) {
        CPubKey pubkey = GetPubKey();
        assert(pubkey.begin() + 33 == pubkey.end());
        BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, out);
    } else {
        assert(begin() + 32 == end());
        BIP32Hash(cc, nChild, 0, begin(), out);
    }
    memcpy(ccChild, out+32, 32);
    memcpy((unsigned char*)keyChild.begin(), begin(), 32);
    bool ret = secp256k1_ec_privkey_tweak_add((unsigned char*)keyChild.begin(), out);
    UnlockObject(out);
    keyChild.fCompressed = true;
    keyChild.fValid = ret;
    return ret;
}

bool CExtKey::Derive(CExtKey &out, unsigned int nChild) const {
    out.nDepth = nDepth + 1;
    CKeyID id = key.GetPubKey().GetID();
    memcpy(&out.vchFingerprint[0], &id, 4);
    out.nChild = nChild;
    return key.Derive(out.key, out.vchChainCode, nChild, vchChainCode);
}

void CExtKey::SetMaster(const unsigned char *seed, unsigned int nSeedLen) {
    static const unsigned char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};
    unsigned char out[64];
    LockObject(out);
    CHMAC_SHA512(hashkey, sizeof(hashkey)).Write(seed, nSeedLen).Finalize(out);
    key.Set(&out[0], &out[32], true);
    memcpy(vchChainCode, &out[32], 32);
    UnlockObject(out);
    nDepth = 0;
    nChild = 0;
    memset(vchFingerprint, 0, sizeof(vchFingerprint));
}

CExtPubKey CExtKey::Neuter() const {
    CExtPubKey ret;
    ret.nDepth = nDepth;
    memcpy(&ret.vchFingerprint[0], &vchFingerprint[0], 4);
    ret.nChild = nChild;
    ret.pubkey = key.GetPubKey();
    memcpy(&ret.vchChainCode[0], &vchChainCode[0], 32);
    return ret;
}

void CExtKey::Encode(unsigned char code[74]) const {
    code[0] = nDepth;
    memcpy(code+1, vchFingerprint, 4);
    code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;
    code[7] = (nChild >>  8) & 0xFF; code[8] = (nChild >>  0) & 0xFF;
    memcpy(code+9, vchChainCode, 32);
    code[41] = 0;
    assert(key.size() == 32);
    memcpy(code+42, key.begin(), 32);
}

void CExtKey::Decode(const unsigned char code[74]) {
    nDepth = code[0];
    memcpy(vchFingerprint, code+1, 4);
    nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
    memcpy(vchChainCode, code+9, 32);
    key.Set(code+42, code+74, true);
}

bool ECC_InitSanityCheck() {
    return CECKey::SanityCheck();
}
<commit_msg>Resize after succesful result<commit_after>// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "key.h"

#include "crypto/hmac_sha512.h"
#include "crypto/rfc6979_hmac_sha256.h"
#include "eccryptoverify.h"
#include "pubkey.h"
#include "random.h"

#include <secp256k1.h>
#include "ecwrapper.h"

//! anonymous namespace
namespace {

class CSecp256k1Init {
public:
    CSecp256k1Init() {
        secp256k1_start(SECP256K1_START_SIGN);
    }
    ~CSecp256k1Init() {
        secp256k1_stop();
    }
};
static CSecp256k1Init instance_of_csecp256k1;

} // anon namespace

bool CKey::Check(const unsigned char *vch) {
    return eccrypto::Check(vch);
}

void CKey::MakeNewKey(bool fCompressedIn) {
    do {
        GetRandBytes(vch, sizeof(vch));
    } while (!Check(vch));
    fValid = true;
    fCompressed = fCompressedIn;
}

bool CKey::SetPrivKey(const CPrivKey &privkey, bool fCompressedIn) {
    if (!secp256k1_ec_privkey_import((unsigned char*)begin(), &privkey[0], privkey.size()))
        return false;
    fCompressed = fCompressedIn;
    fValid = true;
    return true;
}

CPrivKey CKey::GetPrivKey() const {
    assert(fValid);
    CPrivKey privkey;
    int privkeylen, ret;
    privkey.resize(279);
    privkeylen = 279;
    ret = secp256k1_ec_privkey_export(begin(), (unsigned char*)&privkey[0], &privkeylen, fCompressed);
    assert(ret);
    privkey.resize(privkeylen);
    return privkey;
}

CPubKey CKey::GetPubKey() const {
    assert(fValid);
    CPubKey result;
    int clen = 65;
    int ret = secp256k1_ec_pubkey_create((unsigned char*)result.begin(), &clen, begin(), fCompressed);
    assert((int)result.size() == clen);
    assert(ret);
    assert(result.IsValid());
    return result;
}

bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig, uint32_t test_case) const {
    if (!fValid)
        return false;
    vchSig.resize(72);
    RFC6979_HMAC_SHA256 prng(begin(), 32, (unsigned char*)&hash, 32);
    do {
        uint256 nonce;
        prng.Generate((unsigned char*)&nonce, 32);
        nonce += test_case;
        int nSigLen = 72;
        int ret = secp256k1_ecdsa_sign((const unsigned char*)&hash, 32, (unsigned char*)&vchSig[0], &nSigLen, begin(), (unsigned char*)&nonce);
        nonce = 0;
        if (ret) {
            vchSig.resize(nSigLen);
            return true;
        }
    } while(true);
}

bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
    if (!fValid)
        return false;
    vchSig.resize(65);
    int rec = -1;
    RFC6979_HMAC_SHA256 prng(begin(), 32, (unsigned char*)&hash, 32);
    do {
        uint256 nonce;
        prng.Generate((unsigned char*)&nonce, 32);
        int ret = secp256k1_ecdsa_sign_compact((const unsigned char*)&hash, 32, &vchSig[1], begin(), (unsigned char*)&nonce, &rec);
        nonce = 0;
        if (ret)
            break;
    } while(true);
    assert(rec != -1);
    vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
    return true;
}

bool CKey::Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck=false) {
    if (!secp256k1_ec_privkey_import((unsigned char*)begin(), &privkey[0], privkey.size()))
        return false;
    fCompressed = vchPubKey.IsCompressed();
    fValid = true;

    if (fSkipCheck)
        return true;

    if (GetPubKey() != vchPubKey)
        return false;

    return true;
}

bool CKey::Derive(CKey& keyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const {
    assert(IsValid());
    assert(IsCompressed());
    unsigned char out[64];
    LockObject(out);
    if ((nChild >> 31) == 0) {
        CPubKey pubkey = GetPubKey();
        assert(pubkey.begin() + 33 == pubkey.end());
        BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, out);
    } else {
        assert(begin() + 32 == end());
        BIP32Hash(cc, nChild, 0, begin(), out);
    }
    memcpy(ccChild, out+32, 32);
    memcpy((unsigned char*)keyChild.begin(), begin(), 32);
    bool ret = secp256k1_ec_privkey_tweak_add((unsigned char*)keyChild.begin(), out);
    UnlockObject(out);
    keyChild.fCompressed = true;
    keyChild.fValid = ret;
    return ret;
}

bool CExtKey::Derive(CExtKey &out, unsigned int nChild) const {
    out.nDepth = nDepth + 1;
    CKeyID id = key.GetPubKey().GetID();
    memcpy(&out.vchFingerprint[0], &id, 4);
    out.nChild = nChild;
    return key.Derive(out.key, out.vchChainCode, nChild, vchChainCode);
}

void CExtKey::SetMaster(const unsigned char *seed, unsigned int nSeedLen) {
    static const unsigned char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};
    unsigned char out[64];
    LockObject(out);
    CHMAC_SHA512(hashkey, sizeof(hashkey)).Write(seed, nSeedLen).Finalize(out);
    key.Set(&out[0], &out[32], true);
    memcpy(vchChainCode, &out[32], 32);
    UnlockObject(out);
    nDepth = 0;
    nChild = 0;
    memset(vchFingerprint, 0, sizeof(vchFingerprint));
}

CExtPubKey CExtKey::Neuter() const {
    CExtPubKey ret;
    ret.nDepth = nDepth;
    memcpy(&ret.vchFingerprint[0], &vchFingerprint[0], 4);
    ret.nChild = nChild;
    ret.pubkey = key.GetPubKey();
    memcpy(&ret.vchChainCode[0], &vchChainCode[0], 32);
    return ret;
}

void CExtKey::Encode(unsigned char code[74]) const {
    code[0] = nDepth;
    memcpy(code+1, vchFingerprint, 4);
    code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;
    code[7] = (nChild >>  8) & 0xFF; code[8] = (nChild >>  0) & 0xFF;
    memcpy(code+9, vchChainCode, 32);
    code[41] = 0;
    assert(key.size() == 32);
    memcpy(code+42, key.begin(), 32);
}

void CExtKey::Decode(const unsigned char code[74]) {
    nDepth = code[0];
    memcpy(vchFingerprint, code+1, 4);
    nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
    memcpy(vchChainCode, code+9, 32);
    key.Set(code+42, code+74, true);
}

bool ECC_InitSanityCheck() {
    return CECKey::SanityCheck();
}
<|endoftext|>


<commit_before>#include "eval.hh"
#include "live.hh"
#include "utils.hh"
#include <SDL2/SDL.h>

struct passed_data_t {
  term_t *const program;
  const std::string definition;
  std::vector<double> frequencies;
  passed_data_t(term_t *const program, const std::string &definition)
    : program(program)
    , definition(definition) {
  }
};

static double note_to_freq(char note, int octave, int accidental_offset) {
  const std::map<char, int> semitone_offset = {
    { 'C', -9 },
    { 'D', -7 },
    { 'E', -5 },
    { 'F', -4 },
    { 'G', -2 },
    { 'A',  0 },
    { 'B',  2 }
  };
  int octave_diff = octave - 4, semitone_diff = semitone_offset.at(note)
    + accidental_offset;
  return 440. * pow(2., octave_diff) * pow(2., semitone_diff / 12.);
}

static void audio_callback(void *userdata, uint8_t *stream, int len) {
  passed_data_t *passed_data = (passed_data_t*)userdata;
  static uint64_t c = 0;
  float *stream_ptr = (float*)stream;
  for (int i = 0; i < 4096; ++i) {
    double t = (double)(c++) * 1. / 48000.;
    *stream_ptr = 0;
    for (double f : passed_data->frequencies) {
      printf("f=%f\n", f);
      float value = (float)evaluate_definition(passed_data->program
          , passed_data->definition, f, t);
      *stream_ptr += 0.2f * value;
    }
    ++stream_ptr;
  }
}

void live(term_t *const program, const std::string &definition) {
  if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO) != 0)
    die("Failed to initialize SDL");

  int window_width = 600, window_height = (3. / 4.) * (double)window_width;
  SDL_Window *window = SDL_CreateWindow("Sythin live", SDL_WINDOWPOS_CENTERED
      , SDL_WINDOWPOS_CENTERED, window_width, window_height, 0);
  if (!window)
    die("failed to create window");

  SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0);
  SDL_SetRenderDrawColor(renderer, 19, 19, 19, 255);

  passed_data_t passed_data(program, definition);

  SDL_AudioSpec want, have;
  SDL_memset(&want, 0, sizeof(want));
  want.freq = 48000;
  want.format = AUDIO_F32;
  want.channels = 1;
  want.samples = 4096;
  want.callback = audio_callback;
  want.userdata = (void*)&passed_data;

  SDL_AudioDeviceID dev = SDL_OpenAudioDevice(nullptr, 0, &want, &have
      , SDL_AUDIO_ALLOW_ANY_CHANGE);
  if (dev == 0)
    die("failed to open audio device: %s", SDL_GetError());

  SDL_PauseAudioDevice(dev, 0);

  std::map<int, double> key_frequencies = {
    { SDLK_z, note_to_freq('A', 4, 0) },
    { SDLK_x, note_to_freq('A', 4, 1) },
    { SDLK_c, note_to_freq('B', 4, 0) },
    { SDLK_v, note_to_freq('C', 5, 0) }
  };

  bool quit = false;
  while (!quit) {
    passed_data.frequencies.clear();

    SDL_Event event;
    while (SDL_PollEvent(&event))
      if (event.type == SDL_QUIT
          || (event.type == SDL_KEYUP && event.key.keysym.sym == SDLK_ESCAPE))
        quit = true;
      else if (event.type == SDL_KEYDOWN)
        if (key_frequencies.count(event.key.keysym.sym)) {
          printf("set %f\n", key_frequencies[event.key.keysym.sym]);
          passed_data.frequencies.push_back(key_frequencies[event.key.keysym.sym]);
        }

    SDL_RenderClear(renderer);
    SDL_RenderPresent(renderer);
  }

  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  SDL_CloseAudioDevice(dev);
  SDL_Quit();
}

<commit_msg>Add playback<commit_after>#include "eval.hh"
#include "live.hh"
#include "utils.hh"
#include <SDL2/SDL.h>

struct passed_data_t {
  term_t *const program;
  const std::string definition;
  std::map<double, bool> frequencies;
  passed_data_t(term_t *const program, const std::string &definition)
    : program(program)
    , definition(definition) {
  }
};

static double note_to_freq(char note, int octave, int accidental_offset) {
  const std::map<char, int> semitone_offset = {
    { 'C', -9 },
    { 'D', -7 },
    { 'E', -5 },
    { 'F', -4 },
    { 'G', -2 },
    { 'A',  0 },
    { 'B',  2 }
  };
  int octave_diff = octave - 4, semitone_diff = semitone_offset.at(note)
    + accidental_offset;
  return 440. * pow(2., octave_diff) * pow(2., semitone_diff / 12.);
}

static void audio_callback(void *userdata, uint8_t *stream, int len) {
  passed_data_t *passed_data = (passed_data_t*)userdata;
  static uint64_t c = 0;
  float *stream_ptr = (float*)stream;
  for (int i = 0; i < 4096; ++i) {
    double t = (double)(c++) * 1. / 48000.;
    *stream_ptr = 0;
    for (const std::pair<double, bool> freq_pair : passed_data->frequencies) {
      if (freq_pair.second) {
        float value = (float)evaluate_definition(passed_data->program
            , passed_data->definition, freq_pair.first, t);
        *stream_ptr += 0.2f * value;
      }
    }
    ++stream_ptr;
  }
}

void live(term_t *const program, const std::string &definition) {
  if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO) != 0)
    die("Failed to initialize SDL");

  int window_width = 600, window_height = (3. / 4.) * (double)window_width;
  SDL_Window *window = SDL_CreateWindow("Sythin live", SDL_WINDOWPOS_CENTERED
      , SDL_WINDOWPOS_CENTERED, window_width, window_height, 0);
  if (!window)
    die("failed to create window");

  SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0);
  SDL_SetRenderDrawColor(renderer, 19, 19, 19, 255);

  passed_data_t passed_data(program, definition);

  SDL_AudioSpec want, have;
  SDL_memset(&want, 0, sizeof(want));
  want.freq = 48000;
  want.format = AUDIO_F32;
  want.channels = 1;
  want.samples = 4096;
  want.callback = audio_callback;
  want.userdata = (void*)&passed_data;

  SDL_AudioDeviceID dev = SDL_OpenAudioDevice(nullptr, 0, &want, &have
      , SDL_AUDIO_ALLOW_ANY_CHANGE);
  if (dev == 0)
    die("failed to open audio device: %s", SDL_GetError());

  SDL_PauseAudioDevice(dev, 0);

  std::map<int, double> key_frequencies = {
    { SDLK_z, note_to_freq('A', 4, 0) },
    { SDLK_x, note_to_freq('A', 4, 1) },
    { SDLK_c, note_to_freq('B', 4, 0) },
    { SDLK_v, note_to_freq('C', 5, 0) }
  };

  bool quit = false;
  while (!quit) {
    SDL_Event event;
    while (SDL_PollEvent(&event))
      if (event.type == SDL_QUIT
          || (event.type == SDL_KEYUP && event.key.keysym.sym == SDLK_ESCAPE))
        quit = true;
      else if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP)
        if (key_frequencies.count(event.key.keysym.sym))
          passed_data.frequencies[key_frequencies[event.key.keysym.sym]]
            = event.type == SDL_KEYDOWN;

    SDL_RenderClear(renderer);
    SDL_RenderPresent(renderer);
  }

  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  SDL_CloseAudioDevice(dev);
  SDL_Quit();
}

<|endoftext|>


<commit_before>/**
 *  \file RMF/Category.h
 *  \brief Handle read/write of Model data from/to files.
 *
 *  Copyright 2007-2012 IMP Inventors. All rights reserved.
 *
 */
#include <RMF/log.h>
#include <RMF/exceptions.h>
#if RMF_HAS_LOG4CXX
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/consoleappender.h>
#include <log4cxx/patternlayout.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/level.h>
#endif

namespace RMF {
#if RMF_HAS_LOG4CXX
namespace {
struct Configurator {
  Configurator(log4cxx::ConsoleAppenderPtr ptr) {
    log4cxx::BasicConfigurator::configure(ptr);
  }
};
void init_logger() {
   // "%-4r [%t] %-5p %c %x - %m%n"
  static log4cxx::PatternLayoutPtr layout
      = new log4cxx::PatternLayout("%-6r %-5p %c- %m%n");
  static log4cxx::ConsoleAppenderPtr appender
      = new log4cxx::ConsoleAppender(layout);
  static Configurator config(appender);
}
}
log4cxx::LoggerPtr get_logger() {
  init_logger();
  static log4cxx::LoggerPtr ret = log4cxx::Logger::getLogger("RMF");
  return ret;
}
log4cxx::LoggerPtr get_avro_logger() {
  init_logger();
  static log4cxx::LoggerPtr ret = log4cxx::Logger::getLogger("RMF.avro");
  return ret;
}
log4cxx::LoggerPtr get_hdf5_logger() {
  init_logger();
  static log4cxx::LoggerPtr ret = log4cxx::Logger::getLogger("RMF.hdf5");
  return ret;
}
void set_log_level(std::string str) {
  try {
    get_logger()->setLevel(log4cxx::Level::toLevel(str));
  } catch (log4cxx::helpers::Exception &e) {
    RMF_THROW(Message("Invalid log level"), UsageException);
  }
}
#else
void set_log_level(std::string str) {
}
#endif

}
<commit_msg>only initialize logging if it is not already<commit_after>/**
 *  \file RMF/Category.h
 *  \brief Handle read/write of Model data from/to files.
 *
 *  Copyright 2007-2012 IMP Inventors. All rights reserved.
 *
 */
#include <RMF/log.h>
#include <RMF/exceptions.h>
#if RMF_HAS_LOG4CXX
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/consoleappender.h>
#include <log4cxx/patternlayout.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/level.h>
#endif

namespace RMF {
#if RMF_HAS_LOG4CXX
namespace {
struct Configurator {
  Configurator(log4cxx::ConsoleAppenderPtr ptr) {
    log4cxx::BasicConfigurator::configure(ptr);
  }
};

void do_init() {
 // "%-4r [%t] %-5p %c %x - %m%n"
  static log4cxx::PatternLayoutPtr layout
      = new log4cxx::PatternLayout("%-6r %-5p %c- %m%n");
  static log4cxx::ConsoleAppenderPtr appender
      = new log4cxx::ConsoleAppender(layout);
  static Configurator config(appender);
}

void init_logger() {
  log4cxx::LoggerPtr rootLogger =
      log4cxx::Logger::getRootLogger();
  bool uninit = rootLogger->getAllAppenders().empty() ? true : false;
  if (uninit) do_init();
}
}
log4cxx::LoggerPtr get_logger() {
  init_logger();
  static log4cxx::LoggerPtr ret = log4cxx::Logger::getLogger("RMF");
  return ret;
}
log4cxx::LoggerPtr get_avro_logger() {
  init_logger();
  static log4cxx::LoggerPtr ret = log4cxx::Logger::getLogger("RMF.avro");
  return ret;
}
log4cxx::LoggerPtr get_hdf5_logger() {
  init_logger();
  static log4cxx::LoggerPtr ret = log4cxx::Logger::getLogger("RMF.hdf5");
  return ret;
}
void set_log_level(std::string str) {
  try {
    get_logger()->setLevel(log4cxx::Level::toLevel(str));
    get_avro_logger()->setLevel(log4cxx::Level::toLevel(str));
    get_hdf5_logger()->setLevel(log4cxx::Level::toLevel(str));
  } catch (log4cxx::helpers::Exception &e) {
    RMF_THROW(Message("Invalid log level"), UsageException);
  }
}
#else
void set_log_level(std::string str) {
}
#endif

}
<|endoftext|>


<commit_before>// Copyright (c) 2016 Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include <ctime>
#include "configreader.h"
#include "log.h"
#include "logprintf.h"

namespace {

class Log {
 public:
  Log(): file_(0) {
    ConfigReader server_cfg("server.cfg");
    std::string filename = server_cfg.GetValueWithDefault("crashdetect_log");
    if (!filename.empty()) {
      file_ = std::fopen(filename.c_str(), "a");
    }
    if (file_ != 0) {
      time_format_ =
        server_cfg.GetValueWithDefault("logtimeformat", "[%H:%M:%S]");
    }
  }

  ~Log() {
    if (file_ != 0) {
      std::fclose(file_);
    }
  }

  void PrintV(const char *prefix,
              const char *format,
              std::va_list va) {
    std::string new_format;

    if (file_ != 0) {
      if (!time_format_.empty()) {
        char time_buffer[128];
        std::time_t time = std::time(0);
        std::strftime(time_buffer,
                      sizeof(time_buffer),
                      time_format_.c_str(),
                      std::localtime(&time));
        new_format.append(time_buffer);
        new_format.append(" ");
      }
    } else {
      new_format.append(prefix);
    }

    new_format.append(format);

    if (file_ != 0) {
      new_format.append("\n");
      vfprintf(file_, new_format.c_str(), va);
    } else {
      vlogprintf(new_format.c_str(), va);
    }
  }

  void Flush() {
    if (file_ != 0) {
      std::fflush(file_);
    }
  }

 private:
  std::FILE *file_;
  std::string time_format_;
};

Log global_log;

} // namespace

void LogPrintV(const char *prefix, const char *format, std::va_list va) {
  global_log.PrintV(prefix, format, va);
}

void LogTracePrint(const char *format, ...) {
  std::va_list va;
  va_start(va, format);
  LogPrintV("[trace] ", format, va);
  va_end(va);
}

void LogDebugPrint(const char *format, ...) {
  std::va_list va;
  va_start(va, format);
  LogPrintV("[debug] ", format, va);
  va_end(va);
}

void LogFlush() {
  global_log.Flush();
}
<commit_msg>Fix compile errors on Linux<commit_after>// Copyright (c) 2016 Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include <ctime>
#include <cstdio>

#include <configreader.h>

#include "log.h"
#include "logprintf.h"

namespace {

class Log {
 public:
  Log(): file_(0) {
    ConfigReader server_cfg("server.cfg");
    std::string filename = server_cfg.GetValueWithDefault("crashdetect_log");
    if (!filename.empty()) {
      file_ = std::fopen(filename.c_str(), "a");
    }
    if (file_ != 0) {
      time_format_ =
        server_cfg.GetValueWithDefault("logtimeformat", "[%H:%M:%S]");
    }
  }

  ~Log() {
    if (file_ != 0) {
      std::fclose(file_);
    }
  }

  void PrintV(const char *prefix,
              const char *format,
              std::va_list va) {
    std::string new_format;

    if (file_ != 0) {
      if (!time_format_.empty()) {
        char time_buffer[128];
        std::time_t time = std::time(0);
        std::strftime(time_buffer,
                      sizeof(time_buffer),
                      time_format_.c_str(),
                      std::localtime(&time));
        new_format.append(time_buffer);
        new_format.append(" ");
      }
    } else {
      new_format.append(prefix);
    }

    new_format.append(format);

    if (file_ != 0) {
      new_format.append("\n");
      vfprintf(file_, new_format.c_str(), va);
    } else {
      vlogprintf(new_format.c_str(), va);
    }
  }

  void Flush() {
    if (file_ != 0) {
      std::fflush(file_);
    }
  }

 private:
  std::FILE *file_;
  std::string time_format_;
};

Log global_log;

} // namespace

void LogPrintV(const char *prefix, const char *format, std::va_list va) {
  global_log.PrintV(prefix, format, va);
}

void LogTracePrint(const char *format, ...) {
  std::va_list va;
  va_start(va, format);
  LogPrintV("[trace] ", format, va);
  va_end(va);
}

void LogDebugPrint(const char *format, ...) {
  std::va_list va;
  va_start(va, format);
  LogPrintV("[debug] ", format, va);
  va_end(va);
}

void LogFlush() {
  global_log.Flush();
}
<|endoftext|>


<commit_before>
#include <ugdk/system/engine.h>
#include <ugdk/action/3D/camera.h>
#include <ugdk/input/events.h>
#include <ugdk/input/module.h>
#include <ugdk/action/3D/element.h>
#include <ugdk/action/3D/scene3d.h>
#include <ugdk/action/3D/physics.h>
#include <ugdk/action/3D/component/physicsbody.h>
#include <ugdk/action/3D/component/view.h>
#include <BtOgreGP.h>
#include <memory>
#include <iostream>

#include <OgreCamera.h>
#include <OgreEntity.h>
#include <OgreLogManager.h>
#include <OgreRoot.h>
#include <OgreViewport.h>
#include <OgreSceneManager.h>
#include <OgreRenderWindow.h>
#include <OgreConfigFile.h>
#include <OgreMeshManager.h>

#define AREA_RANGE 200.0

using std::weak_ptr;
using std::shared_ptr;
using std::unique_ptr;
using std::make_shared;
using std::cout;
using std::endl;
using ugdk::action::mode3d::Element;
using ugdk::action::mode3d::component::PhysicsBody;
using ugdk::action::mode3d::component::Body;
using ugdk::action::mode3d::component::View;
using ugdk::action::mode3d::component::CollisionAction;
using ugdk::action::mode3d::component::ElementPtr;
using ugdk::action::mode3d::component::ContactPointVector;

namespace {

ugdk::action::mode3d::Scene3D *ourscene;

struct {
   double angle;
} player;

} // unnamed namespace

#define BIT(x) (1<<(x))
enum CollisionGroup {
    HEADS = BIT(6),
    WALLS = BIT(7),
    WAT2 = BIT(8),
    WAT3 = BIT(9),
    WAT4 = BIT(10)
};

shared_ptr<Element> createOgreHead(const std::string& name, bool useBox=false) {
    Ogre::SceneManager *mSceneMgr = ourscene->manager();
    // Element
    auto head = ourscene->AddElement();
    // View
    auto headEnt = mSceneMgr->createEntity(name, "Mage.mesh");
    head->AddComponent(make_shared<View>());
    head->component<View>()->AddEntity(headEnt);
    // Body
    PhysicsBody::PhysicsData headData;
    auto meshShapeConv = BtOgre::StaticMeshToShapeConverter(headEnt);
    if (useBox)
        headData.shape = meshShapeConv.createBox();
    else
        headData.shape = meshShapeConv.createSphere();
    headData.mass = 80;
    headData.collision_group = CollisionGroup::HEADS;
    headData.collides_with = CollisionGroup::WALLS | CollisionGroup::HEADS;
    headData.apply_orientation = false;
    head->AddComponent(make_shared<PhysicsBody>(*ourscene->physics(), headData));
    head->component<Body>()->set_damping(.4, .4);
    return head;
}

shared_ptr<Element> createWall(const std::string& name, const Ogre::Vector3& dir, double dist, double width = AREA_RANGE, double height = AREA_RANGE) {
    Ogre::SceneManager *mSceneMgr = ourscene->manager();
    // Element
    auto wall = ourscene->AddElement();
    // View
    Ogre::Plane plane(dir, dist);
    auto mesh_ptr = Ogre::MeshManager::getSingleton().createPlane(name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
        plane, width, height, 5, 5, true, 1, 5, 5, dir.perpendicular());
    const std::string wat = name + "Entity";
    Ogre::Entity* wallEnt = mSceneMgr->createEntity(wat, mesh_ptr);
    wallEnt->setMaterialName("Ogre/Tusks");
    wall->AddComponent(make_shared<View>());
    wall->component<View>()->AddEntity(wallEnt);
    // Body
    PhysicsBody::PhysicsData wallData;
    wallData.shape = new btStaticPlaneShape(btVector3(dir.x, dir.y, dir.z), dist);
    wallData.mass = 0;
    wallData.collision_group = CollisionGroup::WALLS;
    wallData.collides_with = CollisionGroup::HEADS;
    wall->AddComponent(make_shared<PhysicsBody>(*ourscene->physics(), wallData));
    wall->component<Body>()->set_friction(10);
    return wall;
}

int main(int argc, char* argv[]) {
    using Ogre::Vector3;

    ugdk::system::Configuration config;
    config.base_path = "assets/";
    ugdk::system::Initialize(config);
    ourscene = new ugdk::action::mode3d::Scene3D(btVector3(0.0, -10.0, 0.0));

    ourscene->physics()->set_debug_draw_enabled(true);
    ourscene->ShowFrameStats();

    {
        player.angle = 0.0;
        weak_ptr<Element> head1 = createOgreHead("Head");
        weak_ptr<Element> head2 = createOgreHead("Head2", true);
        auto body2 = head2.lock()->component<Body>();
        body2->Translate(0, 0, 80);
        body2->set_angular_factor(0.0, 0.0, 0.0);

        body2->AddCollisionAction(CollisionGroup::HEADS,
        [](const ElementPtr& self, const ElementPtr& target, const ContactPointVector& pts) {
            cout << "CARAS COLIDINDO MANO (" << pts.size() << ")" << endl;
        });

        weak_ptr<Element> wall = createWall("ground", Vector3::UNIT_Y, -5.0);

        ourscene->camera()->AttachTo(*head2.lock());
        ourscene->camera()->SetParameters(Vector3::UNIT_Y*10.0, 5000.0);
        ourscene->camera()->SetDistance(80.0);
        ourscene->camera()->Rotate(0.0, Ogre::Degree(20.0).valueDegrees());

        ourscene->AddTask(ugdk::system::Task(
        [head2, body2](double dt) {
            auto& keyboard = ugdk::input::manager()->keyboard();
            Vector3 move = Vector3::ZERO;
            if (keyboard.IsDown(ugdk::input::Scancode::RIGHT))
                player.angle -= dt*90.0;
            else if (keyboard.IsDown(ugdk::input::Scancode::LEFT))
                player.angle += dt*90.0;
            if (keyboard.IsDown(ugdk::input::Scancode::UP))
                move.z += 1.0;
            else if (keyboard.IsDown(ugdk::input::Scancode::DOWN))
                move.z += -1.0;

            Ogre::Quaternion rot(Ogre::Degree(player.angle), Vector3::UNIT_Y);
            move.normalise();
            move = rot * move;
            move.y = 0.0;
            move.normalise();

            body2->ApplyImpulse((move * 80));
            Ogre::SceneNode &node = head2.lock()->node();
            node.setOrientation(rot);
            // Now update camera
            Ogre::SceneNode &cam_node = ourscene->camera()->node();
        }));

        ourscene->event_handler().AddListener<ugdk::input::KeyPressedEvent>(
            [] (const ugdk::input::KeyPressedEvent& ev) -> void {
                if (ev.scancode == ugdk::input::Scancode::ESCAPE)
                    ourscene->Finish();
            });
        //ourscene->event_handler().AddListener<ugdk::input::MouseMotionEvent>(
        //    [] (const ugdk::input::MouseMotionEvent& ev) -> void {
        //        ourscene->camera()->Rotate(-ev.motion.x, ev.motion.y);
        //    });

        ourscene->manager()->setAmbientLight(Ogre::ColourValue(.7, .7, .7));

        ugdk::system::PushScene(unique_ptr<ugdk::action::Scene>(ourscene));

    }

    ugdk::system::Run();
    ugdk::system::Release();
    return 0;
}
<commit_msg>Adjustments to friction<commit_after>
#include <ugdk/system/engine.h>
#include <ugdk/action/3D/camera.h>
#include <ugdk/input/events.h>
#include <ugdk/input/module.h>
#include <ugdk/action/3D/element.h>
#include <ugdk/action/3D/scene3d.h>
#include <ugdk/action/3D/physics.h>
#include <ugdk/action/3D/component/physicsbody.h>
#include <ugdk/action/3D/component/view.h>
#include <BtOgreGP.h>
#include <memory>
#include <iostream>

#include <OgreCamera.h>
#include <OgreEntity.h>
#include <OgreLogManager.h>
#include <OgreRoot.h>
#include <OgreViewport.h>
#include <OgreSceneManager.h>
#include <OgreRenderWindow.h>
#include <OgreConfigFile.h>
#include <OgreMeshManager.h>

#define AREA_RANGE 200.0

using std::weak_ptr;
using std::shared_ptr;
using std::unique_ptr;
using std::make_shared;
using std::cout;
using std::endl;
using ugdk::action::mode3d::Element;
using ugdk::action::mode3d::component::PhysicsBody;
using ugdk::action::mode3d::component::Body;
using ugdk::action::mode3d::component::View;
using ugdk::action::mode3d::component::CollisionAction;
using ugdk::action::mode3d::component::ElementPtr;
using ugdk::action::mode3d::component::ContactPointVector;

namespace {

ugdk::action::mode3d::Scene3D *ourscene;

struct {
   double angle;
} player;

} // unnamed namespace

#define BIT(x) (1<<(x))
enum CollisionGroup {
    HEADS = BIT(6),
    WALLS = BIT(7),
    WAT2 = BIT(8),
    WAT3 = BIT(9),
    WAT4 = BIT(10)
};

shared_ptr<Element> createOgreHead(const std::string& name, bool useBox=false) {
    Ogre::SceneManager *mSceneMgr = ourscene->manager();
    // Element
    auto head = ourscene->AddElement();
    // View
    auto headEnt = mSceneMgr->createEntity(name, "Mage.mesh");
    head->AddComponent(make_shared<View>());
    head->component<View>()->AddEntity(headEnt);
    // Body
    PhysicsBody::PhysicsData headData;
    auto meshShapeConv = BtOgre::StaticMeshToShapeConverter(headEnt);
    if (useBox)
        headData.shape = meshShapeConv.createBox();
    else
        headData.shape = meshShapeConv.createSphere();
    headData.mass = 80;
    headData.collision_group = CollisionGroup::HEADS;
    headData.collides_with = CollisionGroup::WALLS | CollisionGroup::HEADS;
    headData.apply_orientation = false;
    head->AddComponent(make_shared<PhysicsBody>(*ourscene->physics(), headData));
    head->component<Body>()->set_damping(.8, .8);
    return head;
}

shared_ptr<Element> createWall(const std::string& name, const Ogre::Vector3& dir, double dist, double width = AREA_RANGE, double height = AREA_RANGE) {
    Ogre::SceneManager *mSceneMgr = ourscene->manager();
    // Element
    auto wall = ourscene->AddElement();
    // View
    Ogre::Plane plane(dir, dist);
    auto mesh_ptr = Ogre::MeshManager::getSingleton().createPlane(name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
        plane, width, height, 5, 5, true, 1, 5, 5, dir.perpendicular());
    const std::string wat = name + "Entity";
    Ogre::Entity* wallEnt = mSceneMgr->createEntity(wat, mesh_ptr);
    wallEnt->setMaterialName("Ogre/Tusks");
    wall->AddComponent(make_shared<View>());
    wall->component<View>()->AddEntity(wallEnt);
    // Body
    PhysicsBody::PhysicsData wallData;
    wallData.shape = new btStaticPlaneShape(btVector3(dir.x, dir.y, dir.z), dist);
    wallData.mass = 0;
    wallData.collision_group = CollisionGroup::WALLS;
    wallData.collides_with = CollisionGroup::HEADS;
    wall->AddComponent(make_shared<PhysicsBody>(*ourscene->physics(), wallData));
    wall->component<Body>()->set_friction(20);
    return wall;
}

int main(int argc, char* argv[]) {
    using Ogre::Vector3;

    ugdk::system::Configuration config;
    config.base_path = "assets/";
    ugdk::system::Initialize(config);
    ourscene = new ugdk::action::mode3d::Scene3D(btVector3(0.0, -10.0, 0.0));

    ourscene->physics()->set_debug_draw_enabled(true);
    ourscene->ShowFrameStats();

    {
        player.angle = 0.0;
        weak_ptr<Element> head1 = createOgreHead("Head");
        weak_ptr<Element> head2 = createOgreHead("Head2", true);
        auto body2 = head2.lock()->component<Body>();
        body2->Translate(0, 0, 80);
        body2->set_angular_factor(0.0, 0.0, 0.0);

        body2->AddCollisionAction(CollisionGroup::HEADS,
        [](const ElementPtr& self, const ElementPtr& target, const ContactPointVector& pts) {
            cout << "CARAS COLIDINDO MANO (" << pts.size() << ")" << endl;
        });

        weak_ptr<Element> wall = createWall("ground", Vector3::UNIT_Y, -5.0);

        ourscene->camera()->AttachTo(*head2.lock());
        ourscene->camera()->SetParameters(Vector3::UNIT_Y*10.0, 5000.0);
        ourscene->camera()->SetDistance(80.0);
        ourscene->camera()->Rotate(0.0, Ogre::Degree(20.0).valueDegrees());

        ourscene->AddTask(ugdk::system::Task(
        [head2, body2](double dt) {
            auto& keyboard = ugdk::input::manager()->keyboard();
            Vector3 move = Vector3::ZERO;
            if (keyboard.IsDown(ugdk::input::Scancode::RIGHT))
                player.angle -= dt*135.0;
            else if (keyboard.IsDown(ugdk::input::Scancode::LEFT))
                player.angle += dt*135.0;
            if (keyboard.IsDown(ugdk::input::Scancode::UP))
                move.z += 1.0;
            else if (keyboard.IsDown(ugdk::input::Scancode::DOWN))
                move.z += -1.0;

            Ogre::Quaternion rot(Ogre::Degree(player.angle), Vector3::UNIT_Y);
            move.normalise();
            move = rot * move;
            move.y = 0.0;
            move.normalise();

            body2->ApplyImpulse(move * 200);
            Ogre::SceneNode &node = head2.lock()->node();
            node.setOrientation(rot);
        }));

        ourscene->event_handler().AddListener<ugdk::input::KeyPressedEvent>(
            [] (const ugdk::input::KeyPressedEvent& ev) -> void {
                if (ev.scancode == ugdk::input::Scancode::ESCAPE)
                    ourscene->Finish();
            });
        //ourscene->event_handler().AddListener<ugdk::input::MouseMotionEvent>(
        //    [] (const ugdk::input::MouseMotionEvent& ev) -> void {
        //        ourscene->camera()->Rotate(-ev.motion.x, ev.motion.y);
        //    });

        ourscene->manager()->setAmbientLight(Ogre::ColourValue(.7, .7, .7));

        ugdk::system::PushScene(unique_ptr<ugdk::action::Scene>(ourscene));

    }

    ugdk::system::Run();
    ugdk::system::Release();
    return 0;
}
<|endoftext|>


<commit_before>#include "gameboy.h"
#include "cartridge.h"
#include "video/screen.h"
#include "util/log.h"

#include "video/screens/null_screen.h"
#include "video/screens/sfml_screen.h"

struct Options {
    bool debugger;
    bool trace;
    std::string filename;
};

static bool flag_set(char** begin, char** end, const std::string& short_option, const std::string& long_option) {
    bool short_option_found = std::find(begin, end, short_option) != end;
    bool long_option_found = std::find(begin, end, long_option) != end;
    return short_option_found || long_option_found;
}

static Options get_options(int argc, char* argv[]) {
    char** begin = argv;
    char** end = argv + argc;

    if (argc < 2) {
        log_error("Please provide a ROM file to run");
        fatal_error();
    }

    bool debugger = flag_set(begin, end, "-d", "--debug");
    bool trace = flag_set(begin, end, "-t", "--trace");

    std::string filename = argv[1];

    return Options { debugger, trace, filename };
}

int main(int argc, char* argv[]) {
    Options options = get_options(argc, argv);

    auto log_level = options.trace ?
        LogLevel::Trace : LogLevel::Debug;

    log_set_level(log_level);

    Cartridge cartridge(options.filename);
    SFMLScreen screen;

    Gameboy gameboy(screen, cartridge, options.debugger);
    gameboy.run();
}
<commit_msg>Add a flag (--nolog/-n) to disable all logging<commit_after>#include "gameboy.h"
#include "cartridge.h"
#include "video/screen.h"
#include "util/log.h"

#include "video/screens/null_screen.h"
#include "video/screens/sfml_screen.h"

struct Options {
    bool debugger;
    bool trace;
    bool disable_logs;
    std::string filename;
};

static bool flag_set(char** begin, char** end, const std::string& short_option, const std::string& long_option) {
    bool short_option_found = std::find(begin, end, short_option) != end;
    bool long_option_found = std::find(begin, end, long_option) != end;
    return short_option_found || long_option_found;
}

static Options get_options(int argc, char* argv[]) {
    char** begin = argv;
    char** end = argv + argc;

    if (argc < 2) {
        log_error("Please provide a ROM file to run");
        fatal_error();
    }

    bool debugger = flag_set(begin, end, "-d", "--debug");
    bool trace = flag_set(begin, end, "-t", "--trace");
    bool disable_logs = flag_set(begin, end, "-n", "--nolog");

    std::string filename = argv[1];

    return Options { debugger, trace, disable_logs, filename };
}

int main(int argc, char* argv[]) {
    Options options = get_options(argc, argv);

    auto log_level = options.trace ?
        LogLevel::Trace : LogLevel::Debug;

    log_set_level(log_level);

    if (options.disable_logs) log_set_level(LogLevel::Error);

    Cartridge cartridge(options.filename);
    SFMLScreen screen;

    Gameboy gameboy(screen, cartridge, options.debugger);
    gameboy.run();
}
<|endoftext|>


<commit_before>#include <QApplication>
#include "mainwindow.h"

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

    app.setAttribute(Qt::AA_UseHighDpiPixmaps);

    QIcon appIcon;
    appIcon.addFile(":/Icons/AppIcon32");
    appIcon.addFile(":/Icons/AppIcon128");
    app.setWindowIcon(appIcon);

    MainWindow mainWindow;
    mainWindow.show();
    return app.exec();
}
<commit_msg>Add comment about Retina display support<commit_after>#include <QApplication>
#include "mainwindow.h"

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

    // Retina display support for Mac OS, iOS and X11:
    // http://blog.qt.digia.com/blog/2013/04/25/retina-display-support-for-mac-os-ios-and-x11/
    //
    // AA_UseHighDpiPixmaps attribute is off by default in Qt 5.1 but will most
    // likely be on by default in a future release of Qt.
    app.setAttribute(Qt::AA_UseHighDpiPixmaps);

    QIcon appIcon;
    appIcon.addFile(":/Icons/AppIcon32");
    appIcon.addFile(":/Icons/AppIcon128");
    app.setWindowIcon(appIcon);

    MainWindow mainWindow;
    mainWindow.show();
    return app.exec();
}
<|endoftext|>


<commit_before>
#include <iostream>
#include <bitset>

#include "jet/Utf8String.h"
#include "jet/File.h"
#include "jet/Exception.h"

#include "Parser.h"

using namespace std;
using namespace jet;
using namespace jet::modeler;

template< class T >
void print_as_binary( T value, ostream& output_stream ){

    bitset< sizeof(T) * 8 > x( value );

    output_stream << x ;

}

void show_usage(){

    cout << "Usage: jm <filename>" << endl;

}

void red( Utf8String text ){

    cout << "\033[1;31m" << text << "\033[0m";

}

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

    if( argc < 2 ){
        show_usage();
        return 1;
    }

    Utf8String *filename = NULL;
    File *file = NULL;
    Utf8String *contents = NULL;
    Parser *parser = NULL;

    try{

        filename = new Utf8String( argv[1] );

        file = new File( *filename );

        contents = new Utf8String;
        *contents = file->getContents();

        parser = new Parser;
        parser->parse( contents );

        cout << endl;

        parser->printModels();
        parser->writeModelFiles();

    }catch( Exception *e ){

        red( Utf8String("[Exception] ") );
        cout << "- " << e->message << endl;

    }

    if( parser != NULL ) delete parser;
    if( contents != NULL ) delete contents;
    if( file != NULL ) delete file;
    if( filename != NULL ) delete filename;

    /*
    Utf8String my_string( "Hello", 5 );

    cout << my_string << endl;

    unsigned char current_byte = 0;

    unsigned int value = 0x80 >> 7;

    int shift_bytes = sizeof(unsigned int) - 1;

    current_byte = value;

    cout << shift_bytes << endl;

    //cout << value << endl;

    //cout << current_byte << endl;

    cout << "Value as Binary: ";
    print_as_binary( value, cout );
    cout << endl;

    cout << "Current Byte as Binary: ";
    print_as_binary( current_byte, cout );
    cout << endl;

    cout << "Shift Bytes as Binary: ";
    print_as_binary( shift_bytes, cout );
    cout << endl;

    cout << "Literal as Binary: ";
    print_as_binary( 0x01, cout );
    cout << endl;

    //print_as_binary( my_string, cout );

    */

    return 0;

}
<commit_msg>Cleaned up main to actually do something.<commit_after>
#include <iostream>
#include <bitset>

#include "jet/Utf8String.h"
#include "jet/File.h"
#include "jet/Exception.h"

using namespace std;
using namespace jet;

template< class T >
void print_as_binary( T value, ostream& output_stream ){

    bitset< sizeof(T) * 8 > x( value );

    output_stream << x ;

}

void show_usage(){

    cout << "Usage: my_exe <filename>" << endl;

}

void red( Utf8String text ){

    cout << "\033[1;31m" << text << "\033[0m";

}

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

    if( argc < 2 ){
        show_usage();
        return 1;
    }

    Utf8String *filename = NULL;
    File *file = NULL;
    Utf8String *contents = NULL;

    try{

        filename = new Utf8String( argv[1] );

        file = new File( *filename );

        contents = new Utf8String;
        *contents = file->getContents();

        cout << *contents;

    }catch( Exception *e ){

        red( Utf8String("[Exception] ") );
        cout << "- " << e->message << endl;

    }

    if( contents != NULL ) delete contents;
    if( file != NULL ) delete file;
    if( filename != NULL ) delete filename;

    /*
    Utf8String my_string( "Hello", 5 );

    cout << my_string << endl;

    unsigned char current_byte = 0;

    unsigned int value = 0x80 >> 7;

    int shift_bytes = sizeof(unsigned int) - 1;

    current_byte = value;

    cout << shift_bytes << endl;

    //cout << value << endl;

    //cout << current_byte << endl;

    cout << "Value as Binary: ";
    print_as_binary( value, cout );
    cout << endl;

    cout << "Current Byte as Binary: ";
    print_as_binary( current_byte, cout );
    cout << endl;

    cout << "Shift Bytes as Binary: ";
    print_as_binary( shift_bytes, cout );
    cout << endl;

    cout << "Literal as Binary: ";
    print_as_binary( 0x01, cout );
    cout << endl;

    //print_as_binary( my_string, cout );

    */

    return 0;

}
<|endoftext|>


<commit_before>//============================================================================
// Name        : pel.cpp
// Author      : Joe Selman
// Version     :

//============================================================================

#ifdef HAVE_CONFIG_H
#include "../config.h"
#endif

#ifndef PACKAGE_STRING
#define PACKAGE_STRING "pel 0.8-svn"
#endif

#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <boost/foreach.hpp>
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <utility>
#include <ctime>
#include <map>
#include "fol/fol.h"
#include "fol/folparser.h"
#include "fol/domain.h"
#include "log.h"
#include "fol/moves.h"
#include "fol/maxwalksat.h"
#include "fol/formulaset.h"

int main(int argc, char* argv[]) {
	// Declare the supported options.
	po::options_description desc("Allowed options");
	desc.add_options()
	    ("help", "produce help message")
	    ("version,v", "print version and exit")
	    ("max", po::value<unsigned int>(), "maximum value an interval endpoint can take")
	    ("min", po::value<unsigned int>(), "minimum value an interval endpoint can take")
	    ("evalModel,e", "simply print the model weight of the facts file")
	    ("prob,p", po::value<double>()->default_value(0.25), "probability of taking a random move")
	    ("iterations,i", po::value<unsigned int>()->default_value(1000), "number of iterations before returning a model")
	    ("output,o", po::value<std::string>(), "output model file")
	;

	po::options_description hidden("Hidden options");
	hidden.add_options()
		("facts-file", po::value<std::string>(), "facts file")
		("formula-file", po::value<std::string>(), "formula file")
	;
	po::positional_options_description p;
	p.add("facts-file", 1);
	p.add("formula-file", 1);

	po::options_description cmdline_options;
	cmdline_options.add(desc).add(hidden);

	po::variables_map vm;
	po::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm);
	po::notify(vm);

	if (vm.count("version")) {
		std::cout << PACKAGE_STRING << std::endl;
		return 0;
	}

	if (vm.count("help") || !vm.count("facts-file") || !vm.count("formula-file")) {
	    std::cout << "Usage: pel [OPTION]... FACT-FILE FORMULA-FILE" << std::endl;
		std::cout << desc << std::endl;
	    return 1;
	}

	// setup our logging facilities
	FILE* debugFile = fopen("debug.log", "w");
	if (!debugFile) std::cerr << "unable to open debug.log for logging - logging to stderr";
	else FilePolicy::stream() = debugFile;
	FileLog::globalLogLevel() = LOG_DEBUG;

	LOG(LOG_INFO) << "Opened log file for new session";

	// make sure we can open the output model file, if specified
	FILE* outputFile = NULL;
	if (vm.count("output")) {
		outputFile = fopen(vm["output"].as<std::string>().c_str(), "w");
		if (!outputFile) {
			std::cerr << "unable to open output file \"" << vm["output"].as<std::string>() << "\" for writing." << std::endl;
			return 1;
		}
	}

	boost::shared_ptr<Domain> d = FOLParse::loadDomainFromFiles(vm["facts-file"].as<std::string>(), vm["formula-file"].as<std::string>());
	if (vm.count("max") || vm.count("min")) {
		Interval maxInt = d->maxInterval();
		if (vm.count("max")) maxInt.setFinish(vm["max"].as<unsigned int>());
		if (vm.count("min")) maxInt.setStart(vm["min"].as<unsigned int>());
		d->setMaxInterval(maxInt);
	}

	Model model = d->defaultModel();

	LOG_PRINT(LOG_INFO) << "model size: " << model.size();
	LOG(LOG_DEBUG) << "observation predicates: ";
	for(std::map<std::string, SISet>::const_iterator it = d->observedPredicates().begin();
			it != d->observedPredicates().end();
			it++) {
		LOG(LOG_DEBUG) << "\t" << it->first;
	}

	if (vm.count("evalModel")) {
		LOG(LOG_INFO) << "evaluating model...";
		unsigned long sum = 0;
		// evaluate the weight of each formula in the domain
		for(FormulaSet::const_iterator it = d->formulaSet().begin(); it != d->formulaSet().end(); it++) {
			WSentence formula = *it;
			SISet satisfied = d->satisfied(*(formula.sentence()), model);
			unsigned long weight = d->score(formula, model);
			sum += weight;
			LOG_PRINT(LOG_INFO) << "formula: (" << formula.sentence()->toString() << ")";
			LOG_PRINT(LOG_INFO) << "\tsatisfied @ " << satisfied.toString();
			LOG_PRINT(LOG_INFO) << "\tscore contributed: " << weight;
		}
		LOG_PRINT(LOG_INFO) << "total score of model: " << sum;
	} else {
		double p = vm["prob"].as<double>();
		unsigned int iterations = vm["iterations"].as<unsigned int>();

		LOG(LOG_INFO) << "searching for a maximum-weight model, with p=" << p << " and iterations=" << iterations;
		Model defModel = d->defaultModel();
		Model maxModel = maxWalkSat(*d, iterations, p, &defModel);
		LOG_PRINT(LOG_INFO) << "Best model found: " << std::endl;
		LOG_PRINT(LOG_INFO) << maxModel.toString();
		if (vm.count("output")) {
			// log it to the output file as well
			fprintf(outputFile, "# generated from fact file \"%s\" and formula file \"%s\"\n",
					vm["facts-file"].as<std::string>().c_str(),
					vm["formula-file"].as<std::string>().c_str());
			std::string timeStr;
			{
				time_t rawtime;
				struct tm * timeinfo;
				time (&rawtime);
				timeinfo = localtime (&rawtime);
				timeStr = asctime(timeinfo);
			}
			fprintf(outputFile, "# generated on %s\n", timeStr.c_str());
			fprintf(outputFile, "# run with %d iterations and %g chance of choosing a random move\n",
					iterations,
					p);
			fputs(maxModel.toString().c_str(), outputFile);
		}
	}

	// Should be good and close files?
	return 0;
}
<commit_msg>code now uses correct package name<commit_after>//============================================================================
// Name        : pel.cpp
// Author      : Joe Selman
// Version     :

//============================================================================

#include "PELConfig.h"

#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <boost/foreach.hpp>
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <utility>
#include <ctime>
#include <map>
#include "fol/fol.h"
#include "fol/folparser.h"
#include "fol/domain.h"
#include "log.h"
#include "fol/moves.h"
#include "fol/maxwalksat.h"
#include "fol/formulaset.h"

int main(int argc, char* argv[]) {
	// Declare the supported options.
	po::options_description desc("Allowed options");
	desc.add_options()
	    ("help", "produce help message")
	    ("version,v", "print version and exit")
	    ("max", po::value<unsigned int>(), "maximum value an interval endpoint can take")
	    ("min", po::value<unsigned int>(), "minimum value an interval endpoint can take")
	    ("evalModel,e", "simply print the model weight of the facts file")
	    ("prob,p", po::value<double>()->default_value(0.25), "probability of taking a random move")
	    ("iterations,i", po::value<unsigned int>()->default_value(1000), "number of iterations before returning a model")
	    ("output,o", po::value<std::string>(), "output model file")
	;

	po::options_description hidden("Hidden options");
	hidden.add_options()
		("facts-file", po::value<std::string>(), "facts file")
		("formula-file", po::value<std::string>(), "formula file")
	;
	po::positional_options_description p;
	p.add("facts-file", 1);
	p.add("formula-file", 1);

	po::options_description cmdline_options;
	cmdline_options.add(desc).add(hidden);

	po::variables_map vm;
	po::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm);
	po::notify(vm);

	if (vm.count("version")) {
		std::cout << "pelmap version " << PEL_VERSION_MAJOR << "." << PEL_VERSION_MINOR << std::endl;
		return 0;
	}

	if (vm.count("help") || !vm.count("facts-file") || !vm.count("formula-file")) {
	    std::cout << "Usage: pelmap [OPTION]... FACT-FILE FORMULA-FILE" << std::endl;
		std::cout << desc << std::endl;
	    return 1;
	}

	// setup our logging facilities
	FILE* debugFile = fopen("debug.log", "w");
	if (!debugFile) std::cerr << "unable to open debug.log for logging - logging to stderr";
	else FilePolicy::stream() = debugFile;
	FileLog::globalLogLevel() = LOG_DEBUG;

	LOG(LOG_INFO) << "Opened log file for new session";

	// make sure we can open the output model file, if specified
	FILE* outputFile = NULL;
	if (vm.count("output")) {
		outputFile = fopen(vm["output"].as<std::string>().c_str(), "w");
		if (!outputFile) {
			std::cerr << "unable to open output file \"" << vm["output"].as<std::string>() << "\" for writing." << std::endl;
			return 1;
		}
	}

	boost::shared_ptr<Domain> d = FOLParse::loadDomainFromFiles(vm["facts-file"].as<std::string>(), vm["formula-file"].as<std::string>());
	if (vm.count("max") || vm.count("min")) {
		Interval maxInt = d->maxInterval();
		if (vm.count("max")) maxInt.setFinish(vm["max"].as<unsigned int>());
		if (vm.count("min")) maxInt.setStart(vm["min"].as<unsigned int>());
		d->setMaxInterval(maxInt);
	}

	Model model = d->defaultModel();

	LOG_PRINT(LOG_INFO) << "model size: " << model.size();
	LOG(LOG_DEBUG) << "observation predicates: ";
	for(std::map<std::string, SISet>::const_iterator it = d->observedPredicates().begin();
			it != d->observedPredicates().end();
			it++) {
		LOG(LOG_DEBUG) << "\t" << it->first;
	}

	if (vm.count("evalModel")) {
		LOG(LOG_INFO) << "evaluating model...";
		unsigned long sum = 0;
		// evaluate the weight of each formula in the domain
		for(FormulaSet::const_iterator it = d->formulaSet().begin(); it != d->formulaSet().end(); it++) {
			WSentence formula = *it;
			SISet satisfied = d->satisfied(*(formula.sentence()), model);
			unsigned long weight = d->score(formula, model);
			sum += weight;
			LOG_PRINT(LOG_INFO) << "formula: (" << formula.sentence()->toString() << ")";
			LOG_PRINT(LOG_INFO) << "\tsatisfied @ " << satisfied.toString();
			LOG_PRINT(LOG_INFO) << "\tscore contributed: " << weight;
		}
		LOG_PRINT(LOG_INFO) << "total score of model: " << sum;
	} else {
		double p = vm["prob"].as<double>();
		unsigned int iterations = vm["iterations"].as<unsigned int>();

		LOG(LOG_INFO) << "searching for a maximum-weight model, with p=" << p << " and iterations=" << iterations;
		Model defModel = d->defaultModel();
		Model maxModel = maxWalkSat(*d, iterations, p, &defModel);
		LOG_PRINT(LOG_INFO) << "Best model found: " << std::endl;
		LOG_PRINT(LOG_INFO) << maxModel.toString();
		if (vm.count("output")) {
			// log it to the output file as well
			fprintf(outputFile, "# generated from fact file \"%s\" and formula file \"%s\"\n",
					vm["facts-file"].as<std::string>().c_str(),
					vm["formula-file"].as<std::string>().c_str());
			std::string timeStr;
			{
				time_t rawtime;
				struct tm * timeinfo;
				time (&rawtime);
				timeinfo = localtime (&rawtime);
				timeStr = asctime(timeinfo);
			}
			fprintf(outputFile, "# generated on %s\n", timeStr.c_str());
			fprintf(outputFile, "# run with %d iterations and %g chance of choosing a random move\n",
					iterations,
					p);
			fputs(maxModel.toString().c_str(), outputFile);
		}
	}

	// Should be good and close files?
	return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <pow.h>

#include <arith_uint256.h>
#include <chain.h>
#include <primitives/block.h>
#include <uint256.h>

// ppcoin: find last block index up to pindex
const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
{
    //CBlockIndex will be updated with information about the proof type later
    while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
        pindex = pindex->pprev;
    return pindex;
}

inline arith_uint256 GetLimit(const Consensus::Params& params, bool fProofOfStake)
{
    return fProofOfStake ? UintToArith256(params.posLimit) : UintToArith256(params.powLimit);
}

unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params, bool fProofOfStake)
{

    unsigned int  nTargetLimit = GetLimit(params, fProofOfStake).GetCompact();

    // genesis block
    if (pindexLast == NULL)
        return nTargetLimit;

    // first block
    const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
    if (pindexPrev->pprev == NULL)
        return nTargetLimit;

    // second block
    const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
    if (pindexPrevPrev->pprev == NULL)
        return nTargetLimit;

    // min difficulty
    if (params.fPowAllowMinDifficultyBlocks)
    {
        // Special difficulty rule for testnet:
        // If the new block's timestamp is more than 2* 10 minutes
        // then allow mining of a min-difficulty block.
        if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
            return nTargetLimit;
        else
        {
            // Return the last non-special-min-difficulty-rules-block
            const CBlockIndex* pindex = pindexLast;
            while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval(pindex->nHeight) != 0 && pindex->nBits == nTargetLimit)
                pindex = pindex->pprev;
            return pindex->nBits;
        }
        return pindexLast->nBits;
    }

    return CalculateNextWorkRequired(pindexPrev, pindexPrevPrev->GetBlockTime(), params, fProofOfStake);
}

unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params, bool fProofOfStake)
{
    if(fProofOfStake){
        if (params.fPoSNoRetargeting)
            return pindexLast->nBits;
    }else{
        if (params.fPowNoRetargeting)
            return pindexLast->nBits;
    }
    // Limit adjustment step
    int64_t nTargetSpacing = params.nPowTargetSpacing;
    int64_t nActualSpacing = pindexLast->GetBlockTime() - nFirstBlockTime;
    if (nActualSpacing < 0)
        nActualSpacing = nTargetSpacing;
    if (nActualSpacing > nTargetSpacing * 10)
        nActualSpacing = nTargetSpacing * 10;

	// Retarget
    const arith_uint256 bnTargetLimit = GetLimit(params, fProofOfStake);
    // ppcoin: target change every block
    // ppcoin: retarget with exponential moving toward target spacing
    arith_uint256 bnNew;
    bnNew.SetCompact(pindexLast->nBits);
    int64_t nInterval = params.DifficultyAdjustmentInterval(pindexLast->nHeight);
    bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
    bnNew /= ((nInterval + 1) * nTargetSpacing);

    if (bnNew <= 0 || bnNew > bnTargetLimit)
        bnNew = bnTargetLimit;

    return bnNew.GetCompact();
}

bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params, bool fProofOfStake)
{
    bool fNegative;
    bool fOverflow;
    arith_uint256 bnTarget;

    bnTarget.SetCompact(nBits, &fNegative, &fOverflow);

    // Check range
    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > GetLimit(params, fProofOfStake))
        return false;

    // Check proof of work matches claimed amount
    if (UintToArith256(hash) > bnTarget)
        return false;

    return true;
}
<commit_msg>fix block height<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <pow.h>

#include <arith_uint256.h>
#include <chain.h>
#include <primitives/block.h>
#include <uint256.h>

// ppcoin: find last block index up to pindex
const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
{
    //CBlockIndex will be updated with information about the proof type later
    while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
        pindex = pindex->pprev;
    return pindex;
}

inline arith_uint256 GetLimit(const Consensus::Params& params, bool fProofOfStake)
{
    return fProofOfStake ? UintToArith256(params.posLimit) : UintToArith256(params.powLimit);
}

unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params, bool fProofOfStake)
{

    unsigned int  nTargetLimit = GetLimit(params, fProofOfStake).GetCompact();

    // genesis block
    if (pindexLast == NULL)
        return nTargetLimit;

    // first block
    const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
    if (pindexPrev->pprev == NULL)
        return nTargetLimit;

    // second block
    const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
    if (pindexPrevPrev->pprev == NULL)
        return nTargetLimit;

    // min difficulty
    if (params.fPowAllowMinDifficultyBlocks)
    {
        // Special difficulty rule for testnet:
        // If the new block's timestamp is more than 2* 10 minutes
        // then allow mining of a min-difficulty block.
        if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
            return nTargetLimit;
        else
        {
            // Return the last non-special-min-difficulty-rules-block
            const CBlockIndex* pindex = pindexLast;
            while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval(pindex->nHeight) != 0 && pindex->nBits == nTargetLimit)
                pindex = pindex->pprev;
            return pindex->nBits;
        }
        return pindexLast->nBits;
    }

    return CalculateNextWorkRequired(pindexPrev, pindexPrevPrev->GetBlockTime(), params, fProofOfStake);
}

unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params, bool fProofOfStake)
{
    if(fProofOfStake){
        if (params.fPoSNoRetargeting)
            return pindexLast->nBits;
    }else{
        if (params.fPowNoRetargeting)
            return pindexLast->nBits;
    }
    // Limit adjustment step
    int64_t nTargetSpacing = params.nPowTargetSpacing;
    int64_t nActualSpacing = pindexLast->GetBlockTime() - nFirstBlockTime;
    if (nActualSpacing < 0)
        nActualSpacing = nTargetSpacing;
    if (nActualSpacing > nTargetSpacing * 10)
        nActualSpacing = nTargetSpacing * 10;

	// Retarget
    const arith_uint256 bnTargetLimit = GetLimit(params, fProofOfStake);
    // ppcoin: target change every block
    // ppcoin: retarget with exponential moving toward target spacing
    arith_uint256 bnNew;
    bnNew.SetCompact(pindexLast->nBits);
    int64_t nInterval = params.DifficultyAdjustmentInterval(pindexLast->nHeight + 1);
    bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
    bnNew /= ((nInterval + 1) * nTargetSpacing);

    if (bnNew <= 0 || bnNew > bnTargetLimit)
        bnNew = bnTargetLimit;

    return bnNew.GetCompact();
}

bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params, bool fProofOfStake)
{
    bool fNegative;
    bool fOverflow;
    arith_uint256 bnTarget;

    bnTarget.SetCompact(nBits, &fNegative, &fOverflow);

    // Check range
    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > GetLimit(params, fProofOfStake))
        return false;

    // Check proof of work matches claimed amount
    if (UintToArith256(hash) > bnTarget)
        return false;

    return true;
}
<|endoftext|>


<commit_before>/*
 * File:   qpp.cpp
 * Author: vlad
 *
 * Created on December 12, 2013, 10:43 PM
 */

#include <cstdlib>
#include "qpp.h"

namespace qpp
{

// Random number initialization
std::random_device stat::_rd; // make the random_device generator visible
std::mt19937 stat::_rng(_rd()); // make the mt19937 generator visible

// Various gates (declared extern in "gates.h"); make them visible
namespace gt
{
Eigen::MatrixXcd H, Id2, X, Y, Z, S, T;
Eigen::MatrixXcd CNOT, CP;
Eigen::MatrixXcd TOF(8, 8);
}

// initialize the library
int _init()
{
	// initialize the gates
	gt::_init_gates();

// seed the standard random number generator (needed by Eigen)
	std::srand(static_cast<unsigned int>(stat::_rd()));

	return 0;
}

}
<commit_msg>commit<commit_after>/*
 * File:   qpp.cpp
 * Author: vlad
 *
 * Created on December 12, 2013, 10:43 PM
 */

#include <cstdlib>
#include "qpp.h"

namespace qpp
{

// Random number initialization
std::random_device stat::_rd; // make the random_device generator visible
std::mt19937 stat::_rng(_rd()); // make the mt19937 generator visible, seed it

// Various gates (declared extern in "gates.h"); make them visible
namespace gt
{
Eigen::MatrixXcd H, Id2, X, Y, Z, S, T;
Eigen::MatrixXcd CNOT, CP;
Eigen::MatrixXcd TOF(8, 8);
}

// initialize the library
int _init()
{
	// initialize the gates
	gt::_init_gates();

// seed the standard random number generator (needed by Eigen)
	std::srand(static_cast<unsigned int>(stat::_rd()));

	return 0;
}

}
<|endoftext|>


<commit_before>#include "ray.hpp"

#include <math.h>
#include <array>
#include <algorithm>

#include "constants.hpp"
#include "box2d.hpp"

void Ray::swap(Ray & rhs)
{
  std::swap(m_origin, rhs.m_origin);
  std::swap(m_direction, rhs.m_direction);
}

Ray::Ray(Ray && rhs)
{
  swap(rhs);
}

Ray & Ray::operator=(Ray && rhs)
{
  swap(rhs);
  return *this;
}

bool Ray::operator ==(Ray const & rhs) const
{
  if (this == &rhs) { return true; }

  if (this->m_direction != rhs.direction()) { return false; }
  if (this->m_origin != rhs.origin()) { return false; }

  return true;
}

bool Ray::operator !=(Ray const & rhs) const
{
  return !(this->operator ==(rhs));
}

Ray & Ray::operator=(const Ray & rhs)
{
  Ray tmp(rhs);
  swap(tmp);
  return *this;
}

bool Ray::checkIntersection(
    Ray const & ray,
    Box2D const & box)
{
  // Check if a point inside a box.
  if (Box2D::checkInside(box, ray.origin()))
  {
    return true;
  }

  bool is_special = false;

  // Recalculate box points.
  // Use the point as an origin of a coordinate system for the box.
  float x_1_n = box.boxMin().x() - ray.origin().x();
  float x_2_n = box.boxMax().x() - ray.origin().x();

  float y_1_n = box.boxMin().y() - ray.origin().y();
  float y_2_n = box.boxMax().y() - ray.origin().y();

  float x_3_n = x_1_n;
  float y_3_n = y_2_n;

  float x_4_n = x_2_n;
  float y_4_n = y_1_n;

  float x_ray = ray.direction().x();
  float y_ray = ray.direction().y();

  // It handels special case when rectangle intersepts x-axis
  // to the right from an origin point of a ray.
  if (x_ray < x_1_n && x_ray < x_2_n)
  {
    is_special = true;
  }

  // Check if the x coordinate is zero.
  x_ray = checkZeroDenominator(x_ray);
  x_1_n = checkZeroDenominator(x_1_n);
  x_2_n = checkZeroDenominator(x_2_n);
  x_3_n = checkZeroDenominator(x_3_n);
  x_4_n = checkZeroDenominator(x_4_n);

  // Calculate an anlge for the current point
  // and convert the angle to degrees.
  float angle_ray = convertRadianToDegrees(
        std::atan(y_ray / x_ray));
  float angle_1_n = convertRadianToDegrees(
        std::atan(y_1_n / x_1_n));
  float angle_2_n = convertRadianToDegrees(
        std::atan(y_2_n / x_2_n));
  float angle_3_n = convertRadianToDegrees(
        std::atan(y_3_n / x_3_n));
  float angle_4_n = convertRadianToDegrees(
        std::atan(y_4_n / x_4_n));

  // Correct a value of the angle if needed.
  angle_ray = recalculateAngle(x_ray, y_ray, angle_ray);
  angle_1_n = recalculateAngle(x_1_n, y_1_n, angle_1_n);
  angle_2_n = recalculateAngle(x_2_n, y_2_n, angle_2_n);
  angle_3_n = recalculateAngle(x_3_n, y_3_n, angle_3_n);
  angle_4_n = recalculateAngle(x_4_n, y_4_n, angle_4_n);

  // Combine all angles for the box points.
  std::array<float, 4> angles = {
    angle_1_n, angle_2_n, angle_3_n, angle_4_n
  };

  if (is_special)
  {
    // It finds to angles.
    // Maximum angle in the first quater
    // and the minimun angle in the fouth quater.
    float angle_max_first_quater = 0.0f;
    float angle_min_fourth_quater = 360.0f;

    for (auto const & item : angles)
    {
      if (item < 90.0f)
      {
        if (angle_max_first_quater < item)
        {
          angle_max_first_quater = item;
        }
      }
      else if (item > 270.0f)
      {
        if (angle_min_fourth_quater > item)
        {
          angle_min_fourth_quater = item;
        }
      }
    }

    // Compare the ray angle with
    // the max angle in the first quater
    // and the min angle in the fouth quater.
    if (angle_ray <= angle_max_first_quater &&
        angle_ray >= angle_min_fourth_quater) {
      return true;
    }
  }
  else
  {
    // Find a min and max angles for the box points.
    auto result = std::minmax_element(
          std::begin(angles), std::end(angles));

    // Compare the ray angle with the min
    // and max angles for the box points.
    if (*result.first <= angle_ray &&
        angle_ray <= *result.second) {
      return true;
    }
  }

  return false;
}

float Ray::convertRadianToDegrees(float const & angle)
{
  return angle / Constants::PI * 180;
}

float Ray::recalculateAngle(float const & x,
                            float const & y,
                            float const & angle)
{
  float angle_n = 0.0f;

  // The second quarter.
  if (y > (0.0f - Constants::kEps) &&
      x < (0.0f + Constants::kEps))
  {
    angle_n = 180.0f - abs(angle);
  }

  // The third quarter.
  if (y < 0.0f &&
      x < (0.0f + Constants::kEps))
  {
    angle_n = 180.0f + abs(angle);
  }

  // The fouth quarter.
  if (y < 0.0f &&
      x > 0.0f)
  {
    angle_n = 360.0f - abs(angle);
  }

  return angle_n;
}

float Ray::checkZeroDenominator(float const & value)
{
  float tmp = value;

  if (abs(tmp) < Constants::kEps)
  {
    tmp = Constants::kEps;
  }

  return tmp;
}

void Ray::setOrigin(const Point2D & origin)
{
  m_origin = origin;
}

void Ray::setDirection(const Point2D & direction)
{
  m_direction = direction;
}

std::ostream & operator <<(std::ostream & os,
                           Ray const & rhs)
{
  os << "origin: " << rhs.origin() << "; "
     << "direction: " << rhs.direction() << std::endl;
  return os;
}
<commit_msg>refactor the code: rename point and angle names<commit_after>#include "ray.hpp"

#include <math.h>
#include <array>
#include <algorithm>

#include "constants.hpp"
#include "box2d.hpp"

void Ray::swap(Ray & rhs)
{
  std::swap(m_origin, rhs.m_origin);
  std::swap(m_direction, rhs.m_direction);
}

Ray::Ray(Ray && rhs)
{
  swap(rhs);
}

Ray & Ray::operator=(Ray && rhs)
{
  swap(rhs);
  return *this;
}

bool Ray::operator ==(Ray const & rhs) const
{
  if (this == &rhs) { return true; }

  if (this->m_direction != rhs.direction()) { return false; }
  if (this->m_origin != rhs.origin()) { return false; }

  return true;
}

bool Ray::operator !=(Ray const & rhs) const
{
  return !(this->operator ==(rhs));
}

Ray & Ray::operator=(const Ray & rhs)
{
  Ray tmp(rhs);
  swap(tmp);
  return *this;
}

bool Ray::checkIntersection(
    Ray const & ray,
    Box2D const & box)
{
  // Check if a point inside a box.
  if (Box2D::checkInside(box, ray.origin()))
  {
    return true;
  }

  bool isSpecial = false;

  // Recalculate box points.
  // Use the point as an origin of a coordinate system for the box.
  float xBoxMinLower = box.boxMin().x() - ray.origin().x();
  float xBoxMaxUpper = box.boxMax().x() - ray.origin().x();

  float yBoxMinLower = box.boxMin().y() - ray.origin().y();
  float yBoxMaxUpper = box.boxMax().y() - ray.origin().y();

  float xBoxMinUpper = xBoxMinLower;
  float yBoxMinUpper = yBoxMaxUpper;

  float xBoxMaxLower = xBoxMaxUpper;
  float yBoxMaxLower = yBoxMinLower;

  float xRay = ray.direction().x();
  float yRay = ray.direction().y();

  // It handels special case when rectangle intersepts x-axis
  // to the right from an origin point of a ray.
  if (xRay < xBoxMinLower)
  {
    isSpecial = true;
  }

  // Check if the x coordinate is zero.
  xRay = checkZeroDenominator(xRay);
  xBoxMinLower = checkZeroDenominator(xBoxMinLower);
  xBoxMaxUpper = checkZeroDenominator(xBoxMaxUpper);
  xBoxMinUpper = checkZeroDenominator(xBoxMinUpper);
  xBoxMaxLower = checkZeroDenominator(xBoxMaxLower);

  // Calculate an anlge for the current point
  // and convert the angle to degrees.
  float angleRay = convertRadianToDegrees(
        std::atan(yRay / xRay));

  float angleBoxMinLower = convertRadianToDegrees(
        std::atan(yBoxMinLower / xBoxMinLower));

  float angleBoxMaxUpper = convertRadianToDegrees(
        std::atan(yBoxMaxUpper / xBoxMaxUpper));

  float angleBoxMinUpper = convertRadianToDegrees(
        std::atan(yBoxMinUpper / xBoxMinUpper));

  float angleBoxMaxLower = convertRadianToDegrees(
        std::atan(yBoxMaxLower / xBoxMaxLower));

  // Correct a value of the angle if needed.
  angleRay = recalculateAngle(
        xRay, yRay, angleRay);

  angleBoxMinLower = recalculateAngle(
        xBoxMinLower, yBoxMinLower, angleBoxMinLower);

  angleBoxMaxUpper = recalculateAngle(
        xBoxMaxUpper, yBoxMaxUpper, angleBoxMaxUpper);

  angleBoxMinUpper = recalculateAngle(
        xBoxMinUpper, yBoxMinUpper, angleBoxMinUpper);

  angleBoxMaxLower = recalculateAngle(
        xBoxMaxLower, yBoxMaxLower, angleBoxMaxLower);

  // Combine all angles for the box points.
  std::array<float, 4> angles = {
    angleBoxMinLower, angleBoxMaxUpper,
    angleBoxMinUpper, angleBoxMaxLower
  };

  if (isSpecial)
  {
    // It finds to angles.
    // Maximum angle in the first quater
    // and the minimun angle in the fouth quater.
    float angleMaxFirstQuater = 0.0f;
    float angleMinFourthQuater = 360.0f;

    for (auto const & item : angles)
    {
      if (item < 90.0f)
      {
        if (angleMaxFirstQuater < item)
        {
          angleMaxFirstQuater = item;
        }
      }
      else if (item > 270.0f)
      {
        if (angleMinFourthQuater > item)
        {
          angleMinFourthQuater = item;
        }
      }
    }

    // Compare the ray angle with
    // the max angle in the first quater
    // and the min angle in the fouth quater.
    if (angleRay <= angleMaxFirstQuater &&
        angleRay >= angleMinFourthQuater) {
      return true;
    }
  }
  else
  {
    // Find a min and max angles for the box points.
    auto result = std::minmax_element(
          std::begin(angles), std::end(angles));

    // Compare the ray angle with the min
    // and max angles for the box points.
    if (*result.first <= angleRay &&
        angleRay <= *result.second) {
      return true;
    }
  }

  return false;
}

float Ray::convertRadianToDegrees(float const & angle)
{
  return angle / Constants::PI * 180;
}

float Ray::recalculateAngle(float const & x,
                            float const & y,
                            float const & angle)
{
  float correctedAngle = 0.0f;

  // The second quarter.
  if (y > (0.0f - Constants::kEps) &&
      x < (0.0f + Constants::kEps))
  {
    correctedAngle = 180.0f - abs(angle);
  }

  // The third quarter.
  if (y < 0.0f &&
      x < (0.0f + Constants::kEps))
  {
    correctedAngle = 180.0f + abs(angle);
  }

  // The fouth quarter.
  if (y < 0.0f &&
      x > 0.0f)
  {
    correctedAngle = 360.0f - abs(angle);
  }

  return correctedAngle;
}

float Ray::checkZeroDenominator(float const & value)
{
  float tmp = value;

  if (abs(tmp) < Constants::kEps)
  {
    tmp = Constants::kEps;
  }

  return tmp;
}

void Ray::setOrigin(const Point2D & origin)
{
  m_origin = origin;
}

void Ray::setDirection(const Point2D & direction)
{
  m_direction = direction;
}

std::ostream & operator <<(std::ostream & os,
                           Ray const & rhs)
{
  os << "origin: " << rhs.origin() << "; "
     << "direction: " << rhs.direction() << std::endl;
  return os;
}
<|endoftext|>


<commit_before>#include "mainwindow/mainWindow.h"
#include "thirdparty/windowsmodernstyle.h"

#include <QtCore/QtPlugin>
#include <QtGui/QApplication>

using namespace qReal;

int main(int argc, char *argv[])
{
	int ERROR = trololo;

	QApplication app(argc, argv);

	QTranslator appTranslator;
	if (app.arguments().count() <= 1 || app.arguments().at(1) != "--no-locale") {
		appTranslator.load(":/qrgui_" + QLocale::system().name());
		app.installTranslator(&appTranslator);
	}

#ifndef NO_STYLE_WINDOWSMODERN
	app.setStyle(new WindowsModernStyle());
#endif

	MainWindow window;
	if (window.isVisible())
		return app.exec();
	else  // The window decided to not show itself, exiting now.
		return 0;
}
<commit_msg>jenins fail test fixed<commit_after>#include "mainwindow/mainWindow.h"
#include "thirdparty/windowsmodernstyle.h"

#include <QtCore/QtPlugin>
#include <QtGui/QApplication>

using namespace qReal;

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

	QTranslator appTranslator;
	if (app.arguments().count() <= 1 || app.arguments().at(1) != "--no-locale") {
		appTranslator.load(":/qrgui_" + QLocale::system().name());
		app.installTranslator(&appTranslator);
	}

#ifndef NO_STYLE_WINDOWSMODERN
	app.setStyle(new WindowsModernStyle());
#endif

	MainWindow window;
	if (window.isVisible())
		return app.exec();
	else  // The window decided to not show itself, exiting now.
		return 0;
}
<|endoftext|>


<commit_before>/*****************************************************************************/
/*                                                                           */
/*                                                                           */
/* (c) Copyright 2001 by                                                     */
/*     SINTEF, Oslo, Norway                                                  */
/*     All rights reserved. See the copyright.h for more details.            */
/*                                                                           */
/*****************************************************************************/

#include "copyright.h"

/*
 *
 * $$
 *
 */
#define S1518

#include "sislP.h"

#if defined(SISLNEEDPROTOTYPES)
void
s1518(SISLSurf *surf, double point[], double dir[], double epsge,
	   double start[], double end[], double parin[], double parout[],
	   int *stat)
#else
void s1518(surf, point, dir, epsge, start, end, parin, parout, stat)
     SISLSurf   *surf;
     double point[];
     double dir[];
     double epsge;
     double start[];
     double end[];
     double parin[];
     double parout[];
     int    *stat;
#endif
/*
*********************************************************************
*
*********************************************************************
*
* PURPOSE    : Newton iteration on the intersection between
*              a 3D NURBS surface and a line.
*              If a good initial guess is given, the intersection will
*              be found quickly. However if a bad initial guess is given,
*              the iteration might not converge.
*              We only search in the rectangular subdomain specified
*              by "start" and "end". This can be the whole domain if desired.
*
*
* INPUT      : surf    - The NURBS surface.
*              point   - A point on the line.
*              dir     - The vector direction of the line
*                        (not necessarily normalized).
*              epsge   - Geometric resolution.
*              start   - Lower limits of search rectangle (umin, vmin).
*              end     - Upper limits of search rectangle (umax, vmax).
*              parin   - Initial guess (u0,v0) for parameter point of
*                        intersection (which should be inside the
*                        search rectangle).
*
*
*
* OUTPUT     : parout  - Parameter point (u,v) of intersection.
*              jstat   - status messages
*                                = 1   : Intersection found.
*                                < 0   : error.
*
*
* METHOD     : Newton iteration: we assume the surface is close to
*              the tangent plane through the current estimate s(u_0,v_0)
*              and use the intersection of the line with that (parametric)
*              plane to make the next estimate (u_1,v_1).
*
*
* REFERENCES :
*
*
* WRITTEN BY : Michael Floater, SINTEF Oslo, September 2001.
*
*********************************************************************
*/
{
  int i,j;                  /* For loops. */
  int kstat = 0;            /* Local status variable. */
  int kpos = 0;             /* Error indicator. */
  int num_its = 30;         /* Max number of Newton iterations allowed. */
  double norm1[3];          /* 1st vector normal to dir. */
  double norm2[3];          /* 2nd vector normal to dir. */
  int kleft1=0;             /* Index of knot interval. */
  int kleft2=0;             /* Index of knot interval. */
  int nder=1;               /* evaluate up to derivs of order 1. */
  double parpoint[3];       /* current parameter point. */
  double der[9];            /* surface position and two partial derivatives. */
  double norm[3];           /* surface normal. */
  double a11,a12,a21,a22;   /* Elements of matrix A. */
  double b1,b2;             /* Elements of column vector b. */
  double det;               /* Determinant of A. */
  double du,dv;             /* Increment in parameter point. */
  double su[3],sv[3];       /* two partial derivatives of surface. */
  double pminuss[3];        /* p - s. */
  double epsge2;            /* square of epsge. */

  if(surf->idim != 3) goto error;
  if(start[0] < surf->et1[surf->ik1 - 1]) goto error;
  if(end[0] > surf->et1[surf->in1]) goto error;
  if(start[1] < surf->et2[surf->ik2 - 1]) goto error;
  if(end[1] > surf->et2[surf->in2]) goto error;
  if(parin[0] < start[0] || parin[0] > end[0]) goto error;
  if(parin[1] < start[1] || parin[1] > end[1]) goto error;

  /* Represent line as intersection of two planes, i.e. find
     two vectors norm1 and norm2 of length one,
     perpendicular to the line. */

  s6twonorm(dir,norm1,norm2,&kstat);
    if(kstat < 0) goto error;

  printf("norm1 = %lf %lf %lf\n",norm1[0],norm1[1],norm1[2]);
  printf("norm2 = %lf %lf %lf\n",norm2[0],norm2[1],norm2[2]);

  epsge2 = epsge * epsge;

  parpoint[0] = parin[0];
  parpoint[1] = parin[1];

  printf("parpoint = %lf %lf\n",parpoint[0],parpoint[1]);

  for(i=0; i< num_its; i++)
  {
    /* Evaluate position and 1st derivatives of surface */

    s1421(surf,nder,parpoint,&kleft1,&kleft2,der,norm,&kstat);
    if (kstat < 0) goto error;

    printf("pos = %lf %lf %lf\n",der[0],der[1],der[2]);
    printf("s_u = %lf %lf %lf\n",der[3],der[4],der[5]);
    printf("s_v = %lf %lf %lf\n",der[6],der[7],der[8]);
    printf("norm = %lf %lf %lf\n",norm[0],norm[1],norm[2]);

    /* We assume that s(u,v) is close to the
       parametric plane s(u_0,v_0) + (u-u_0) * s_u + (v-v_0) * s_v,
       i.e. the tangent plane to s at (u_0,v_0).
       We then find (u_1,v_1) where this plane intersects the
       given straight line. We have represented the line as
       those points x in 3D such that

         (x - p) . n1 = 0   (1)
         (x - p) . n2 = 0   (2)

       where p is "point" and n1 = "norm1", "n2 = norm2".
       Thus we solve

         (s(u_0,v_0) + (u_1-u_0) * s_u + (v_1-v_0) * s_v - p) . n1 = 0   (3)
         (s(u_0,v_0) + (u_1-u_0) * s_u + (v_1-v_0) * s_v - p) . n2 = 0   (4)

       which is a 2*2 linear system in the unknowns u_1,v_1.
       This can be written as

         A u = b

       where A = | s_u . n1   s_v . n1 |    b =  | (p - s) . n1 |
                 | s_u . n2   s_v . n2 |         | (p - s) . n2 |

       and u = | du |
               | dv |

       and where du = u_1 - u_0, dv = v_1 - v_0.
       We solve the system for du, dv and find u_1 and v_1 afterwards.

       Note that the distance of the point s(u0,v0) to
       the line is precisely the Euclidean norm of the
       right hand side b. Thus if this is within the
       geometric tolerance, we can stop iterating.
    */

    for(j=0; j<3; j++)
    {
      su[j] = der[j+3];
      sv[j] = der[j+6];
      pminuss[j] = point[j] - der[j];
    }

    b1 = s6scpr(pminuss,norm1,3);
    b2 = s6scpr(pminuss,norm2,3);

    if(b1 * b1 + b2 * b2 <= epsge2) break;

    a11 = s6scpr(su,norm1,3);
    a12 = s6scpr(sv,norm1,3);
    a21 = s6scpr(su,norm2,3);
    a22 = s6scpr(sv,norm2,3);

    det = a11 * a22 - a21 * a12;
    du =  (b1 * a22 - b2 * a12) / det;
    dv =  (a11 * b2 - a21 * b1) / det;

    /* Having now found the increments du,dv, update
       the current parameter point. */

    parpoint[0] += du;    /* u1 = u0 + du; */
    parpoint[1] += dv;    /* v1 = v0 + dv; */

    printf("parpoint = %lf %lf\n",parpoint[0],parpoint[1]);

   if(surf->cuopen_1 == 1)
   {
     if(parpoint[0] < start[0]) parpoint[0] = start[0];
     if(parpoint[0] > end[0]) parpoint[0] = end[0];
   }
   else // closed in u direction
   {
     if(parpoint[0] < start[0]) parpoint[0] = end[0];
     if(parpoint[0] > end[0]) parpoint[0] = start[0];
   }

   if(surf->cuopen_2 == 1)
   {
   if(parpoint[1] < start[1]) parpoint[1] = start[1];
   if(parpoint[1] > end[1]) parpoint[1] = end[1];
   }
   else // closed in v direction
   {
     if(parpoint[1] < start[1]) parpoint[1] = end[1];
     if(parpoint[1] > end[1]) parpoint[1] = start[1];
   }

  }

  parout[0] = parpoint[0];
  parout[1] = parpoint[1];

  printf("parout = %lf %lf\n\n",parout[0],parout[1]);

  goto out;

  /* Error in lower level routine.  */

  error :
  *stat = kstat;
  s6err("s1518", *stat, kpos);
  goto out;

  out:

  return;
}

<commit_msg>Renamed to s1518.c (since it really is c, not c++).<commit_after><|endoftext|>