<commit_before>/*Copyright 2014 George Karagoulis

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

#include "cryptopp_hash.h"
#include "gutil_smartpointer.h"
#include "gutil_globals.h"

#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include <cryptopp/md2.h>
#include <cryptopp/md4.h>
#include <cryptopp/md5.h>
#include <cryptopp/ripemd.h>
#include <cryptopp/sha.h>
#include <cryptopp/sha3.h>
#include <cryptopp/tiger.h>
#include <cryptopp/whrlpool.h>
USING_NAMESPACE_GUTIL;

NAMESPACE_GUTIL1(CryptoPP);

HashBase::HashBase(::CryptoPP::HashTransformation *h)
    :m_hash(h) {}

HashBase::~HashBase() {}

int HashBase::DigestSize() const
{
    return get_hash_transformation()->DigestSize();
}

void HashBase::AddData(const byte *d, GUINT32 len)
{
    get_hash_transformation()->Update(d, len);
}

void HashBase::AddData(GUtil::IInput *input,
                       GUINT32 chunk_size,
                       GUtil::IProgressHandler *ph)
{
    GUINT32 len = input ? input->BytesAvailable() : 0;
    GUINT32 to_read = chunk_size == 0 ? len : GUtil::Min(chunk_size, len);
    GUINT32 read = 0;
    const GUINT32 buf_sz = to_read;

    SmartArrayPointer<byte> buf( new byte[buf_sz] );
    if(ph) ph->ProgressUpdated(0);
    while(read < len)
    {
        if(to_read != input->ReadBytes(buf, buf_sz, to_read))
            THROW_NEW_GUTIL_EXCEPTION2(Exception, "Error reading from device");

        AddData(buf, buf_sz);
        read += to_read;

        if((read + to_read) > len)
            to_read = len - read;

        if(ph){
            if(ph->ShouldOperationCancel())
                THROW_NEW_GUTIL_EXCEPTION(CancelledOperationException);
            ph->ProgressUpdated(((float)read / len) * 100);
        }
    }
    if(ph) ph->ProgressUpdated(100);
}

void HashBase::Final(byte *d)
{
    get_hash_transformation()->Final(d);
}

HashBase *HashBase::CreateHash(HashAlgorithmEnum h)
{
    HashBase *ret;
    switch(h)
    {
    case SHA3_512:
        ret = new Hash<SHA3_512>;
        break;
    case SHA3_384:
        ret = new Hash<SHA3_384>;
        break;
    case SHA3_256:
        ret = new Hash<SHA3_256>;
        break;
    case SHA3_224:
        ret = new Hash<SHA3_224>;
        break;
    case SHA2_512:
        ret = new Hash<SHA2_512>;
        break;
    case SHA2_384:
        ret = new Hash<SHA2_384>;
        break;
    case SHA2_256:
        ret = new Hash<SHA2_256>;
        break;
    case SHA2_224:
        ret = new Hash<SHA2_224>;
        break;
    case SHA1:
        ret = new Hash<SHA1>;
        break;
    case Tiger:
        ret = new Hash<Tiger>;
        break;
    case Whirlpool:
        ret = new Hash<Whirlpool>;
        break;
    case RIPEMD320:
        ret = new Hash<RIPEMD320>;
        break;
    case RIPEMD256:
        ret = new Hash<RIPEMD256>;
        break;
    case RIPEMD160:
        ret = new Hash<RIPEMD160>;
        break;
    case RIPEMD128:
        ret = new Hash<RIPEMD128>;
        break;
    case MD5:
        ret = new Hash<MD5>;
        break;
    case MD4:
        ret = new Hash<MD4>;
        break;
    case MD2:
        ret = new Hash<MD2>;
        break;
    default:
        THROW_NEW_GUTIL_EXCEPTION(NotImplementedException);
    }
    return ret;
}

Hash<SHA3_512>::Hash() :HashBase(new ::CryptoPP::SHA3_512) {}
Hash<SHA3_512>::~Hash() { delete static_cast< ::CryptoPP::SHA3_512 *>(get_hash_transformation()); }

Hash<SHA3_384>::Hash() :HashBase(new ::CryptoPP::SHA3_384) {}
Hash<SHA3_384>::~Hash() { delete static_cast< ::CryptoPP::SHA3_384 *>(get_hash_transformation()); }

Hash<SHA3_256>::Hash() :HashBase(new ::CryptoPP::SHA3_256) {}
Hash<SHA3_256>::~Hash() { delete static_cast< ::CryptoPP::SHA3_256 *>(get_hash_transformation()); }

Hash<SHA3_224>::Hash() :HashBase(new ::CryptoPP::SHA3_224) {}
Hash<SHA3_224>::~Hash() { delete static_cast< ::CryptoPP::SHA3_224 *>(get_hash_transformation()); }

Hash<SHA2_512>::Hash() :HashBase(new ::CryptoPP::SHA512) {}
Hash<SHA2_512>::~Hash() { delete static_cast< ::CryptoPP::SHA512 *>(get_hash_transformation()); }

Hash<SHA2_384>::Hash() :HashBase(new ::CryptoPP::SHA384) {}
Hash<SHA2_384>::~Hash() { delete static_cast< ::CryptoPP::SHA384 *>(get_hash_transformation()); }

Hash<SHA2_256>::Hash() :HashBase(new ::CryptoPP::SHA256) {}
Hash<SHA2_256>::~Hash() { delete static_cast< ::CryptoPP::SHA256 *>(get_hash_transformation()); }

Hash<SHA2_224>::Hash() :HashBase(new ::CryptoPP::SHA224) {}
Hash<SHA2_224>::~Hash() { delete static_cast< ::CryptoPP::SHA224 *>(get_hash_transformation()); }

Hash<RIPEMD320>::Hash() :HashBase(new ::CryptoPP::RIPEMD320) {}
Hash<RIPEMD320>::~Hash() { delete static_cast< ::CryptoPP::RIPEMD320 *>(get_hash_transformation()); }

Hash<RIPEMD256>::Hash() :HashBase(new ::CryptoPP::RIPEMD256) {}
Hash<RIPEMD256>::~Hash() { delete static_cast< ::CryptoPP::RIPEMD256 *>(get_hash_transformation()); }

Hash<RIPEMD160>::Hash() :HashBase(new ::CryptoPP::RIPEMD160) {}
Hash<RIPEMD160>::~Hash() { delete static_cast< ::CryptoPP::RIPEMD160 *>(get_hash_transformation()); }

Hash<RIPEMD128>::Hash() :HashBase(new ::CryptoPP::RIPEMD128) {}
Hash<RIPEMD128>::~Hash() { delete static_cast< ::CryptoPP::RIPEMD128 *>(get_hash_transformation()); }

Hash<Tiger>::Hash() :HashBase(new ::CryptoPP::Tiger) {}
Hash<Tiger>::~Hash() { delete static_cast< ::CryptoPP::Tiger *>(get_hash_transformation()); }

Hash<Whirlpool>::Hash() :HashBase(new ::CryptoPP::Whirlpool) {}
Hash<Whirlpool>::~Hash() { delete static_cast< ::CryptoPP::Whirlpool *>(get_hash_transformation()); }

Hash<SHA1>::Hash() :HashBase(new ::CryptoPP::SHA1) {}
Hash<SHA1>::~Hash() { delete static_cast< ::CryptoPP::SHA1 *>(get_hash_transformation()); }

Hash<MD5>::Hash() :HashBase(new ::CryptoPP::Weak1::MD5) {}
Hash<MD5>::~Hash() { delete static_cast< ::CryptoPP::Weak1::MD5 *>(get_hash_transformation()); }

Hash<MD4>::Hash() :HashBase(new ::CryptoPP::Weak1::MD4) {}
Hash<MD4>::~Hash() { delete static_cast< ::CryptoPP::Weak1::MD4 *>(get_hash_transformation()); }

Hash<MD2>::Hash() :HashBase(new ::CryptoPP::Weak1::MD2) {}
Hash<MD2>::~Hash() { delete static_cast< ::CryptoPP::Weak1::MD2 *>(get_hash_transformation()); }

END_NAMESPACE_GUTIL1;
<commit_msg>Fixed the bug that was screwing up hashes larger than 16384<commit_after>/*Copyright 2014 George Karagoulis

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

#include "cryptopp_hash.h"
#include "gutil_smartpointer.h"
#include "gutil_globals.h"

#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
#include <cryptopp/md2.h>
#include <cryptopp/md4.h>
#include <cryptopp/md5.h>
#include <cryptopp/ripemd.h>
#include <cryptopp/sha.h>
#include <cryptopp/sha3.h>
#include <cryptopp/tiger.h>
#include <cryptopp/whrlpool.h>
USING_NAMESPACE_GUTIL;

NAMESPACE_GUTIL1(CryptoPP);

HashBase::HashBase(::CryptoPP::HashTransformation *h)
    :m_hash(h) {}

HashBase::~HashBase() {}

int HashBase::DigestSize() const
{
    return get_hash_transformation()->DigestSize();
}

void HashBase::AddData(const byte *d, GUINT32 len)
{
    get_hash_transformation()->Update(d, len);
}

void HashBase::AddData(GUtil::IInput *input,
                       GUINT32 chunk_size,
                       GUtil::IProgressHandler *ph)
{
    GUINT32 len = input ? input->BytesAvailable() : 0;
    GUINT32 to_read = chunk_size == 0 ? len : GUtil::Min(chunk_size, len);
    GUINT32 read = 0;
    const GUINT32 buf_sz = to_read;

    SmartArrayPointer<byte> buf( new byte[buf_sz] );
    if(ph) ph->ProgressUpdated(0);
    while(read < len)
    {
        if(to_read != input->ReadBytes(buf, buf_sz, to_read))
            THROW_NEW_GUTIL_EXCEPTION2(Exception, "Error reading from device");

        AddData(buf, to_read);
        read += to_read;

        if((read + to_read) > len)
            to_read = len - read;

        if(ph){
            if(ph->ShouldOperationCancel())
                THROW_NEW_GUTIL_EXCEPTION(CancelledOperationException);
            ph->ProgressUpdated(((float)read / len) * 100);
        }
    }
    if(ph) ph->ProgressUpdated(100);
}

void HashBase::Final(byte *d)
{
    get_hash_transformation()->Final(d);
}

HashBase *HashBase::CreateHash(HashAlgorithmEnum h)
{
    HashBase *ret;
    switch(h)
    {
    case SHA3_512:
        ret = new Hash<SHA3_512>;
        break;
    case SHA3_384:
        ret = new Hash<SHA3_384>;
        break;
    case SHA3_256:
        ret = new Hash<SHA3_256>;
        break;
    case SHA3_224:
        ret = new Hash<SHA3_224>;
        break;
    case SHA2_512:
        ret = new Hash<SHA2_512>;
        break;
    case SHA2_384:
        ret = new Hash<SHA2_384>;
        break;
    case SHA2_256:
        ret = new Hash<SHA2_256>;
        break;
    case SHA2_224:
        ret = new Hash<SHA2_224>;
        break;
    case SHA1:
        ret = new Hash<SHA1>;
        break;
    case Tiger:
        ret = new Hash<Tiger>;
        break;
    case Whirlpool:
        ret = new Hash<Whirlpool>;
        break;
    case RIPEMD320:
        ret = new Hash<RIPEMD320>;
        break;
    case RIPEMD256:
        ret = new Hash<RIPEMD256>;
        break;
    case RIPEMD160:
        ret = new Hash<RIPEMD160>;
        break;
    case RIPEMD128:
        ret = new Hash<RIPEMD128>;
        break;
    case MD5:
        ret = new Hash<MD5>;
        break;
    case MD4:
        ret = new Hash<MD4>;
        break;
    case MD2:
        ret = new Hash<MD2>;
        break;
    default:
        THROW_NEW_GUTIL_EXCEPTION(NotImplementedException);
    }
    return ret;
}

Hash<SHA3_512>::Hash() :HashBase(new ::CryptoPP::SHA3_512) {}
Hash<SHA3_512>::~Hash() { delete static_cast< ::CryptoPP::SHA3_512 *>(get_hash_transformation()); }

Hash<SHA3_384>::Hash() :HashBase(new ::CryptoPP::SHA3_384) {}
Hash<SHA3_384>::~Hash() { delete static_cast< ::CryptoPP::SHA3_384 *>(get_hash_transformation()); }

Hash<SHA3_256>::Hash() :HashBase(new ::CryptoPP::SHA3_256) {}
Hash<SHA3_256>::~Hash() { delete static_cast< ::CryptoPP::SHA3_256 *>(get_hash_transformation()); }

Hash<SHA3_224>::Hash() :HashBase(new ::CryptoPP::SHA3_224) {}
Hash<SHA3_224>::~Hash() { delete static_cast< ::CryptoPP::SHA3_224 *>(get_hash_transformation()); }

Hash<SHA2_512>::Hash() :HashBase(new ::CryptoPP::SHA512) {}
Hash<SHA2_512>::~Hash() { delete static_cast< ::CryptoPP::SHA512 *>(get_hash_transformation()); }

Hash<SHA2_384>::Hash() :HashBase(new ::CryptoPP::SHA384) {}
Hash<SHA2_384>::~Hash() { delete static_cast< ::CryptoPP::SHA384 *>(get_hash_transformation()); }

Hash<SHA2_256>::Hash() :HashBase(new ::CryptoPP::SHA256) {}
Hash<SHA2_256>::~Hash() { delete static_cast< ::CryptoPP::SHA256 *>(get_hash_transformation()); }

Hash<SHA2_224>::Hash() :HashBase(new ::CryptoPP::SHA224) {}
Hash<SHA2_224>::~Hash() { delete static_cast< ::CryptoPP::SHA224 *>(get_hash_transformation()); }

Hash<RIPEMD320>::Hash() :HashBase(new ::CryptoPP::RIPEMD320) {}
Hash<RIPEMD320>::~Hash() { delete static_cast< ::CryptoPP::RIPEMD320 *>(get_hash_transformation()); }

Hash<RIPEMD256>::Hash() :HashBase(new ::CryptoPP::RIPEMD256) {}
Hash<RIPEMD256>::~Hash() { delete static_cast< ::CryptoPP::RIPEMD256 *>(get_hash_transformation()); }

Hash<RIPEMD160>::Hash() :HashBase(new ::CryptoPP::RIPEMD160) {}
Hash<RIPEMD160>::~Hash() { delete static_cast< ::CryptoPP::RIPEMD160 *>(get_hash_transformation()); }

Hash<RIPEMD128>::Hash() :HashBase(new ::CryptoPP::RIPEMD128) {}
Hash<RIPEMD128>::~Hash() { delete static_cast< ::CryptoPP::RIPEMD128 *>(get_hash_transformation()); }

Hash<Tiger>::Hash() :HashBase(new ::CryptoPP::Tiger) {}
Hash<Tiger>::~Hash() { delete static_cast< ::CryptoPP::Tiger *>(get_hash_transformation()); }

Hash<Whirlpool>::Hash() :HashBase(new ::CryptoPP::Whirlpool) {}
Hash<Whirlpool>::~Hash() { delete static_cast< ::CryptoPP::Whirlpool *>(get_hash_transformation()); }

Hash<SHA1>::Hash() :HashBase(new ::CryptoPP::SHA1) {}
Hash<SHA1>::~Hash() { delete static_cast< ::CryptoPP::SHA1 *>(get_hash_transformation()); }

Hash<MD5>::Hash() :HashBase(new ::CryptoPP::Weak1::MD5) {}
Hash<MD5>::~Hash() { delete static_cast< ::CryptoPP::Weak1::MD5 *>(get_hash_transformation()); }

Hash<MD4>::Hash() :HashBase(new ::CryptoPP::Weak1::MD4) {}
Hash<MD4>::~Hash() { delete static_cast< ::CryptoPP::Weak1::MD4 *>(get_hash_transformation()); }

Hash<MD2>::Hash() :HashBase(new ::CryptoPP::Weak1::MD2) {}
Hash<MD2>::~Hash() { delete static_cast< ::CryptoPP::Weak1::MD2 *>(get_hash_transformation()); }

END_NAMESPACE_GUTIL1;
<|endoftext|>


<commit_before>#include <fstream>
#include "object.h"
#include "component.h"
#include "engine.h"
#include "log.h"
#include "sigfile.h"

#include <exception>
#include <algorithm>

namespace gear2d {
  object::object(object::signature & sig)
   : destroyed(false)
   , sig(sig) {
  }

  object::~object() {
    // delete all components
    for (componentcontainer::iterator i = components.begin(); i != components.end(); i++) {
      component::base * c = i->second;
      c->destroyed();
      c->owner = 0;
      engine::remove(c);
      // lets the engine delete c;
    }

    // delete all properties
    for (parameterbase::table::iterator i = parameters.begin(); i != parameters.end(); i++) {
      parameterbase * p = i->second;
      if (p != 0) {
        parameters[p->pid] = 0;
        if (p->dodestroy)  {
          delete p;
        }
      }
    }
  }

  object::id object::oid() { return this; }
  std::string object::name() { return sig["name"]; }

  void object::attach(component::base * newc) throw (evildepends) {
    modinfo("object");
    if (newc == 0) return;

    trace("Attaching", newc->family(), newc->type());

    /* sees that dependencies are met */
    std::string depends = newc->depends();
    bool passed = true;
    std::string d;
    if (depends != "") {
      std::list<std::string> dependencies;
      split(dependencies, depends, ' ');
      while (!dependencies.empty()) {
        component::selector dependency = dependencies.front();

        /* se if family is here */
        component::base * requiredcom = components[dependency.family];
        if (requiredcom == 0) {
          passed = false;
          d = dependency;
          break;
        }

        /* check if dependency has a type. if not, passed. if yes, check */
        if (dependency.type != "") {
          if (requiredcom->type() != dependency.type) {
            passed = false;
            d = dependency;
            break;
          }
        }
        dependencies.pop_front();
      }
    }

    if (passed == false) {
      std::string s;
      s = s + "Component " + newc->family() + "/" + newc->type() + " have unmet dependencies: " + d;
      throw (evildepends(s));
    }

    /* ok... dependency check has passed! */
    component::base * oldc = deattach(newc->family());
    if (oldc != 0) {
      trace("Detaching old component", oldc->type());
    }

    newc->owner = this;
    components[newc->family()] = newc;

    trace("Calling setup on", newc->type());
    newc->setup(sig);
    engine::add(newc);
  }

  component::base * object::deattach(component::family family) {
    component::base * oldc = components[family];
    if (oldc == 0) return 0;
    components.erase(family);
    engine::remove(oldc);
    return oldc;
  }

  parameterbase::value object::get(const parameterbase::id & pid) {
    return parameters[pid];
  }

  void object::set(const parameterbase::id & pid, parameterbase::value v) {
    parameters[pid] = v;
    if (v != 0) {
      v->owner = this;
      v->pid = pid;
    }
  }

  component::base * object::component(gear2d::component::family f) {
    return components[f];
  }

  void object::copy(object::id other) {
    if (other == 0) return;
    for (parameterbase::table::iterator it = parameters.begin(); it != parameters.end(); it++) {
      parameterbase::id pid = it->first;
      parameterbase::value pval = it->second;

      parameterbase::value otherval = other->get(pid);
      pval->set(otherval);
    }
  }

  void object::destroy() {
    destroyed = true;
	for (componentcontainer::iterator it = components.begin(); it != components.end(); it++)
		it->second->destroyed();
    engine::destroy(this);
    ofactory->loadedobjs[sig["name"]].remove(this);
  }

  /* -- factory methods */
  object::factory::factory(component::factory & cfactory) : cfactory(cfactory) {

  }

  void object::factory::load(object::type objtype, std::string filename) {
    modinfo("object-factory");
    /* open the file */
    if (filename == "") filename = objpath + objtype + ".yaml";
    trace("Loading", objtype, "from", filename);
    std::ifstream fin(filename.c_str());
    if (!fin.is_open()) {
      trace("Unable to load", objtype, log::error);
      return;
    }

    /* initialize yaml parser */
    /* YAML::Parser parser(fin);
    YAML::Node node;

    signature & sig = signatures[objtype];
    while (parser.GetNextDocument(node)) {
      trace("node type:", node.Type());
      node >> sig;
    }
    */

    object::signature & sig = signatures[objtype];
    sigfile::load(filename, sig);

    sig["name"] = objtype;

    // add the global signature
    sig.insert(commonsig.begin(), commonsig.end());
    fin.close();
  }

  object::id object::factory::locate(object::type objtype) {
    if (loadedobjs[objtype].size() == 0) return 0;
    else return loadedobjs[objtype].front();
  }

  void object::factory::set(object::type objtype, object::signature sig) {
    signatures[objtype] = sig;
    return;
  }

  void object::factory::innerbuild(object * o, std::string depends) {
    modinfo("object-factory");
    trace("Object:", o->name(), "Depends:", depends);
    std::set<std::string> comlist;
    split(comlist, depends, ' ');
    while(comlist.begin() != comlist.end()) {
      component::selector s = *(comlist.begin());

      /* maybe the object already has these loaded */
      component::base * samecom = o->components[s.family];
      if (samecom != 0) {
        if ((s.type == "")) {
          comlist.erase(comlist.begin());
          continue;
        }
        else if ((samecom->type() == s.type)) {
          comlist.erase(comlist.begin());
          continue;
        }
      }

      /* samecom not found, continue normal attach proccess */
      component::base * c = cfactory.build(s);
      if (c == 0) {
        cfactory.load(s);
        c = cfactory.build(s);
      }

      if (c == 0) continue;

      /* first try to attach the component.
       * if something went wrong, try to load
       * its dependencies. if still going wrong, give up
       * and let it fail */
      try {
        o->attach(c);
      } catch (evildepends & e) {
        /* build dependencies... */
        trace(e.what(), log::info);
        innerbuild(o, c->depends());
        /* if that build did'nt fixed, fuck it. */
        o->attach(c);
      }

      comlist.erase(comlist.begin());
     }
     trace("Finished", o->name(), depends);
  }

  object::id object::factory::build(gear2d::object::type objtype) {
//     cout << "debug: building " << objtype << endl;
    /* first determine if this object type is loaded... */
    if (signatures.find(objtype) == signatures.end()) {
//       std::cerr << "(Object factory) Object type " << objtype << " not found." << std::endl;
      return 0;
    }

    /* now get the signature of this type */
    object::signature & signature = signatures[objtype];

    /* instantiate the object */
    object * obj = new object(signature);
    obj->ofactory = this;

    /* now get the attach string */
    std::string attachstring = signature["attach"];

    /* if nothing to attach, return the object */
    if (attachstring == "") return obj;

    /* recursive build method that takes care of dependency loading */
    innerbuild(obj, attachstring);
    loadedobjs[objtype].push_back(obj);
    return obj;
  }

  evildepends::evildepends (std::string describe) : evil (describe) { }

}
<commit_msg>Removing double destroying of com<commit_after>#include <fstream>
#include "object.h"
#include "component.h"
#include "engine.h"
#include "log.h"
#include "sigfile.h"

#include <exception>
#include <algorithm>

namespace gear2d {
  object::object(object::signature & sig)
   : destroyed(false)
   , sig(sig) {
  }

  object::~object() {
    // delete all components
    for (componentcontainer::iterator i = components.begin(); i != components.end(); i++) {
      component::base * c = i->second;
      c->destroyed();
      c->owner = 0;
      engine::remove(c);
      // lets the engine delete c;
    }

    // delete all properties
    for (parameterbase::table::iterator i = parameters.begin(); i != parameters.end(); i++) {
      parameterbase * p = i->second;
      if (p != 0) {
        parameters[p->pid] = 0;
        if (p->dodestroy)  {
          delete p;
        }
      }
    }
  }

  object::id object::oid() { return this; }
  std::string object::name() { return sig["name"]; }

  void object::attach(component::base * newc) throw (evildepends) {
    modinfo("object");
    if (newc == 0) return;

    trace("Attaching", newc->family(), newc->type());

    /* sees that dependencies are met */
    std::string depends = newc->depends();
    bool passed = true;
    std::string d;
    if (depends != "") {
      std::list<std::string> dependencies;
      split(dependencies, depends, ' ');
      while (!dependencies.empty()) {
        component::selector dependency = dependencies.front();

        /* se if family is here */
        component::base * requiredcom = components[dependency.family];
        if (requiredcom == 0) {
          passed = false;
          d = dependency;
          break;
        }

        /* check if dependency has a type. if not, passed. if yes, check */
        if (dependency.type != "") {
          if (requiredcom->type() != dependency.type) {
            passed = false;
            d = dependency;
            break;
          }
        }
        dependencies.pop_front();
      }
    }

    if (passed == false) {
      std::string s;
      s = s + "Component " + newc->family() + "/" + newc->type() + " have unmet dependencies: " + d;
      throw (evildepends(s));
    }

    /* ok... dependency check has passed! */
    component::base * oldc = deattach(newc->family());
    if (oldc != 0) {
      trace("Detaching old component", oldc->type());
    }

    newc->owner = this;
    components[newc->family()] = newc;

    trace("Calling setup on", newc->type());
    newc->setup(sig);
    engine::add(newc);
  }

  component::base * object::deattach(component::family family) {
    component::base * oldc = components[family];
    if (oldc == 0) return 0;
    components.erase(family);
    engine::remove(oldc);
    return oldc;
  }

  parameterbase::value object::get(const parameterbase::id & pid) {
    return parameters[pid];
  }

  void object::set(const parameterbase::id & pid, parameterbase::value v) {
    parameters[pid] = v;
    if (v != 0) {
      v->owner = this;
      v->pid = pid;
    }
  }

  component::base * object::component(gear2d::component::family f) {
    return components[f];
  }

  void object::copy(object::id other) {
    if (other == 0) return;
    for (parameterbase::table::iterator it = parameters.begin(); it != parameters.end(); it++) {
      parameterbase::id pid = it->first;
      parameterbase::value pval = it->second;

      parameterbase::value otherval = other->get(pid);
      pval->set(otherval);
    }
  }

  void object::destroy() {
    destroyed = true;
    engine::destroy(this);
    ofactory->loadedobjs[sig["name"]].remove(this);
  }

  /* -- factory methods */
  object::factory::factory(component::factory & cfactory) : cfactory(cfactory) {

  }

  void object::factory::load(object::type objtype, std::string filename) {
    modinfo("object-factory");
    /* open the file */
    if (filename == "") filename = objpath + objtype + ".yaml";
    trace("Loading", objtype, "from", filename);
    std::ifstream fin(filename.c_str());
    if (!fin.is_open()) {
      trace("Unable to load", objtype, log::error);
      return;
    }

    /* initialize yaml parser */
    /* YAML::Parser parser(fin);
    YAML::Node node;

    signature & sig = signatures[objtype];
    while (parser.GetNextDocument(node)) {
      trace("node type:", node.Type());
      node >> sig;
    }
    */

    object::signature & sig = signatures[objtype];
    sigfile::load(filename, sig);

    sig["name"] = objtype;

    // add the global signature
    sig.insert(commonsig.begin(), commonsig.end());
    fin.close();
  }

  object::id object::factory::locate(object::type objtype) {
    if (loadedobjs[objtype].size() == 0) return 0;
    else return loadedobjs[objtype].front();
  }

  void object::factory::set(object::type objtype, object::signature sig) {
    signatures[objtype] = sig;
    return;
  }

  void object::factory::innerbuild(object * o, std::string depends) {
    modinfo("object-factory");
    trace("Object:", o->name(), "Depends:", depends);
    std::set<std::string> comlist;
    split(comlist, depends, ' ');
    while(comlist.begin() != comlist.end()) {
      component::selector s = *(comlist.begin());

      /* maybe the object already has these loaded */
      component::base * samecom = o->components[s.family];
      if (samecom != 0) {
        if ((s.type == "")) {
          comlist.erase(comlist.begin());
          continue;
        }
        else if ((samecom->type() == s.type)) {
          comlist.erase(comlist.begin());
          continue;
        }
      }

      /* samecom not found, continue normal attach proccess */
      component::base * c = cfactory.build(s);
      if (c == 0) {
        cfactory.load(s);
        c = cfactory.build(s);
      }

      if (c == 0) continue;

      /* first try to attach the component.
       * if something went wrong, try to load
       * its dependencies. if still going wrong, give up
       * and let it fail */
      try {
        o->attach(c);
      } catch (evildepends & e) {
        /* build dependencies... */
        trace(e.what(), log::info);
        innerbuild(o, c->depends());
        /* if that build did'nt fixed, fuck it. */
        o->attach(c);
      }

      comlist.erase(comlist.begin());
     }
     trace("Finished", o->name(), depends);
  }

  object::id object::factory::build(gear2d::object::type objtype) {
//     cout << "debug: building " << objtype << endl;
    /* first determine if this object type is loaded... */
    if (signatures.find(objtype) == signatures.end()) {
//       std::cerr << "(Object factory) Object type " << objtype << " not found." << std::endl;
      return 0;
    }

    /* now get the signature of this type */
    object::signature & signature = signatures[objtype];

    /* instantiate the object */
    object * obj = new object(signature);
    obj->ofactory = this;

    /* now get the attach string */
    std::string attachstring = signature["attach"];

    /* if nothing to attach, return the object */
    if (attachstring == "") return obj;

    /* recursive build method that takes care of dependency loading */
    innerbuild(obj, attachstring);
    loadedobjs[objtype].push_back(obj);
    return obj;
  }

  evildepends::evildepends (std::string describe) : evil (describe) { }

}
<|endoftext|>


<commit_before>#pragma once

#include "glid.hpp"
#include "noncopyable.hpp"
#include "opengl.hpp"

namespace llogl
{
    namespace v1
    {
        enum class buffer_type: GLuint
        {
            array_buffer = gl::ARRAY_BUFFER,
            atomic_count_buffer = gl::ATOMIC_COUNTER_BUFFER,
            copy_read_buffer = gl::COPY_READ_BUFFER,
            copy_write_buffer = gl::COPY_WRITE_BUFFER,
            element_array_buffer = gl::ELEMENT_ARRAY_BUFFER,
            pixel_pack_buffer = gl::PIXEL_PACK_BUFFER,
            texture_buffer = gl::TEXTURE_BUFFER,
            transform_feedback_buffer = gl::TRANSFORM_FEEDBACK_BUFFER,
            uniform_buffer = gl::UNIFORM_BUFFER
        };

        template <buffer_type T>
        class buffer: noncopyable<buffer<T>>
        {
        public:
            buffer(): id()
            {
            }

            buffer(buffer&& other): id(std::move(other.id))
            {
            }

            buffer<T>& operator=(buffer<T>&& other)
            {
                id = std::move(other.id);
                return *this;
            }

            void bind()
            {
                gl::BindBuffer(static_cast<GLuint>(T), id.get());
            }

            void unbind()
            {
                gl::BindBuffer(static_cast<GLuint>(T), 0);
            }

            void bind_buffer_base(GLuint index)
            {
                gl::BindBufferBase(static_cast<GLuint>(T), index, id.get());
            }

            static GLuint create()
            {
                GLuint id;
                gl::GenBuffers(1, &id);
                return id;
            }

            static void destroy(GLuint& id)
            {
                gl::DeleteBuffers(1, &id);
                id = 0;
            }

        private:
            glid<buffer<T>> id;

            friend GLuint get_id<buffer<T>>(const buffer<T>& t);
        };
    }

    using namespace v1;
}
<commit_msg>Added enum value for draw indirect arrays.<commit_after>#pragma once

#include "glid.hpp"
#include "noncopyable.hpp"
#include "opengl.hpp"

namespace llogl
{
    namespace v1
    {
        enum class buffer_type : GLuint
        {
            array_buffer = gl::ARRAY_BUFFER,
            atomic_count_buffer = gl::ATOMIC_COUNTER_BUFFER,
            copy_read_buffer = gl::COPY_READ_BUFFER,
            copy_write_buffer = gl::COPY_WRITE_BUFFER,
            draw_indirect_buffer = gl::DRAW_INDIRECT_BUFFER,
            element_array_buffer = gl::ELEMENT_ARRAY_BUFFER,
            pixel_pack_buffer = gl::PIXEL_PACK_BUFFER,
            texture_buffer = gl::TEXTURE_BUFFER,
            transform_feedback_buffer = gl::TRANSFORM_FEEDBACK_BUFFER,
            uniform_buffer = gl::UNIFORM_BUFFER
        };

        template <buffer_type T>
        class buffer: noncopyable<buffer<T>>
        {
        public:
            buffer(): id()
            {
            }

            buffer(buffer&& other): id(std::move(other.id))
            {
            }

            buffer<T>& operator=(buffer<T>&& other)
            {
                id = std::move(other.id);
                return *this;
            }

            void bind()
            {
                gl::BindBuffer(static_cast<GLuint>(T), id.get());
            }

            void unbind()
            {
                gl::BindBuffer(static_cast<GLuint>(T), 0);
            }

            void bind_buffer_base(GLuint index)
            {
                gl::BindBufferBase(static_cast<GLuint>(T), index, id.get());
            }

            static GLuint create()
            {
                GLuint id;
                gl::GenBuffers(1, &id);
                return id;
            }

            static void destroy(GLuint& id)
            {
                gl::DeleteBuffers(1, &id);
                id = 0;
            }

        private:
            glid<buffer<T>> id;

            friend GLuint get_id<buffer<T>>(const buffer<T>& t);
        };
    }

    using namespace v1;
}
<|endoftext|>


<commit_before>#include "ofApp.h"

using namespace ofxCv;
using namespace cv;

//--------------------------------------------------------------
void ofApp::setup(){
    cout << "Hello World!";
}

//--------------------------------------------------------------
void ofApp::update(){

}

//--------------------------------------------------------------
void ofApp::draw(){

}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){
    switch (key){

        case 'f':
        case 'F':
            ofToggleFullscreen();
            break;

        default:
            break;
    }

}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}
<commit_msg>setup from ofxFaceTracker example-expression<commit_after>#include "ofApp.h"

using namespace ofxCv;
using namespace cv;

//--------------------------------------------------------------
void ofApp::setup(){
    cout << "Hello World!";

    ofSetVerticalSync(true);
    cam.initGrabber(640, 480);

    tracker.setup();
    tracker.setRescale(.5);
}

//--------------------------------------------------------------
void ofApp::update(){

}

//--------------------------------------------------------------
void ofApp::draw(){

}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){
    switch (key){

        case 'f':
        case 'F':
            ofToggleFullscreen();
            break;

        default:
            break;
    }

}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}
<|endoftext|>


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

#ifndef MAPNIK_IMAGE_HPP
#define MAPNIK_IMAGE_HPP

#include <mapnik/image_data_any.hpp>

namespace mapnik {

class MAPNIK_DECL image
{
public:
    image() = default;
    inline std::size_t width() const { return data_.width(); }
    inline std::size_t height() const { return data_.height(); }
    void set_data(image_data_any && data);
    inline image_data_any const& data() const { return data_;}
    static image read_from_file(std::string const& filename);
    void save_to_file(std::string const& filename, std::string const& format);
private:
    image(image && other) = default;
    image(image_data_any && data) noexcept;
    image_data_any data_;
};

}

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

#ifndef MAPNIK_IMAGE_HPP
#define MAPNIK_IMAGE_HPP

#include <mapnik/image_data_any.hpp>
#include <mapnik/config.hpp>

namespace mapnik {

class MAPNIK_DECL image
{
public:
    image() = default;
    inline std::size_t width() const { return data_.width(); }
    inline std::size_t height() const { return data_.height(); }
    void set_data(image_data_any && data);
    inline image_data_any const& data() const { return data_;}
    static image read_from_file(std::string const& filename);
    void save_to_file(std::string const& filename, std::string const& format);
private:
    image(image && other) = default;
    image(image_data_any && data) noexcept;
    image_data_any data_;
};

}

#endif // MAPNIK_IMAGE_HPP
<|endoftext|>


<commit_before>/*
 * Copyright 2015, Matthew Teasdale <m.teasdale@tcd.ie>
 *
 * ped_hom is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ped_hom is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ped_hom.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <time.h>
#include <boost/algorithm/string.hpp>

void make_hom(std::string ped_line){
  /*
   * Split the line by space or tab
   * Then print the line's header then
   *
   */
  std::vector<std::string> cols;
  boost::split(cols, ped_line, boost::is_any_of(" \t"));

  // print start of header
  std::cout << cols[0]; // fam ID
  std::cout << ' ' <<cols[1]; // sample ID
  std::cout << ' ' <<cols[2]; // parents
  std::cout << ' ' <<cols[3]; // parents
  std::cout << ' ' <<cols[4]; // sex
  std::cout << ' ' <<cols[5]; // status

  // print genotypes
  for(int j=6; j < cols.size(); j +=2){
    int v1 = rand() % 2;
    if(v1 == 0){
      std::cout << ' ' << cols[j] << ' ' << cols[j];
    } else{
      std::cout << ' ' << cols[j+1] << ' ' << cols[j+1];
    }
  }
  // newline beween samples
  std::cout << std::endl;
}

void filter_ped(std::string file_name){
  /*
   * Read the file, check for empty lines
   * and print some errors
   */

  // some input file things
  std::string line;
  std::ifstream myfile(file_name);

  // set random number
  srand(time(NULL));
  int ct = 0;
  // read file
  if (myfile.is_open()){
    // iterating through the file
    while (getline (myfile,line)){

      // Set a counter to update where we are
      ct++;
      if(ct % 100 == 0){
        std::cerr << "Processed " << ct << " samples" <<'\xd';
      };
      // trim string
      boost::trim(line);
      //Check the line isn't empty
      if(line.empty()){
        continue;
      } else{
        make_hom(line);
      }
    }
    // close file
    myfile.close();
  // can't open file
  } else {
    std::cerr << "Unable to open file \n";
  }
  // all is well
  // print final count and tell user we're done
  std::cerr << "Processed " << ct << " samples" <<'\xd';
  std::cerr << std::endl << "Finished filtering" << std::endl;
}

int main (int argc, char* argv[]) {
  /*
   * Simple main statement to show programs name and collect commands
  */
  std::cerr << std::endl;
  std::cerr << "	#######################" << std::endl;
  std::cerr << "	##                   ##" << std::endl;
  std::cerr << "	##      ped_hom      ##" << std::endl;
  std::cerr << "	##     version 0.1   ##" << std::endl;
  std::cerr << "	##                   ##" << std::endl;
  std::cerr << "	#######################" << std::endl;
  std::cerr << std::endl;

  if(argc < 2){
    std::cerr << "Error!! - Usage..... ped_hom input.ped" << std::endl << std::endl;
  } else{
    std::cerr << "Starting filtering" << std::endl;
    filter_ped(argv[1]);
  }
  return 0;
}
<commit_msg>Update ped_hom_0.1.cpp<commit_after>/*
 * Copyright 2015, Matthew Teasdale <m.teasdale@tcd.ie>
 *
 * ped_hom is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ped_hom is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ped_hom.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <time.h>
#include <boost/algorithm/string.hpp>

void make_hom(std::string ped_line){
  /*
   * Split the line by space or tab
   * Then print the line's header then
   *
   */
  std::vector<std::string> cols;
  boost::split(cols, ped_line, boost::is_any_of(" \t"));

  // print start of header
  std::cout << cols[0]; // fam ID
  std::cout << ' ' <<cols[1]; // sample ID
  std::cout << ' ' <<cols[2]; // parents
  std::cout << ' ' <<cols[3]; // parents
  std::cout << ' ' <<cols[4]; // sex
  std::cout << ' ' <<cols[5]; // status

  // print genotypes
  for(int j=6; j < cols.size(); j +=2){
    int v1 = rand() % 2;
    if(v1 == 0){
      std::cout << ' ' << cols[j] << ' ' << cols[j];
    } else{
      std::cout << ' ' << cols[j+1] << ' ' << cols[j+1];
    }
  }
  // newline beween samples
  std::cout << std::endl;
}

void filter_ped(std::string file_name){
  /*
   * Read the file, check for empty lines
   * and print some errors
   */

  // some input file things
  std::string line;
  std::ifstream myfile(file_name);

  // set random number
  srand(time(NULL));
  int ct = 0;
  // read file
  if (myfile.is_open()){
    // iterating through the file
    while (getline (myfile,line)){

      // Set a counter to update where we are
      ct++;
      if(ct % 100 == 0){
        std::cerr << "Processed " << ct << " samples" <<'\xd';
      };
      // trim string
      boost::trim(line);
      //Check the line isn't empty
      if(line.empty()){
        continue;
      } else{
        make_hom(line);
      }
    }
    // close file
    myfile.close();
  // can't open file
  } else {
    std::cerr << "Unable to open file \n";
  }
  // all is well
  // print final count and tell user we're done
  std::cerr << "Processed " << ct << " samples" <<'\xd';
  std::cerr << std::endl << "Finished filtering" << std::endl;
}

int main (int argc, char* argv[]) {
  /*
   * Simple main statement to show programs name and collect commands
  */
  std::cerr << std::endl;
  std::cerr << "ped_hom v 0.1 (21 March 2015)  github.com/teasdalm/ped_hom" << std::endl;
  std::cerr << "(C) Matthew Teasdale 2015  GNU General Public License v3" << std::endl;
  std::cerr << std::endl;

  if(argc < 2){
    std::cerr << "Error!! - Usage..... ped_hom input.ped" << std::endl << std::endl;
  } else{
    std::cerr << "Starting filtering" << std::endl;
    filter_ped(argv[1]);
  }
  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011, Cornell University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of HyperDex nor the names of its contributors may be
//       used to endorse or promote products derived from this software without
//       specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.

// POSIX
#include <signal.h>

// STL
#include <tr1/memory>

// Google Log
#include <glog/logging.h>
#include <glog/raw_logging.h>

// e
#include <e/timer.h>

// HyperDex
#include "hyperdex/hyperdex/coordinatorlink.h"

// HyperDaemon
#include "hyperdaemon/hyperdaemon/daemon.h"
#include "hyperdaemon/datalayer.h"
#include "hyperdaemon/logical.h"
#include "hyperdaemon/network_worker.h"
#include "hyperdaemon/ongoing_state_transfers.h"
#include "hyperdaemon/replication_manager.h"
#include "hyperdaemon/searches.h"

// Configuration

typedef std::tr1::shared_ptr<po6::threads::thread> thread_ptr;

static bool s_continue = true;

void
sig_handle(int /*signum*/)
{
    RAW_LOG(ERROR, "signal received; triggering exit..");
    s_continue = false;
}

int
hyperdaemon :: daemon(po6::pathname datadir,
                      po6::net::location coordinator,
                      uint16_t num_threads,
                      po6::net::ipaddr bind_to,
                      in_port_t incoming,
                      in_port_t outgoing)
{
    // Catch signals.
    struct sigaction handle;
    handle.sa_handler = sig_handle;
    sigfillset(&handle.sa_mask);
    handle.sa_flags = SA_RESTART;
    int ret = 0;
    ret += sigaction(SIGHUP, &handle, NULL);
    ret += sigaction(SIGINT, &handle, NULL);

    if (ret < 0)
    {
        PLOG(INFO) << "could not set signal handlers (sigaction)";
        return EXIT_FAILURE;
    }

    num_threads = s_continue ? num_threads : 0;

    // Setup our link to the coordinator.
    hyperdex::coordinatorlink cl(coordinator);
    // Setup the data component.
    datalayer data(&cl, datadir);
    // Setup the communication component.
    logical comm(&cl, bind_to, incoming, outgoing, num_threads);
    // Create our announce string.
    std::ostringstream announce;
    announce << "instance\t" << comm.inst().inbound.address << "\t"
                             << comm.inst().inbound.port << "\t"
                             << comm.inst().outbound.port
                             << "\t3333\ttoken";
    cl.set_announce(announce.str());
    // Setup the search component.
    searches ssss(&cl, &data, &comm);
    // Setup the recovery component.
    ongoing_state_transfers ost(&data);
    // Setup the replication component.
    replication_manager repl(&cl, &data, &comm, &ost);
    // Give the ongoing_state_transfers a view into the replication component
    ost.set_replication_manager(&repl);

    LOG(INFO) << "Connecting to the coordinator.";

    while (s_continue && cl.connect() != hyperdex::coordinatorlink::SUCCESS)
    {
        PLOG(INFO) << "Coordinator connection failed";
        e::sleep_ms(1, 0);
    }

    // Start the network workers.
    LOG(INFO) << "Starting network workers.";
    network_worker nw(&data, &comm, &ssss, &ost, &repl);
    std::tr1::function<void (network_worker*)> fnw(&network_worker::run);
    std::vector<thread_ptr> threads;

    for (size_t i = 0; i < num_threads; ++i)
    {
        thread_ptr t(new po6::threads::thread(std::tr1::bind(fnw, &nw)));
        t->start();
        threads.push_back(t);
    }

    LOG(INFO) << "Network workers started.";
    uint64_t disconnected_at = e::time();

    while (s_continue)
    {
        if (cl.unacknowledged())
        {
            LOG(INFO) << "Installing new configuration.";
            hyperdex::instance newinst = comm.inst();

            // Figure out which versions we were assigned.
            cl.config().instance_versions(&newinst);

            if (newinst.inbound_version == 0 ||
                newinst.outbound_version == 0)
            {
                LOG(ERROR) << "We've been configured to a dummy node.";
            }

            // Prepare for our new configuration.
            // These operations should assume that there will be network
            // activity, and that the network threads will be in full force.
            comm.prepare(cl.config(), newinst);
            data.prepare(cl.config(), newinst);
            repl.prepare(cl.config(), newinst);
            ssss.prepare(cl.config(), newinst);

            // Protect ourself against exceptions.
            e::guard g1 = e::makeobjguard(comm, &logical::unpause);
            e::guard g2 = e::makeobjguard(comm, &logical::shutdown);

            LOG(INFO) << "Pausing communication for reconfiguration.";

            // Make sure that we wait until everyone is paused.
            comm.pause();

            // Here is the critical section.  This is is mutually exclusive with the
            // network workers' loop.
            comm.reconfigure(cl.config(), newinst);
            data.reconfigure(cl.config(), comm.inst());
            repl.reconfigure(cl.config(), comm.inst());
            ssss.reconfigure(cl.config(), comm.inst());
            comm.unpause();
            g1.dismiss();
            g2.dismiss();
            LOG(INFO) << "Reconfiguration complete; unpausing communication.";

            // Cleanup anything not specified by our new configuration.
            // These operations should assume that there will be network
            // activity, and that the network threads will be in full force..
            ssss.prepare(cl.config(), comm.inst());
            repl.cleanup(cl.config(), comm.inst());
            data.cleanup(cl.config(), comm.inst());
            comm.cleanup(cl.config(), comm.inst());
            cl.acknowledge();
        }

        uint64_t now;

        switch (cl.loop(1, -1))
        {
            case hyperdex::coordinatorlink::SHUTDOWN:
                s_continue = false;
                break;
            case hyperdex::coordinatorlink::SUCCESS:
                break;
            case hyperdex::coordinatorlink::CONNECTFAIL:
            case hyperdex::coordinatorlink::DISCONNECT:
                now = e::time();

                if (now - disconnected_at < 1000000000)
                {
                    e::sleep_ns(0, 1000000000 - (now - disconnected_at));
                }

                if (cl.connect() != hyperdex::coordinatorlink::SUCCESS)
                {
                    PLOG(INFO) << "Coordinator connection failed";
                    e::sleep_ms(1, 0);
                }

                disconnected_at = e::time();
                break;
            case hyperdex::coordinatorlink::LOGICERROR:
            default:
                abort();
        }
    }

    LOG(INFO) << "Exiting daemon.";

    // Stop replication.
    repl.shutdown();
    // Turn off the network.
    comm.shutdown();
    // Cleanup the network_worker threads.
    nw.shutdown();
    // Cleanup the master thread.
    cl.shutdown();
    // Stop the data layer.
    data.shutdown();

    for (std::vector<thread_ptr>::iterator t = threads.begin();
            t != threads.end(); ++t)
    {
        (*t)->join();
    }

    return EXIT_SUCCESS;
}
<commit_msg>Log everything to stdout by default.<commit_after>// Copyright (c) 2011, Cornell University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of HyperDex nor the names of its contributors may be
//       used to endorse or promote products derived from this software without
//       specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.

// POSIX
#include <signal.h>

// STL
#include <tr1/memory>

// Google Log
#include <glog/logging.h>
#include <glog/raw_logging.h>

// e
#include <e/timer.h>

// HyperDex
#include "hyperdex/hyperdex/coordinatorlink.h"

// HyperDaemon
#include "hyperdaemon/hyperdaemon/daemon.h"
#include "hyperdaemon/datalayer.h"
#include "hyperdaemon/logical.h"
#include "hyperdaemon/network_worker.h"
#include "hyperdaemon/ongoing_state_transfers.h"
#include "hyperdaemon/replication_manager.h"
#include "hyperdaemon/searches.h"

// Configuration

typedef std::tr1::shared_ptr<po6::threads::thread> thread_ptr;

static bool s_continue = true;

void
sig_handle(int /*signum*/)
{
    RAW_LOG(ERROR, "signal received; triggering exit..");
    s_continue = false;
}

int
hyperdaemon :: daemon(po6::pathname datadir,
                      po6::net::location coordinator,
                      uint16_t num_threads,
                      po6::net::ipaddr bind_to,
                      in_port_t incoming,
                      in_port_t outgoing)
{
    google::LogToStderr();

    // Catch signals.
    struct sigaction handle;
    handle.sa_handler = sig_handle;
    sigfillset(&handle.sa_mask);
    handle.sa_flags = SA_RESTART;
    int ret = 0;
    ret += sigaction(SIGHUP, &handle, NULL);
    ret += sigaction(SIGINT, &handle, NULL);

    if (ret < 0)
    {
        PLOG(INFO) << "could not set signal handlers (sigaction)";
        return EXIT_FAILURE;
    }

    num_threads = s_continue ? num_threads : 0;

    // Setup our link to the coordinator.
    hyperdex::coordinatorlink cl(coordinator);
    // Setup the data component.
    datalayer data(&cl, datadir);
    // Setup the communication component.
    logical comm(&cl, bind_to, incoming, outgoing, num_threads);
    // Create our announce string.
    std::ostringstream announce;
    announce << "instance\t" << comm.inst().inbound.address << "\t"
                             << comm.inst().inbound.port << "\t"
                             << comm.inst().outbound.port
                             << "\t3333\ttoken";
    cl.set_announce(announce.str());
    // Setup the search component.
    searches ssss(&cl, &data, &comm);
    // Setup the recovery component.
    ongoing_state_transfers ost(&data);
    // Setup the replication component.
    replication_manager repl(&cl, &data, &comm, &ost);
    // Give the ongoing_state_transfers a view into the replication component
    ost.set_replication_manager(&repl);

    LOG(INFO) << "Connecting to the coordinator.";

    while (s_continue && cl.connect() != hyperdex::coordinatorlink::SUCCESS)
    {
        PLOG(INFO) << "Coordinator connection failed";
        e::sleep_ms(1, 0);
    }

    // Start the network workers.
    LOG(INFO) << "Starting network workers.";
    network_worker nw(&data, &comm, &ssss, &ost, &repl);
    std::tr1::function<void (network_worker*)> fnw(&network_worker::run);
    std::vector<thread_ptr> threads;

    for (size_t i = 0; i < num_threads; ++i)
    {
        thread_ptr t(new po6::threads::thread(std::tr1::bind(fnw, &nw)));
        t->start();
        threads.push_back(t);
    }

    LOG(INFO) << "Network workers started.";
    uint64_t disconnected_at = e::time();

    while (s_continue)
    {
        if (cl.unacknowledged())
        {
            LOG(INFO) << "Installing new configuration.";
            hyperdex::instance newinst = comm.inst();

            // Figure out which versions we were assigned.
            cl.config().instance_versions(&newinst);

            if (newinst.inbound_version == 0 ||
                newinst.outbound_version == 0)
            {
                LOG(ERROR) << "We've been configured to a dummy node.";
            }

            // Prepare for our new configuration.
            // These operations should assume that there will be network
            // activity, and that the network threads will be in full force.
            comm.prepare(cl.config(), newinst);
            data.prepare(cl.config(), newinst);
            repl.prepare(cl.config(), newinst);
            ssss.prepare(cl.config(), newinst);

            // Protect ourself against exceptions.
            e::guard g1 = e::makeobjguard(comm, &logical::unpause);
            e::guard g2 = e::makeobjguard(comm, &logical::shutdown);

            LOG(INFO) << "Pausing communication for reconfiguration.";

            // Make sure that we wait until everyone is paused.
            comm.pause();

            // Here is the critical section.  This is is mutually exclusive with the
            // network workers' loop.
            comm.reconfigure(cl.config(), newinst);
            data.reconfigure(cl.config(), comm.inst());
            repl.reconfigure(cl.config(), comm.inst());
            ssss.reconfigure(cl.config(), comm.inst());
            comm.unpause();
            g1.dismiss();
            g2.dismiss();
            LOG(INFO) << "Reconfiguration complete; unpausing communication.";

            // Cleanup anything not specified by our new configuration.
            // These operations should assume that there will be network
            // activity, and that the network threads will be in full force..
            ssss.prepare(cl.config(), comm.inst());
            repl.cleanup(cl.config(), comm.inst());
            data.cleanup(cl.config(), comm.inst());
            comm.cleanup(cl.config(), comm.inst());
            cl.acknowledge();
        }

        uint64_t now;

        switch (cl.loop(1, -1))
        {
            case hyperdex::coordinatorlink::SHUTDOWN:
                s_continue = false;
                break;
            case hyperdex::coordinatorlink::SUCCESS:
                break;
            case hyperdex::coordinatorlink::CONNECTFAIL:
            case hyperdex::coordinatorlink::DISCONNECT:
                now = e::time();

                if (now - disconnected_at < 1000000000)
                {
                    e::sleep_ns(0, 1000000000 - (now - disconnected_at));
                }

                if (cl.connect() != hyperdex::coordinatorlink::SUCCESS)
                {
                    PLOG(INFO) << "Coordinator connection failed";
                    e::sleep_ms(1, 0);
                }

                disconnected_at = e::time();
                break;
            case hyperdex::coordinatorlink::LOGICERROR:
            default:
                abort();
        }
    }

    LOG(INFO) << "Exiting daemon.";

    // Stop replication.
    repl.shutdown();
    // Turn off the network.
    comm.shutdown();
    // Cleanup the network_worker threads.
    nw.shutdown();
    // Cleanup the master thread.
    cl.shutdown();
    // Stop the data layer.
    data.shutdown();

    for (std::vector<thread_ptr>::iterator t = threads.begin();
            t != threads.end(); ++t)
    {
        (*t)->join();
    }

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#ifndef HAXOR_COMPILER_HH
#define HAXOR_COMPILER_HH

#include <string>
#include <vector>
#include <iostream>
#include <map>
#include "haxor/hc/node/all.hh"
#include "haxor/hc/lexer.hh"
#include "haxor/common/cmd.hh"
#include "haxor/common/hdr.hh"
#include "parser.hh"

namespace haxor {
  class instr_spec {
    public:
    instr_spec(enum cmd cmd, std::string args, bool rel, bool x8) {
      this->cmd = cmd;
      this->args = args;
      this->rel = rel;
      this->x8 = x8;
    }
    instr_spec(enum cmd cmd, std::string args) {
      this->cmd = cmd;
      this->args = args;
      this->rel = false;
      this->x8 = false;
    }

    enum cmd cmd;
    std::string args;
    bool rel;
    bool x8;
  };

  class compiler {
    friend class parser;

    public:
    compiler();
    void compile(const std::string &filename);

    private:
    void set_ast(std::vector<node_base*> *ast);
    std::string& get_filename();

    void verify_code();
    void unwind_pseudo();
    void mark_sections();
    void order_sections();
    void calc_addresses();
    void collect_labels();
    hdr_t build_hdr();
    int64_t calc_bss_size();
    uint8_t resolve_reg(const std::string &name);
    std::string format_location(const class location &location);

    class lexer lexer;
    class parser parser;

    std::string filename;
    std::vector<node_base*> *ast;
    std::map<std::string, word_t> labels;

    std::map<std::string, uint8_t> reg_aliases = {
      { "$zero", reg_zero }, { "$at",  reg_accumulator },
      { "$a0",   2 }, { "$a1",  3 }, { "$a2",  4 }, { "$a3",  5 }, { "$a4",  6 },
      { "$a5",   7 }, { "$a6",  8 }, { "$a7",  9 }, { "$a8", 10 }, { "$a9", 11 },
      { "$t0",  12 }, { "$t1", 13 }, { "$t2", 14 }, { "$t3", 15 }, { "$t4", 16 },
      { "$t5",  17 }, { "$t6", 18 }, { "$t7", 19 }, { "$t8", 20 }, { "$t9", 21 },
      { "$sp",  reg_stack }, { "$ra", reg_return }, { "$sc", reg_syscall }
    };

    std::map<std::string, instr_spec> instr_list = {
      { "nop",     instr_spec(cmd_nop,     "") },
      { "exiti",   instr_spec(cmd_exiti,   "i") },
      { "syscall", instr_spec(cmd_syscall, "") },

      { "add",     instr_spec(cmd_add,     "rrr") },
      { "addi",    instr_spec(cmd_addi,    "rri") },
      { "sub",     instr_spec(cmd_sub,     "rrr") },
      { "mult",    instr_spec(cmd_mult,    "rrr") },
      { "div",     instr_spec(cmd_div,     "rrr") },
      { "mod",     instr_spec(cmd_mod,     "rrr") },

      { "lw",      instr_spec(cmd_lw,      "rri") },
      { "sw",      instr_spec(cmd_sw,      "rir") },
      { "lui",     instr_spec(cmd_lui,     "ri") },

      { "and",     instr_spec(cmd_and,     "rrr") },
      { "andi",    instr_spec(cmd_andi,    "rri") },
      { "or",      instr_spec(cmd_or,      "rrr") },
      { "ori",     instr_spec(cmd_ori,     "rri") },
      { "xor",     instr_spec(cmd_xor,     "rrr") },
      { "nor",     instr_spec(cmd_nor,     "rrr") },
      { "slt",     instr_spec(cmd_slt,     "rrr") },
      { "slti",    instr_spec(cmd_slti,    "rri") },

      { "slli",    instr_spec(cmd_slli,    "rri") },
      { "srli",    instr_spec(cmd_srli,    "rri") },
      { "sll",     instr_spec(cmd_sll,     "rrr") },
      { "srl",     instr_spec(cmd_srl,     "rrr") },

      { "beq",     instr_spec(cmd_beq,     "rri", true,  true) },
      { "beql",    instr_spec(cmd_beql,    "rri", true,  true) },
      { "bne",     instr_spec(cmd_bne,     "rri", true,  true) },
      { "bnel",    instr_spec(cmd_bnel,    "rri", true,  true) },
      { "j",       instr_spec(cmd_j,       "i",   false, true) },
      { "jr",      instr_spec(cmd_jr,      "r") },
      { "jal",     instr_spec(cmd_jal,     "i",   false, true) },

      // pseudo

      { "push",    instr_spec(cmd_pseudo,  "r") },
      { "pushi",   instr_spec(cmd_pseudo,  "i") },
      { "pushm",   instr_spec(cmd_pseudo,  "i") },
      { "pop",     instr_spec(cmd_pseudo,  "r") },
      { "popm",    instr_spec(cmd_pseudo,  "i") },
      { "move",    instr_spec(cmd_pseudo,  "rr") },
      { "clear",   instr_spec(cmd_pseudo,  "r") },
      { "not",     instr_spec(cmd_pseudo,  "rr") },
      { "ret",     instr_spec(cmd_pseudo,  "") },
      { "b",       instr_spec(cmd_pseudo,  "i") },
      { "bal",     instr_spec(cmd_pseudo,  "i") },
      { "bgt",     instr_spec(cmd_pseudo,  "rri") },
      { "blt",     instr_spec(cmd_pseudo,  "rri") },
      { "bge",     instr_spec(cmd_pseudo,  "rri") },
      { "ble",     instr_spec(cmd_pseudo,  "rri") },
      { "blez",    instr_spec(cmd_pseudo,  "ri") },
      { "bgtz",    instr_spec(cmd_pseudo,  "ri") },
      { "beqz",    instr_spec(cmd_pseudo,  "ri") },
      { "prol",    instr_spec(cmd_pseudo,  "i") },
      { "epil",    instr_spec(cmd_pseudo,  "") }
    };
  };
}

#endif
<commit_msg>break it into multiple lines for readibility<commit_after>#ifndef HAXOR_COMPILER_HH
#define HAXOR_COMPILER_HH

#include <string>
#include <vector>
#include <iostream>
#include <map>
#include "haxor/hc/node/all.hh"
#include "haxor/hc/lexer.hh"
#include "haxor/common/cmd.hh"
#include "haxor/common/hdr.hh"
#include "parser.hh"

namespace haxor {
  class instr_spec {
    public:
    instr_spec(enum cmd cmd, std::string args, bool rel, bool x8) {
      this->cmd = cmd;
      this->args = args;
      this->rel = rel;
      this->x8 = x8;
    }
    instr_spec(enum cmd cmd, std::string args) {
      this->cmd = cmd;
      this->args = args;
      this->rel = false;
      this->x8 = false;
    }

    enum cmd cmd;
    std::string args;
    bool rel;
    bool x8;
  };

  class compiler {
    friend class parser;

    public:
    compiler();
    void compile(const std::string &filename);

    private:
    void set_ast(std::vector<node_base*> *ast);
    std::string& get_filename();

    void verify_code();
    void unwind_pseudo();
    void mark_sections();
    void order_sections();
    void calc_addresses();
    void collect_labels();
    hdr_t build_hdr();
    int64_t calc_bss_size();
    uint8_t resolve_reg(const std::string &name);
    std::string format_location(const class location &location);

    class lexer lexer;
    class parser parser;

    std::string filename;
    std::vector<node_base*> *ast;
    std::map<std::string, word_t> labels;

    std::map<std::string, uint8_t> reg_aliases = {
      { "$zero", reg_zero },
      { "$at",   reg_accumulator },
      { "$a0",    2 },
      { "$a1",    3 },
      { "$a2",    4 },
      { "$a3",    5 },
      { "$a4",    6 },
      { "$a5",    7 },
      { "$a6",    8 },
      { "$a7" ,   9 },
      { "$a8",   10 },
      { "$a9",   11 },
      { "$t0",   12 },
      { "$t1",   13 },
      { "$t2",   14 },
      { "$t3",   15 },
      { "$t4",   16 },
      { "$t5",   17 },
      { "$t6",   18 },
      { "$t7",   19 },
      { "$t8",   20 },
      { "$t9",   21 },
      { "$sp",   reg_stack },
      { "$ra",   reg_return },
      { "$sc",   reg_syscall }
    };

    std::map<std::string, instr_spec> instr_list = {
      { "nop",     instr_spec(cmd_nop,     "") },
      { "exiti",   instr_spec(cmd_exiti,   "i") },
      { "syscall", instr_spec(cmd_syscall, "") },

      { "add",     instr_spec(cmd_add,     "rrr") },
      { "addi",    instr_spec(cmd_addi,    "rri") },
      { "sub",     instr_spec(cmd_sub,     "rrr") },
      { "mult",    instr_spec(cmd_mult,    "rrr") },
      { "div",     instr_spec(cmd_div,     "rrr") },
      { "mod",     instr_spec(cmd_mod,     "rrr") },

      { "lw",      instr_spec(cmd_lw,      "rri") },
      { "sw",      instr_spec(cmd_sw,      "rir") },
      { "lui",     instr_spec(cmd_lui,     "ri") },

      { "and",     instr_spec(cmd_and,     "rrr") },
      { "andi",    instr_spec(cmd_andi,    "rri") },
      { "or",      instr_spec(cmd_or,      "rrr") },
      { "ori",     instr_spec(cmd_ori,     "rri") },
      { "xor",     instr_spec(cmd_xor,     "rrr") },
      { "nor",     instr_spec(cmd_nor,     "rrr") },
      { "slt",     instr_spec(cmd_slt,     "rrr") },
      { "slti",    instr_spec(cmd_slti,    "rri") },

      { "slli",    instr_spec(cmd_slli,    "rri") },
      { "srli",    instr_spec(cmd_srli,    "rri") },
      { "sll",     instr_spec(cmd_sll,     "rrr") },
      { "srl",     instr_spec(cmd_srl,     "rrr") },

      { "beq",     instr_spec(cmd_beq,     "rri", true,  true) },
      { "beql",    instr_spec(cmd_beql,    "rri", true,  true) },
      { "bne",     instr_spec(cmd_bne,     "rri", true,  true) },
      { "bnel",    instr_spec(cmd_bnel,    "rri", true,  true) },
      { "j",       instr_spec(cmd_j,       "i",   false, true) },
      { "jr",      instr_spec(cmd_jr,      "r") },
      { "jal",     instr_spec(cmd_jal,     "i",   false, true) },

      // pseudo

      { "push",    instr_spec(cmd_pseudo,  "r") },
      { "pushi",   instr_spec(cmd_pseudo,  "i") },
      { "pushm",   instr_spec(cmd_pseudo,  "i") },
      { "pop",     instr_spec(cmd_pseudo,  "r") },
      { "popm",    instr_spec(cmd_pseudo,  "i") },
      { "move",    instr_spec(cmd_pseudo,  "rr") },
      { "clear",   instr_spec(cmd_pseudo,  "r") },
      { "not",     instr_spec(cmd_pseudo,  "rr") },
      { "ret",     instr_spec(cmd_pseudo,  "") },
      { "b",       instr_spec(cmd_pseudo,  "i") },
      { "bal",     instr_spec(cmd_pseudo,  "i") },
      { "bgt",     instr_spec(cmd_pseudo,  "rri") },
      { "blt",     instr_spec(cmd_pseudo,  "rri") },
      { "bge",     instr_spec(cmd_pseudo,  "rri") },
      { "ble",     instr_spec(cmd_pseudo,  "rri") },
      { "blez",    instr_spec(cmd_pseudo,  "ri") },
      { "bgtz",    instr_spec(cmd_pseudo,  "ri") },
      { "beqz",    instr_spec(cmd_pseudo,  "ri") },
      { "prol",    instr_spec(cmd_pseudo,  "i") },
      { "epil",    instr_spec(cmd_pseudo,  "") }
    };
  };
}

#endif
<|endoftext|>


<commit_before>/**
* \file AnnPlayer.hpp
* \brief class that represent the player
* \author A. Brainville (Ybalrid)
*/

#ifndef ANN_PLAYER
#define ANN_PLAYER

#include "systemMacro.h"
#include "AnnVect3.hpp"
#include "AnnQuaternion.hpp"
#include "AnnPlayerActuator.hpp"

#include "euler.h"
#include <btBulletCollisionCommon.h>
#include <btBulletDynamicsCommon.h>

#define DEFAULT_STARTING_POS AnnVect3(0,1,10)
#define DEFAULT_STARTING_ORIENT Ogre::Euler(0)
namespace Annwvyn
{
	enum AnnPlayerMode { STANDING, ROOMSCALE };
	class AnnEngine; //pre-declaration of AnnEngine

	///Parameters of the user's VirtualBody
	class DLL bodyParams
	{
		/**
		* That class was a structure. It is kept as a class with public attributes to keep compatibility with legacy code.
		*/
	public:
		///Constructor that handle the default body parameters.
		bodyParams();

		float eyeHeight;
		float walkSpeed;
		float runFactor;
		float turnSpeed;
		float mass;
		AnnVect3 FeetPosition;
		Ogre::Euler Orientation;
		AnnQuaternion HeadOrientation;

		//bullet
		btCollisionShape* Shape;
		btRigidBody* Body;

		AnnVect3 getHeadPosition() { return (FeetPosition + eyeHeight*AnnVect3::UNIT_Y); }
	};

	///Correspondence between array position and walk direction for the "walking" array
	enum walkDirection { forward, backward, left, right };

	///class that represent the player. This is the user's "Virtual body" in the world. It's the object that you have to move and turn to explore the space.
	class DLL AnnPlayer
	{
	public:

		///Construct the player object
		AnnPlayer();

		///Destroy the player object
		~AnnPlayer();

		///Prevent modification of physical parameter
		void lockParameters();

		///Permit to know if parameters are locked
		bool isLocked();

		///Set the position of the player. If physics is enabled you need to call  AnnEngine::resetPlayerPhysics() to recreate player's body.
		/// \param Position 3D vector representing the position of the player (referenced by the point between his eyes)
		void setPosition(AnnVect3 Position);

		///Set body orientation
		/// \param Orientation Euler angle that represent the orientation of the player's BODY. That orientation is used as a "zero point" for the head orientation.
		void setOrientation(Ogre::Euler Orientation);

		///Set the head orientation
		/// \param HeadOrientation A quaternion representing the orientation of the head
		void setHeadOrientation(AnnQuaternion HeadOrientation);

		///distance between foot-plane and eyes
		/// \param eyeHeight floating point number in meter
		void setEyesHeight(float eyeHeight);

		///WalkSpeed, meters by second
		/// \param walkSpeed The speed a the user is walking
		void setWalkSpeed(float walkSpeed);

		///Turn-speed
		/// \param turnSpeed Angular speed that the user can turn his body
		void setTurnSpeed(float turnSpeed);

		///Mass in Kg
		/// \param mass Mass of the player in Kg
		void setMass(float mass);

		///Bullet shape
		/// \param Shape the Bullet collision shape used to simulate player physics
		void setShape(btCollisionShape* Shape);

		///Bullet RIGID body
		/// \param Body The bullet rigid body used for simulating player's physics
		void setBody(btRigidBody* Body);

		///Get the distance between foot-plane and eyes in meters
		float getEyesHeight();

		///Get a vector that correspond to the translation between the feet point and the eyes
		AnnVect3 getEyeTranslation();

		///Get walk-speed in meter/seconds
		float getWalkSpeed();

		///Get turn-speed in rad/seconds
		float getTurnSpeed();

		///Get mass in Kg
		float getMass();

		///Get position vector
		AnnVect3 getPosition();

		///Get body orientation (Euler vector)
		Ogre::Euler getOrientation();

		///Get rigid body
		btRigidBody* getBody();

		///Get Shape
		btCollisionShape* getShape();

		///Apply a relative yaw transform to the player. Useful to bind it to the mouse X axis for FPS-like gameplay.
		/// \param angle Radian angle of the transformation.
		void applyRelativeBodyYaw(Ogre::Radian angle);

		///Apply the rotation from the mouse relative value
		/// \param relValue Relative value in pixels of the mouse linear movement
		void applyMouseRelativeRotation(int relValue);

		///Return true if physics has been initialized once
		bool hasPhysics();

		///Get the translation vector (normalized) from the walking state
		AnnVect3 getTranslation();

		///Get the translation from analog joystick value
		AnnVect3 getAnalogTranslation();

		///Set the player actuator object
		void setActuator(AnnPlayerActuator* act);

		///Boolean false if the player can get orientation transformation from
		bool standing;

		///Get the ratio between walking and running speed
		float getRunFactor();

		///If the player is handled through the physics engine, this method will detach the rigid-body from the camera,
		///remove it from the dynamics world, de-allocate it from the memory and recreate it from scratch. This is useful for
		///"teleporting" the player, for example if you need to reset his position.
		void resetPlayerPhysics();

		///Teleport the player to the given location, and get it facing the given direction
		void teleport(AnnVect3 position, AnnRadian orientation);

		///Teleport the player without touching it's direction
		void teleport(AnnVect3 position);

		///Set the player mode between standing and roomscale;
		void setMode(AnnPlayerMode playerMode);

		void setRoomRefNode(Ogre::SceneNode* node);

		void reground(float YvalueForGround);
		void reground(AnnVect3 pointOnGround);
		void regroundOnPhysicsBody(float lenght = 1000, AnnVect3 preoffset = AnnVect3::ZERO);

	protected:

		///Object that keep body parameters (= legacy structure)
		bodyParams* playerBody;

	private:

		AnnPlayerMode mode;

		///Give back the right to modify some parameters
		void unlockParameters();

		///Give Annwvyn::AnnEngine the right to access private members
		friend class AnnEngine;
		friend class AnnPhysicsEngine;

		///Engine update call for each frame
		void engineUpdate(float time);

		///Get the pointer to bodyParams (compatibility with legacy code here. Highly dangerous, do not mess with whatever is pointed by that vector. Seriously.
		bodyParams* getLowLevelBodyParams();

		///The famous boolean that permit to prevent YOU for breaking my work! :D
		bool locked;

		///If there is contact with ground
		bool contactWithGround;

		///Apply yaw from analog value
		void applyAnalogYaw();

		///time length of the frame
		double updateTime;

		///Player body physics enabled
		bool physics;

		///PlayerActuator to use
		AnnPlayerActuator* actuator;

		Ogre::SceneNode* RoomReferenceNode;

	public:

		///Turning that off bypass the physics code. Cool for menu scene or weird manipulation of the player object
		bool ignorePhysics;

		///Waling state. Forward Backward Left Right
		bool walking[4];

		///Running state
		bool run;

		//Analog values between -1 and 1
		float analogWalk;
		float analogStraff;
		float analogRotate;
	};
}
#endif //ANN_PLAYER<commit_msg>add some comments for documentation<commit_after>/**
* \file AnnPlayer.hpp
* \brief class that represent the player
* \author A. Brainville (Ybalrid)
*/

#ifndef ANN_PLAYER
#define ANN_PLAYER

#include "systemMacro.h"
#include "AnnVect3.hpp"
#include "AnnQuaternion.hpp"
#include "AnnPlayerActuator.hpp"

#include "euler.h"
#include <btBulletCollisionCommon.h>
#include <btBulletDynamicsCommon.h>

#define DEFAULT_STARTING_POS AnnVect3(0,1,10)
#define DEFAULT_STARTING_ORIENT Ogre::Euler(0)
namespace Annwvyn
{
	enum AnnPlayerMode { STANDING, ROOMSCALE };
	class AnnEngine; //pre-declaration of AnnEngine

	///Parameters of the user's VirtualBody
	class DLL bodyParams
	{
		/**
		* That class was a structure. It is kept as a class with public attributes to keep compatibility with legacy code.
		*/
	public:
		///Constructor that handle the default body parameters.
		bodyParams();

		float eyeHeight;
		float walkSpeed;
		float runFactor;
		float turnSpeed;
		float mass;
		AnnVect3 FeetPosition;
		Ogre::Euler Orientation;
		AnnQuaternion HeadOrientation;

		//bullet
		btCollisionShape* Shape;
		btRigidBody* Body;

		AnnVect3 getHeadPosition() { return (FeetPosition + eyeHeight*AnnVect3::UNIT_Y); }
	};

	///Correspondence between array position and walk direction for the "walking" array
	enum walkDirection { forward, backward, left, right };

	///class that represent the player. This is the user's "Virtual body" in the world. It's the object that you have to move and turn to explore the space.
	class DLL AnnPlayer
	{
	public:

		///Construct the player object
		AnnPlayer();

		///Destroy the player object
		~AnnPlayer();

		///Prevent modification of physical parameter
		void lockParameters();

		///Permit to know if parameters are locked
		bool isLocked();

		///Set the position of the player. If physics is enabled you need to call  AnnEngine::resetPlayerPhysics() to recreate player's body.
		/// \param Position 3D vector representing the position of the player (referenced by the point between his eyes)
		void setPosition(AnnVect3 Position);

		///Set body orientation
		/// \param Orientation Euler angle that represent the orientation of the player's BODY. That orientation is used as a "zero point" for the head orientation.
		void setOrientation(Ogre::Euler Orientation);

		///Set the head orientation
		/// \param HeadOrientation A quaternion representing the orientation of the head
		void setHeadOrientation(AnnQuaternion HeadOrientation);

		///distance between foot-plane and eyes
		/// \param eyeHeight floating point number in meter
		void setEyesHeight(float eyeHeight);

		///WalkSpeed, meters by second
		/// \param walkSpeed The speed a the user is walking
		void setWalkSpeed(float walkSpeed);

		///Turn-speed
		/// \param turnSpeed Angular speed that the user can turn his body
		void setTurnSpeed(float turnSpeed);

		///Mass in Kg
		/// \param mass Mass of the player in Kg
		void setMass(float mass);

		///Bullet shape
		/// \param Shape the Bullet collision shape used to simulate player physics
		void setShape(btCollisionShape* Shape);

		///Bullet RIGID body
		/// \param Body The bullet rigid body used for simulating player's physics
		void setBody(btRigidBody* Body);

		///Get the distance between foot-plane and eyes in meters
		float getEyesHeight();

		///Get a vector that correspond to the translation between the feet point and the eyes
		AnnVect3 getEyeTranslation();

		///Get walk-speed in meter/seconds
		float getWalkSpeed();

		///Get turn-speed in rad/seconds
		float getTurnSpeed();

		///Get mass in Kg
		float getMass();

		///Get position vector
		AnnVect3 getPosition();

		///Get body orientation (Euler vector)
		Ogre::Euler getOrientation();

		///Get rigid body
		btRigidBody* getBody();

		///Get Shape
		btCollisionShape* getShape();

		///Apply a relative yaw transform to the player. Useful to bind it to the mouse X axis for FPS-like gameplay.
		/// \param angle Radian angle of the transformation.
		void applyRelativeBodyYaw(Ogre::Radian angle);

		///Apply the rotation from the mouse relative value
		/// \param relValue Relative value in pixels of the mouse linear movement
		void applyMouseRelativeRotation(int relValue);

		///Return true if physics has been initialized once
		bool hasPhysics();

		///Get the translation vector (normalized) from the walking state
		AnnVect3 getTranslation();

		///Get the translation from analog joystick value
		AnnVect3 getAnalogTranslation();

		///Set the player actuator object
		void setActuator(AnnPlayerActuator* act);

		///Boolean false if the player can get orientation transformation from
		bool standing;

		///Get the ratio between walking and running speed
		float getRunFactor();

		///If the player is handled through the physics engine, this method will detach the rigid-body from the camera,
		///remove it from the dynamics world, de-allocate it from the memory and recreate it from scratch. This is useful for
		///"teleporting" the player, for example if you need to reset his position.
		void resetPlayerPhysics();

		///Teleport the player to the given location, and get it facing the given direction
		void teleport(AnnVect3 position, AnnRadian orientation);

		///Teleport the player without touching it's direction
		void teleport(AnnVect3 position);

		///Set the player mode between standing and roomscale;
		void setMode(AnnPlayerMode playerMode);

		void setRoomRefNode(Ogre::SceneNode* node);

		///Put the reference point for the roomscale VR at Y altitude
		void reground(float YvalueForGround);

		///call reground(pointOnGround.y);
		void reground(AnnVect3 pointOnGround);

		///Shoot a ray form the player to relative -Y. If it hits a rigidbody, call reground() on the impact position
		void regroundOnPhysicsBody(float lenght = 1000, AnnVect3 preoffset = AnnVect3::ZERO);

	protected:

		///Object that keep body parameters (= legacy structure)
		bodyParams* playerBody;

	private:

		AnnPlayerMode mode;

		///Give back the right to modify some parameters
		void unlockParameters();

		///Give Annwvyn::AnnEngine the right to access private members
		friend class AnnEngine;
		friend class AnnPhysicsEngine;

		///Engine update call for each frame
		void engineUpdate(float time);

		///Get the pointer to bodyParams (compatibility with legacy code here. Highly dangerous, do not mess with whatever is pointed by that vector. Seriously.
		bodyParams* getLowLevelBodyParams();

		///The famous boolean that permit to prevent YOU for breaking my work! :D
		bool locked;

		///If there is contact with ground
		bool contactWithGround;

		///Apply yaw from analog value
		void applyAnalogYaw();

		///time length of the frame
		double updateTime;

		///Player body physics enabled
		bool physics;

		///PlayerActuator to use
		AnnPlayerActuator* actuator;

		Ogre::SceneNode* RoomReferenceNode;

	public:

		///Turning that off bypass the physics code. Cool for menu scene or weird manipulation of the player object
		bool ignorePhysics;

		///Waling state. Forward Backward Left Right
		bool walking[4];

		///Running state
		bool run;

		//Analog values between -1 and 1
		float analogWalk;
		float analogStraff;
		float analogRotate;
	};
}
#endif //ANN_PLAYER<|endoftext|>