<commit_before>///
/// @file  print.cpp
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <print.hpp>
#include <primecount-internal.hpp>
#include <int128.hpp>
#include <stdint.h>

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

namespace {

bool print_status_ = false;

bool print_variables_ = false;

}

namespace primecount {

void set_print_status(bool print_status)
{
  print_status_ = print_status;
}

void set_print_variables(bool print_variables)
{
  print_variables_ = print_variables;
}

bool print_result()
{
  return !print_variables();
}

bool print_status()
{
  return print_status_;
}

bool print_variables()
{
  return print_variables_;
}

void print(const string& str)
{
  if (print_status())
    cout << str << endl;
}

void print(maxint_t x, int64_t y, int64_t z, int64_t c, double alpha, int threads)
{
  if (print_status())
  {
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    cout << "z = " << z << endl;
    cout << "c = " << c << endl;
    cout << "alpha = " << fixed << setprecision(3) << alpha << endl;
    cout << "threads = " << validate_threads(threads) << endl;
  }
}

void print(maxint_t x, int64_t y, int threads)
{
  if (print_variables())
  {
    maxint_t z = x / y;
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    cout << "z = " << z << endl;
    cout << "alpha = " << fixed << setprecision(3) << get_alpha(x, y) << endl;
    cout << "threads = " << validate_threads(threads) << endl;
    cout << endl;
  }
}

void print(maxint_t x, int64_t y, int64_t c, int threads)
{
  if (print_variables())
  {
    maxint_t z = x / y;
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    cout << "z = " << z << endl;
    cout << "c = " << c << endl;
    cout << "alpha = " << fixed << setprecision(3) << get_alpha(x, y) << endl;
    cout << "threads = " << validate_threads(threads) << endl;
    cout << endl;
  }
}

void print(const string& res_name, maxint_t res, double time)
{
  if (print_status())
  {
    cout << "\r" << string(50,' ') << "\r";
    cout << "Status: 100%" << endl;
    cout << res_name << " = " << res << endl;
    print_seconds(get_wtime() - time);
  }
}

void print_seconds(double seconds)
{
  cout << "Seconds: " << fixed << setprecision(3) << seconds << endl;
}

} // namespace
<commit_msg>Refactoring<commit_after>///
/// @file  print.cpp
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <print.hpp>
#include <primecount-internal.hpp>
#include <int128.hpp>
#include <stdint.h>

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

namespace {

bool print_result_ = true;

bool print_status_ = false;

bool print_variables_ = false;

}

namespace primecount {

void set_print_status(bool print_status)
{
  print_status_ = print_status;
}

void set_print_variables(bool print_variables)
{
  print_variables_ = print_variables;

  // Avoid printing the result twice in standalone mode
  // when e.g. only computing S2_hard(x, y)
  print_result_ = !print_variables;
}

bool print_result()
{
  return print_result_;
}

bool print_status()
{
  return print_status_;
}

bool print_variables()
{
  return print_variables_;
}

void print(const string& str)
{
  if (print_status())
    cout << str << endl;
}

void print(maxint_t x, int64_t y, int64_t z, int64_t c, double alpha, int threads)
{
  if (print_status() &&
      print_variables())
  {
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    cout << "z = " << z << endl;
    cout << "c = " << c << endl;
    cout << "alpha = " << fixed << setprecision(3) << alpha << endl;
    cout << "threads = " << validate_threads(threads) << endl;
  }
}

void print(maxint_t x, int64_t y, int threads)
{
  if (print_status() &&
      print_variables())
  {
    maxint_t z = x / y;
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    cout << "z = " << z << endl;
    cout << "alpha = " << fixed << setprecision(3) << get_alpha(x, y) << endl;
    cout << "threads = " << validate_threads(threads) << endl;
    cout << endl;
  }
}

void print(maxint_t x, int64_t y, int64_t c, int threads)
{
  if (print_status() &&
      print_variables())
  {
    maxint_t z = x / y;
    cout << "x = " << x << endl;
    cout << "y = " << y << endl;
    cout << "z = " << z << endl;
    cout << "c = " << c << endl;
    cout << "alpha = " << fixed << setprecision(3) << get_alpha(x, y) << endl;
    cout << "threads = " << validate_threads(threads) << endl;
    cout << endl;
  }
}

void print(const string& res_name, maxint_t res, double time)
{
  if (print_status())
  {
    cout << "\r" << string(50,' ') << "\r";
    cout << "Status: 100%" << endl;
    cout << res_name << " = " << res << endl;
    print_seconds(get_wtime() - time);
  }
}

void print_seconds(double seconds)
{
  cout << "Seconds: " << fixed << setprecision(3) << seconds << endl;
}

} // namespace
<|endoftext|>


<commit_before>#pragma once
/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/

#ifndef _QITYPE_DETAILS_TYPESTRING_HXX_
#define _QITYPE_DETAILS_TYPESTRING_HXX_

namespace qi
{
  inline std::string TypeString::getString(void* storage) const
  {
    std::pair<char*, size_t> res = get(storage);
    return std::string(res.first, res.second);
  }
  inline void TypeString::set(void** storage, const std::string& val)
  {
    set(storage, val.c_str(), val.size());
  }
  class QITYPE_API TypeStringImpl: public TypeString
  {
  public:
    typedef DefaultTypeImplMethods<std::string,
      typename detail::TypeImplMethodsBySize<std::string>::type
    > Methods;
    virtual std::pair<char*, size_t> get(void* storage) const
    {
      std::string* ptr = (std::string*)Methods::ptrFromStorage(&storage);
      return std::make_pair((char*)ptr->c_str(), ptr->size());
    }
    virtual void set(void** storage, const char* value, size_t sz)
    {
      std::string* ptr = (std::string*)Methods::ptrFromStorage(storage);
      *ptr = std::string(value, sz);
    }

    _QI_BOUNCE_TYPE_METHODS(Methods);
  };

  template<> class TypeImpl<std::string>: public TypeStringImpl{};

  class QITYPE_API TypeCStringImpl: public TypeString
  {
  public:
    virtual std::pair<char*, size_t> get(void* storage) const
    {
      return std::make_pair((char*)storage, strlen((char*)storage));
    }
    virtual void set(void** storage, const char* ptr, size_t sz)
    {
      *(char**)storage = strdup(ptr);
    }
    virtual void* clone(void* src)
    {
      return strdup((char*)src);
    }
    virtual void destroy(void* src)
    {
      free(src);
    }
    typedef DefaultTypeImplMethods<char*, TypeByValue<char*> > Methods;
    _QI_BOUNCE_TYPE_METHODS_NOCLONE(Methods);
  };

  template<> class TypeImpl<char*>: public TypeCStringImpl{};

  template<int I> class TypeImpl<char [I]>: public TypeString
  {
  public:
    virtual void* clone(void* src)
    {
      char* res = new char[I];
      memcpy(res, src, I);
      return res;
    }
    virtual void destroy(void* ptr)
    {
      delete[]  (char*)ptr;
    }
    virtual std::pair<char*, size_t> get(void* storage) const
    {
      return std::make_pair((char*)storage, I-1);
    }
    virtual void set(void** storage, const char* ptr, size_t sz)
    {
      // haha...no
      qiLogWarning("qi.meta") << "set on C array not implemented";
    }

    typedef  DefaultTypeImplMethods<char[I],
      TypeByPointer<char[I]> > Methods;
      _QI_BOUNCE_TYPE_METHODS_NOCLONE(Methods);
  };
}

#endif  // _QITYPE_DETAILS_TYPESTRING_HXX_
<commit_msg>TypeString: fix clang warning<commit_after>#pragma once
/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/

#ifndef _QITYPE_DETAILS_TYPESTRING_HXX_
#define _QITYPE_DETAILS_TYPESTRING_HXX_

namespace qi
{
  inline std::string TypeString::getString(void* storage) const
  {
    std::pair<char*, size_t> res = get(storage);
    return std::string(res.first, res.second);
  }
  inline void TypeString::set(void** storage, const std::string& val)
  {
    set(storage, val.c_str(), val.size());
  }
  class QITYPE_API TypeStringImpl: public TypeString
  {
  public:
    typedef DefaultTypeImplMethods<std::string,
      detail::TypeImplMethodsBySize<std::string>::type
    > Methods;
    virtual std::pair<char*, size_t> get(void* storage) const
    {
      std::string* ptr = (std::string*)Methods::ptrFromStorage(&storage);
      return std::make_pair((char*)ptr->c_str(), ptr->size());
    }
    virtual void set(void** storage, const char* value, size_t sz)
    {
      std::string* ptr = (std::string*)Methods::ptrFromStorage(storage);
      *ptr = std::string(value, sz);
    }

    _QI_BOUNCE_TYPE_METHODS(Methods);
  };

  template<> class TypeImpl<std::string>: public TypeStringImpl{};

  class QITYPE_API TypeCStringImpl: public TypeString
  {
  public:
    virtual std::pair<char*, size_t> get(void* storage) const
    {
      return std::make_pair((char*)storage, strlen((char*)storage));
    }
    virtual void set(void** storage, const char* ptr, size_t sz)
    {
      *(char**)storage = strdup(ptr);
    }
    virtual void* clone(void* src)
    {
      return strdup((char*)src);
    }
    virtual void destroy(void* src)
    {
      free(src);
    }
    typedef DefaultTypeImplMethods<char*, TypeByValue<char*> > Methods;
    _QI_BOUNCE_TYPE_METHODS_NOCLONE(Methods);
  };

  template<> class TypeImpl<char*>: public TypeCStringImpl{};

  template<int I> class TypeImpl<char [I]>: public TypeString
  {
  public:
    virtual void* clone(void* src)
    {
      char* res = new char[I];
      memcpy(res, src, I);
      return res;
    }
    virtual void destroy(void* ptr)
    {
      delete[]  (char*)ptr;
    }
    virtual std::pair<char*, size_t> get(void* storage) const
    {
      return std::make_pair((char*)storage, I-1);
    }
    virtual void set(void** storage, const char* ptr, size_t sz)
    {
      // haha...no
      qiLogWarning("qi.meta") << "set on C array not implemented";
    }

    typedef  DefaultTypeImplMethods<char[I],
      TypeByPointer<char[I]> > Methods;
      _QI_BOUNCE_TYPE_METHODS_NOCLONE(Methods);
  };
}

#endif  // _QITYPE_DETAILS_TYPESTRING_HXX_
<|endoftext|>


<commit_before>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *
 * This program 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 program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "Tests.h"

#include "Album.h"
#include "AlbumTrack.h"
#include "Artist.h"
#include "Media.h"
#include "Genre.h"

class AlbumTracks : public Tests
{
};

TEST_F( AlbumTracks, Create )
{
    auto album = ml->createAlbum( "album" );
    auto f = ml->addFile( "track1.mp3" );
    auto track = album->addTrack( f, 1, 10 );
    f->save();
    ASSERT_NE( nullptr, track );
    ASSERT_EQ( 10u, track->discNumber() );

    Reload();

    f = std::static_pointer_cast<Media>( ml->media( f->id() ) );
    ASSERT_EQ( 10u, f->albumTrack()->discNumber() );
}

TEST_F( AlbumTracks, Artist )
{
    auto album = ml->createAlbum( "album" );
    auto f = ml->addFile( "track1.mp3" );
    auto track = album->addTrack( f, 1, 0 );
    f->save();

    auto artist = track->artist();
    ASSERT_EQ( nullptr, artist );
    auto newArtist = ml->createArtist( "Dream Seaotter" );
    track->setArtist( newArtist );
    artist = track->artist();
    ASSERT_NE( nullptr, artist );
    ASSERT_EQ( artist->name(), newArtist->name() );

    Reload();

    // Don't reuse the "track" and "f" variable, their type differ
    auto media = ml->media( f->id() );
    auto albumTrack = media->albumTrack();
    artist = albumTrack->artist();
    ASSERT_NE( nullptr, artist );
    ASSERT_EQ( newArtist->name(), artist->name() );
    ASSERT_EQ( newArtist->id(), artist->id() );
}

TEST_F( AlbumTracks, SetGenre )
{
    auto a = ml->createAlbum( "album" );
    auto f = ml->addFile( "track.mp3" );
    auto t = a->addTrack( f, 1, 0 );
    f->save();
    auto genre = ml->createGenre( "happy underground post progressive death metal" );

    ASSERT_EQ( nullptr, t->genre() );
    t->setGenre( genre );
    ASSERT_EQ( t->genre()->name(), "happy underground post progressive death metal" );

    Reload();

    a = std::static_pointer_cast<Album>( ml->album( a->id() ) );
    auto tracks = a->tracks( SortingCriteria::Default, false );
    ASSERT_EQ( tracks.size(), 1u );
    auto t2 = tracks[0];
    ASSERT_EQ( t->genre()->id(), t2->albumTrack()->genre()->id() );
}

TEST_F( AlbumTracks, Media )
{
    auto album = ml->createAlbum( "album" );
    auto f = ml->addFile( "track1.mp3" );
    auto track = album->addTrack( f, 1, 10 );
    f->save();

    auto media = track->media();
    ASSERT_NE( nullptr, media );
    ASSERT_EQ( media->id(), f->id() );

    Reload();

    track = ml->albumTrack( track->id() );
    media = track->media();
    ASSERT_NE( nullptr, media );
    ASSERT_EQ( media->id(), f->id() );
}
<commit_msg>unittests: Add a AlbumTrack::album() test<commit_after>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *
 * This program 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 program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "Tests.h"

#include "Album.h"
#include "AlbumTrack.h"
#include "Artist.h"
#include "Media.h"
#include "Genre.h"

class AlbumTracks : public Tests
{
};

TEST_F( AlbumTracks, Create )
{
    auto album = ml->createAlbum( "album" );
    auto f = ml->addFile( "track1.mp3" );
    auto track = album->addTrack( f, 1, 10 );
    f->save();
    ASSERT_NE( nullptr, track );
    ASSERT_EQ( 10u, track->discNumber() );

    Reload();

    f = std::static_pointer_cast<Media>( ml->media( f->id() ) );
    ASSERT_EQ( 10u, f->albumTrack()->discNumber() );
}

TEST_F( AlbumTracks, Artist )
{
    auto album = ml->createAlbum( "album" );
    auto f = ml->addFile( "track1.mp3" );
    auto track = album->addTrack( f, 1, 0 );
    f->save();

    auto artist = track->artist();
    ASSERT_EQ( nullptr, artist );
    auto newArtist = ml->createArtist( "Dream Seaotter" );
    track->setArtist( newArtist );
    artist = track->artist();
    ASSERT_NE( nullptr, artist );
    ASSERT_EQ( artist->name(), newArtist->name() );

    Reload();

    // Don't reuse the "track" and "f" variable, their type differ
    auto media = ml->media( f->id() );
    auto albumTrack = media->albumTrack();
    artist = albumTrack->artist();
    ASSERT_NE( nullptr, artist );
    ASSERT_EQ( newArtist->name(), artist->name() );
    ASSERT_EQ( newArtist->id(), artist->id() );
}

TEST_F( AlbumTracks, SetGenre )
{
    auto a = ml->createAlbum( "album" );
    auto f = ml->addFile( "track.mp3" );
    auto t = a->addTrack( f, 1, 0 );
    f->save();
    auto genre = ml->createGenre( "happy underground post progressive death metal" );

    ASSERT_EQ( nullptr, t->genre() );
    t->setGenre( genre );
    ASSERT_EQ( t->genre()->name(), "happy underground post progressive death metal" );

    Reload();

    a = std::static_pointer_cast<Album>( ml->album( a->id() ) );
    auto tracks = a->tracks( SortingCriteria::Default, false );
    ASSERT_EQ( tracks.size(), 1u );
    auto t2 = tracks[0];
    ASSERT_EQ( t->genre()->id(), t2->albumTrack()->genre()->id() );
}

TEST_F( AlbumTracks, Media )
{
    auto album = ml->createAlbum( "album" );
    auto f = ml->addFile( "track1.mp3" );
    auto track = album->addTrack( f, 1, 10 );
    f->save();

    auto media = track->media();
    ASSERT_NE( nullptr, media );
    ASSERT_EQ( media->id(), f->id() );

    Reload();

    track = ml->albumTrack( track->id() );
    media = track->media();
    ASSERT_NE( nullptr, media );
    ASSERT_EQ( media->id(), f->id() );
}

TEST_F( AlbumTracks, Album )
{
    auto album = ml->createAlbum( "album" );
    auto f = ml->addFile( "track1.mp3" );
    auto track = album->addTrack( f, 1, 0 );
    f->save();

    auto albumFromTrack = track->album();
    ASSERT_EQ( album, albumFromTrack );

    Reload();

    track = ml->albumTrack( track->id() );
    albumFromTrack = track->album();
    auto a2 = ml->album( album->id() );
    // Fetching this value twice seems to be problematic on Android.
    // Ensure it works for other platforms at least
    auto aft2 = track->album();
    ASSERT_EQ( albumFromTrack, a2 );
    ASSERT_EQ( aft2, a2 );
}
<|endoftext|>


<commit_before>#include <cassert>
#include <future>
#include <netinet/in.h>
#include <rapid/rapid.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

namespace rapid {

Server::Server() {}

void Server::set_port(int port) { _port = port; }

void Server::run() {
  assert(_port != kUndefinedPort);

  std::async(std::launch::deferred, [&] {
    _stopped = false;

    auto sock = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(_port);
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_len = sizeof(addr);
    bind(sock, (struct sockaddr*)&addr, sizeof(addr));
    listen(sock, 5);

    while (!_stop_requested) {
      struct sockaddr_in client_addr;
      auto len = sizeof(client_addr);
      auto peer = accept(sock, (struct sockaddr *)&client_addr, (socklen_t *)&len);
      write(peer, "HELLO", 5);
      close(peer);
    }

    close(sock);

    _stopped = true;
  });
}

void Server::stop() { _stop_requested = true; }

bool Server::stopped() const { return _stopped; }
}<commit_msg>fix threading<commit_after>#include <cassert>
#include <thread>
#include <netinet/in.h>
#include <rapid/rapid.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

namespace rapid {

Server::Server() {}

void Server::set_port(int port) { _port = port; }

void Server::run() {
  assert(_port != kUndefinedPort);

  auto th = std::thread([&] {
    _stopped = false;

    auto sock = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(_port);
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_len = sizeof(addr);
    bind(sock, (struct sockaddr*)&addr, sizeof(addr));
    listen(sock, 5);

    while (!_stop_requested) {
      struct sockaddr_in client_addr;
      auto len = sizeof(client_addr);
      auto peer =
          accept(sock, (struct sockaddr*)&client_addr, (socklen_t*)&len);
      write(peer, "HELLO", 5);
      close(peer);
    }

    close(sock);

    _stopped = true;
  });

  th.detach();
}

void Server::stop() { _stop_requested = true; }

bool Server::stopped() const { return _stopped; }
}<|endoftext|>


<commit_before><commit_msg>boost::random->std::random<commit_after><|endoftext|>


<commit_before>#include "./scene.h"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <string>
#include <vector>
#include <map>
#include "./graphics/gl.h"
#include "./input/invoke_manager.h"
#include "./graphics/render_data.h"
#include "./graphics/managers.h"
#include "./graphics/volume_manager.h"
#include "./graphics/shader_program.h"
#include "./graphics/buffer_drawer.h"
#include "./camera_controllers.h"
#include "./nodes.h"
#include "./camera_node.h"
#include "./label_node.h"
#include "./eigen_qdebug.h"
#include "./utils/path_helper.h"
#include "./placement/to_gray.h"
#include "./placement/distance_transform.h"
#include "./placement/occupancy.h"
#include "./placement/apollonius.h"
#include "./texture_mapper_manager.h"
#include "./constraint_buffer_object.h"
#include "./labelling_coordinator.h"

Scene::Scene(int layerCount, std::shared_ptr<InvokeManager> invokeManager,
             std::shared_ptr<Nodes> nodes, std::shared_ptr<Labels> labels,
             std::shared_ptr<LabellingCoordinator> labellingCoordinator,
             std::shared_ptr<TextureMapperManager> textureMapperManager)

  : nodes(nodes), labels(labels), labellingCoordinator(labellingCoordinator),
    frustumOptimizer(nodes), textureMapperManager(textureMapperManager)
{
  cameraControllers =
      std::make_shared<CameraControllers>(invokeManager, getCamera());

  fbo = std::make_shared<Graphics::FrameBufferObject>(layerCount);
  constraintBufferObject = std::make_shared<ConstraintBufferObject>();
  managers = std::make_shared<Graphics::Managers>();
}

Scene::~Scene()
{
  nodes->clear();
  qInfo() << "Destructor of Scene"
          << "Remaining managers instances" << managers.use_count();
}

void Scene::initialize()
{
  glAssert(gl->glClearColor(0.9f, 0.9f, 0.8f, 1.0f));

  quad = std::make_shared<Graphics::ScreenQuad>(
      ":shader/pass.vert", ":shader/textureForRenderBuffer.frag");
  screenQuad = std::make_shared<Graphics::ScreenQuad>(
      ":shader/pass.vert", ":shader/combineLayers.frag");
  positionQuad = std::make_shared<Graphics::ScreenQuad>(
      ":shader/pass.vert", ":shader/positionRenderTarget.frag");
  distanceTransformQuad = std::make_shared<Graphics::ScreenQuad>(
      ":shader/pass.vert", ":shader/distanceTransform.frag");
  transparentQuad = std::make_shared<Graphics::ScreenQuad>(
      ":shader/pass.vert", ":shader/transparentOverlay.frag");

  fbo->initialize(gl, width, height);
  picker = std::make_unique<Picker>(fbo, gl, labels);
  picker->resize(width, height);
  constraintBufferObject->initialize(gl, textureMapperManager->getBufferSize(),
                                     textureMapperManager->getBufferSize());
  haBuffer =
      std::make_shared<Graphics::HABuffer>(Eigen::Vector2i(width, height));
  managers->getShaderManager()->initialize(gl, haBuffer);

  managers->getObjectManager()->initialize(gl, 128, 10000000);
  haBuffer->initialize(gl, managers);
  quad->initialize(gl, managers);
  screenQuad->initialize(gl, managers);
  positionQuad->initialize(gl, managers);
  distanceTransformQuad->initialize(gl, managers);
  transparentQuad->initialize(gl, managers);

  managers->getTextureManager()->initialize(gl, true, 8);

  textureMapperManager->createTextureMappersForLayers(fbo->getLayerCount());
  textureMapperManager->resize(width, height);
  textureMapperManager->initialize(gl, fbo, constraintBufferObject);

  auto drawer = std::make_shared<Graphics::BufferDrawer>(
      textureMapperManager->getBufferSize(),
      textureMapperManager->getBufferSize(), gl, managers->getShaderManager());

  labellingCoordinator->initialize(textureMapperManager->getBufferSize(),
                                   drawer, textureMapperManager, width, height);
}

void Scene::cleanup()
{
  labellingCoordinator->cleanup();

  textureMapperManager->cleanup();
}

void Scene::update(double frameTime, QSet<Qt::Key> keysPressed)
{
  auto camera = getCamera();

  if (camera->needsResizing())
    camera->resize(width, height);

  this->frameTime = frameTime;
  cameraControllers->update(camera, frameTime);

  frustumOptimizer.update(camera->getViewMatrix());
  camera->updateNearAndFarPlanes(frustumOptimizer.getNear(),
                                 frustumOptimizer.getFar());
  haBuffer->updateNearAndFarPlanes(frustumOptimizer.getNear(),
                                   frustumOptimizer.getFar());

  labellingCoordinator->update(frameTime, camera->getProjectionMatrix(),
                               camera->getViewMatrix(), activeLayerNumber);
}

void Scene::render()
{
  auto camera = getCamera();

  if (shouldResize)
  {
    camera->resize(width, height);
    fbo->resize(width, height);
    shouldResize = false;
  }

  glAssert(gl->glViewport(0, 0, width, height));
  glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));

  RenderData renderData = createRenderData();

  renderNodesWithHABufferIntoFBO(renderData);

  glAssert(gl->glDisable(GL_DEPTH_TEST));
  renderScreenQuad();

  textureMapperManager->update();

  constraintBufferObject->bind();

  labellingCoordinator->updatePlacement();

  constraintBufferObject->unbind();

  glAssert(gl->glViewport(0, 0, width, height));

  if (showConstraintOverlay)
  {
    constraintBufferObject->bindTexture(GL_TEXTURE0);
    renderQuad(transparentQuad, Eigen::Matrix4f::Identity());
  }

  if (showBufferDebuggingViews)
    renderDebuggingViews(renderData);

  glAssert(gl->glEnable(GL_DEPTH_TEST));

  nodes->renderLabels(gl, managers, renderData);
}

void Scene::renderNodesWithHABufferIntoFBO(const RenderData &renderData)
{
  fbo->bind();
  glAssert(gl->glViewport(0, 0, width, height));
  glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));

  haBuffer->clearAndPrepare(managers);

  nodes->render(gl, managers, renderData);

  managers->getObjectManager()->render(renderData);

  std::vector<float> zValues = labellingCoordinator->updateClusters();

  haBuffer->setLayerZValues(zValues);
  haBuffer->render(managers, renderData);

  picker->doPick(renderData.viewProjectionMatrix);

  fbo->unbind();
}

void Scene::renderDebuggingViews(const RenderData &renderData)
{
  for (int i = 0; i < fbo->getLayerCount(); ++i)
  {
    fbo->bindColorTexture(i, GL_TEXTURE0);
    auto transformation = Eigen::Affine3f(
        Eigen::Translation3f(Eigen::Vector3f(-0.8 + 0.4 * i, -0.4, 0)) *
        Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
    renderQuad(quad, transformation.matrix());
  }

  for (int i = 0; i < fbo->getLayerCount(); ++i)
  {
    fbo->bindDepthTexture(i, GL_TEXTURE0);
    auto transformation = Eigen::Affine3f(
        Eigen::Translation3f(Eigen::Vector3f(-0.8 + 0.4 * i, 0.8, 0)) *
        Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
    renderQuad(quad, transformation.matrix());
  }

  fbo->bindDepthTexture(GL_TEXTURE0);
  auto transformation =
      Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(-0.8, -0.8, 0)) *
                      Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
  renderQuad(quad, transformation.matrix());

  int layerIndex = activeLayerNumber == 0 ? 0 : activeLayerNumber - 1;
  textureMapperManager->bindOccupancyTexture(layerIndex);
  transformation =
      Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(-0.4, -0.8, 0)) *
                      Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
  renderQuad(quad, transformation.matrix());

  textureMapperManager->bindDistanceTransform(layerIndex);
  transformation =
      Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.0, -0.8, 0)) *
                      Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
  renderQuad(distanceTransformQuad, transformation.matrix());

  textureMapperManager->bindApollonius(layerIndex);
  transformation =
      Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.4, -0.8, 0)) *
                      Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
  renderQuad(quad, transformation.matrix());

  constraintBufferObject->bindTexture(GL_TEXTURE0);
  transformation =
      Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.8, -0.8, 0)) *
                      Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
  renderQuad(quad, transformation.matrix());
}

void Scene::renderQuad(std::shared_ptr<Graphics::ScreenQuad> quad,
                       Eigen::Matrix4f modelMatrix)
{
  RenderData renderData;
  renderData.modelMatrix = modelMatrix;

  quad->getShaderProgram()->bind();
  quad->getShaderProgram()->setUniform("textureSampler", 0);
  quad->renderImmediately(gl, managers, renderData);
}

void Scene::renderScreenQuad()
{
  if (activeLayerNumber == 0)
  {
    fbo->bindColorTexture(0, GL_TEXTURE0);
    fbo->bindColorTexture(1, GL_TEXTURE1);
    fbo->bindColorTexture(2, GL_TEXTURE2);
    fbo->bindColorTexture(3, GL_TEXTURE3);

    screenQuad->getShaderProgram()->setUniform("layer1", 0);
    screenQuad->getShaderProgram()->setUniform("layer2", 1);
    screenQuad->getShaderProgram()->setUniform("layer3", 2);
    screenQuad->getShaderProgram()->setUniform("layer4", 3);
    renderQuad(screenQuad, Eigen::Matrix4f::Identity());

    gl->glActiveTexture(GL_TEXTURE0);
  }
  else
  {
    fbo->bindColorTexture(activeLayerNumber - 1, GL_TEXTURE0);
    renderQuad(quad, Eigen::Matrix4f::Identity());
  }
}

void Scene::resize(int width, int height)
{
  this->width = width;
  this->height = height;

  shouldResize = true;

  labellingCoordinator->resize(width, height);
}

RenderData Scene::createRenderData()
{
  auto camera = getCamera();

  return RenderData(camera->getProjectionMatrix(), camera->getViewMatrix(),
                    camera->getPosition(), Eigen::Vector2f(width, height));
}

void Scene::pick(int id, Eigen::Vector2f position)
{
  if (picker.get())
    picker->pick(id, position);
}

void Scene::enableBufferDebuggingViews(bool enable)
{
  showBufferDebuggingViews = enable;
}

void Scene::enableConstraingOverlay(bool enable)
{
  showConstraintOverlay = enable;
}

std::shared_ptr<Camera> Scene::getCamera()
{
  return nodes->getCameraNode()->getCamera();
}

void Scene::setRenderLayer(int layerNumber)
{
  activeLayerNumber = layerNumber;
}

<commit_msg>Render labels and final screen quad after label placement.<commit_after>#include "./scene.h"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <string>
#include <vector>
#include <map>
#include "./graphics/gl.h"
#include "./input/invoke_manager.h"
#include "./graphics/render_data.h"
#include "./graphics/managers.h"
#include "./graphics/volume_manager.h"
#include "./graphics/shader_program.h"
#include "./graphics/buffer_drawer.h"
#include "./camera_controllers.h"
#include "./nodes.h"
#include "./camera_node.h"
#include "./label_node.h"
#include "./eigen_qdebug.h"
#include "./utils/path_helper.h"
#include "./placement/to_gray.h"
#include "./placement/distance_transform.h"
#include "./placement/occupancy.h"
#include "./placement/apollonius.h"
#include "./texture_mapper_manager.h"
#include "./constraint_buffer_object.h"
#include "./labelling_coordinator.h"

Scene::Scene(int layerCount, std::shared_ptr<InvokeManager> invokeManager,
             std::shared_ptr<Nodes> nodes, std::shared_ptr<Labels> labels,
             std::shared_ptr<LabellingCoordinator> labellingCoordinator,
             std::shared_ptr<TextureMapperManager> textureMapperManager)

  : nodes(nodes), labels(labels), labellingCoordinator(labellingCoordinator),
    frustumOptimizer(nodes), textureMapperManager(textureMapperManager)
{
  cameraControllers =
      std::make_shared<CameraControllers>(invokeManager, getCamera());

  fbo = std::make_shared<Graphics::FrameBufferObject>(layerCount);
  constraintBufferObject = std::make_shared<ConstraintBufferObject>();
  managers = std::make_shared<Graphics::Managers>();
}

Scene::~Scene()
{
  nodes->clear();
  qInfo() << "Destructor of Scene"
          << "Remaining managers instances" << managers.use_count();
}

void Scene::initialize()
{
  glAssert(gl->glClearColor(0.9f, 0.9f, 0.8f, 1.0f));

  quad = std::make_shared<Graphics::ScreenQuad>(
      ":shader/pass.vert", ":shader/textureForRenderBuffer.frag");
  screenQuad = std::make_shared<Graphics::ScreenQuad>(
      ":shader/pass.vert", ":shader/combineLayers.frag");
  positionQuad = std::make_shared<Graphics::ScreenQuad>(
      ":shader/pass.vert", ":shader/positionRenderTarget.frag");
  distanceTransformQuad = std::make_shared<Graphics::ScreenQuad>(
      ":shader/pass.vert", ":shader/distanceTransform.frag");
  transparentQuad = std::make_shared<Graphics::ScreenQuad>(
      ":shader/pass.vert", ":shader/transparentOverlay.frag");

  fbo->initialize(gl, width, height);
  picker = std::make_unique<Picker>(fbo, gl, labels);
  picker->resize(width, height);
  constraintBufferObject->initialize(gl, textureMapperManager->getBufferSize(),
                                     textureMapperManager->getBufferSize());
  haBuffer =
      std::make_shared<Graphics::HABuffer>(Eigen::Vector2i(width, height));
  managers->getShaderManager()->initialize(gl, haBuffer);

  managers->getObjectManager()->initialize(gl, 128, 10000000);
  haBuffer->initialize(gl, managers);
  quad->initialize(gl, managers);
  screenQuad->initialize(gl, managers);
  positionQuad->initialize(gl, managers);
  distanceTransformQuad->initialize(gl, managers);
  transparentQuad->initialize(gl, managers);

  managers->getTextureManager()->initialize(gl, true, 8);

  textureMapperManager->createTextureMappersForLayers(fbo->getLayerCount());
  textureMapperManager->resize(width, height);
  textureMapperManager->initialize(gl, fbo, constraintBufferObject);

  auto drawer = std::make_shared<Graphics::BufferDrawer>(
      textureMapperManager->getBufferSize(),
      textureMapperManager->getBufferSize(), gl, managers->getShaderManager());

  labellingCoordinator->initialize(textureMapperManager->getBufferSize(),
                                   drawer, textureMapperManager, width, height);
}

void Scene::cleanup()
{
  labellingCoordinator->cleanup();

  textureMapperManager->cleanup();
}

void Scene::update(double frameTime, QSet<Qt::Key> keysPressed)
{
  auto camera = getCamera();

  if (camera->needsResizing())
    camera->resize(width, height);

  this->frameTime = frameTime;
  cameraControllers->update(camera, frameTime);

  frustumOptimizer.update(camera->getViewMatrix());
  camera->updateNearAndFarPlanes(frustumOptimizer.getNear(),
                                 frustumOptimizer.getFar());
  haBuffer->updateNearAndFarPlanes(frustumOptimizer.getNear(),
                                   frustumOptimizer.getFar());

  labellingCoordinator->update(frameTime, camera->getProjectionMatrix(),
                               camera->getViewMatrix(), activeLayerNumber);
}

void Scene::render()
{
  auto camera = getCamera();

  if (shouldResize)
  {
    camera->resize(width, height);
    fbo->resize(width, height);
    shouldResize = false;
  }

  glAssert(gl->glViewport(0, 0, width, height));
  glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));

  RenderData renderData = createRenderData();

  renderNodesWithHABufferIntoFBO(renderData);

  textureMapperManager->update();

  constraintBufferObject->bind();

  labellingCoordinator->updatePlacement();

  constraintBufferObject->unbind();

  glAssert(gl->glViewport(0, 0, width, height));

  fbo->bind();
  glAssert(gl->glDisable(GL_DEPTH_TEST));
  nodes->renderLabels(gl, managers, renderData);
  fbo->unbind();
  renderScreenQuad();

  if (showConstraintOverlay)
  {
    constraintBufferObject->bindTexture(GL_TEXTURE0);
    renderQuad(transparentQuad, Eigen::Matrix4f::Identity());
  }

  if (showBufferDebuggingViews)
    renderDebuggingViews(renderData);

  glAssert(gl->glEnable(GL_DEPTH_TEST));

}

void Scene::renderNodesWithHABufferIntoFBO(const RenderData &renderData)
{
  fbo->bind();
  glAssert(gl->glViewport(0, 0, width, height));
  glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));

  haBuffer->clearAndPrepare(managers);

  nodes->render(gl, managers, renderData);

  managers->getObjectManager()->render(renderData);

  std::vector<float> zValues = labellingCoordinator->updateClusters();

  haBuffer->setLayerZValues(zValues);
  haBuffer->render(managers, renderData);

  picker->doPick(renderData.viewProjectionMatrix);

  fbo->unbind();
}

void Scene::renderDebuggingViews(const RenderData &renderData)
{
  for (int i = 0; i < fbo->getLayerCount(); ++i)
  {
    fbo->bindColorTexture(i, GL_TEXTURE0);
    auto transformation = Eigen::Affine3f(
        Eigen::Translation3f(Eigen::Vector3f(-0.8 + 0.4 * i, -0.4, 0)) *
        Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
    renderQuad(quad, transformation.matrix());
  }

  for (int i = 0; i < fbo->getLayerCount(); ++i)
  {
    fbo->bindDepthTexture(i, GL_TEXTURE0);
    auto transformation = Eigen::Affine3f(
        Eigen::Translation3f(Eigen::Vector3f(-0.8 + 0.4 * i, 0.8, 0)) *
        Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
    renderQuad(quad, transformation.matrix());
  }

  fbo->bindDepthTexture(GL_TEXTURE0);
  auto transformation =
      Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(-0.8, -0.8, 0)) *
                      Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
  renderQuad(quad, transformation.matrix());

  int layerIndex = activeLayerNumber == 0 ? 0 : activeLayerNumber - 1;
  textureMapperManager->bindOccupancyTexture(layerIndex);
  transformation =
      Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(-0.4, -0.8, 0)) *
                      Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
  renderQuad(quad, transformation.matrix());

  textureMapperManager->bindDistanceTransform(layerIndex);
  transformation =
      Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.0, -0.8, 0)) *
                      Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
  renderQuad(distanceTransformQuad, transformation.matrix());

  textureMapperManager->bindApollonius(layerIndex);
  transformation =
      Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.4, -0.8, 0)) *
                      Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
  renderQuad(quad, transformation.matrix());

  constraintBufferObject->bindTexture(GL_TEXTURE0);
  transformation =
      Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.8, -0.8, 0)) *
                      Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
  renderQuad(quad, transformation.matrix());
}

void Scene::renderQuad(std::shared_ptr<Graphics::ScreenQuad> quad,
                       Eigen::Matrix4f modelMatrix)
{
  RenderData renderData;
  renderData.modelMatrix = modelMatrix;

  quad->getShaderProgram()->bind();
  quad->getShaderProgram()->setUniform("textureSampler", 0);
  quad->renderImmediately(gl, managers, renderData);
}

void Scene::renderScreenQuad()
{
  if (activeLayerNumber == 0)
  {
    fbo->bindColorTexture(0, GL_TEXTURE0);
    fbo->bindColorTexture(1, GL_TEXTURE1);
    fbo->bindColorTexture(2, GL_TEXTURE2);
    fbo->bindColorTexture(3, GL_TEXTURE3);

    screenQuad->getShaderProgram()->setUniform("layer1", 0);
    screenQuad->getShaderProgram()->setUniform("layer2", 1);
    screenQuad->getShaderProgram()->setUniform("layer3", 2);
    screenQuad->getShaderProgram()->setUniform("layer4", 3);
    renderQuad(screenQuad, Eigen::Matrix4f::Identity());

    gl->glActiveTexture(GL_TEXTURE0);
  }
  else
  {
    fbo->bindColorTexture(activeLayerNumber - 1, GL_TEXTURE0);
    renderQuad(quad, Eigen::Matrix4f::Identity());
  }
}

void Scene::resize(int width, int height)
{
  this->width = width;
  this->height = height;

  shouldResize = true;

  labellingCoordinator->resize(width, height);
}

RenderData Scene::createRenderData()
{
  auto camera = getCamera();

  return RenderData(camera->getProjectionMatrix(), camera->getViewMatrix(),
                    camera->getPosition(), Eigen::Vector2f(width, height));
}

void Scene::pick(int id, Eigen::Vector2f position)
{
  if (picker.get())
    picker->pick(id, position);
}

void Scene::enableBufferDebuggingViews(bool enable)
{
  showBufferDebuggingViews = enable;
}

void Scene::enableConstraingOverlay(bool enable)
{
  showConstraintOverlay = enable;
}

std::shared_ptr<Camera> Scene::getCamera()
{
  return nodes->getCameraNode()->getCamera();
}

void Scene::setRenderLayer(int layerNumber)
{
  activeLayerNumber = layerNumber;
}

<|endoftext|>


<commit_before>#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <cmath>
#include <memory>
#include <limits>

#include "scene.hpp"
#include "light.hpp"

using std::vector;
using std::auto_ptr;

/*
 * In the case of an empty constructor, Scene will generate a predefined
 * scene for rendering.
 */
Scene::Scene() : shapes(vector<Shape*>()),
                 lights(vector<LightSource*>()),
                 ambient(Color(0.25, 0.25, 0.25)),
                 camera(Camera())
{
    //floor
    shapes.push_back(new Plane(Point(0, -3, 0), Vector(0, 1, 0), Color(0, 1, 0), 1, 0.5, 0.5, 0.5));

    //back wall
    //shapes.push_back(new Plane(Point(0, 0, 20), Vector(0, 0, -1), Color(1, 1, 0), 1, 0.5, 0.5, 0.5));

    //left side wall
    //shapes.push_back(new Plane(Point(-3, 0, 0), Vector(1, 0, 0), Color(0, 1, 1), 1, 0.5, 0.5, 0.5));

    //right sphere (red)
    shapes.push_back(new Sphere(Point(3, -1, 5), 2,
                Color(1, 0, 0), 1, 0.9, 0.5, 0.5));

    //left sphere (blue)
    shapes.push_back(new Sphere(Point(-1, 2, 5), 1,
                Color(0, 0, 1), 1, 0.3, 0.5, 0.5));

    //light source 1
    //lights.push_back(new PointLight(Color(1, 1, 1), Point(0, .001, 2)));

    //light source 2
    lights.push_back(new PointLight(Color(1, 1, 1), Point(0, 5, 0)));
}

Scene::Scene(std::string fileName): shapes(vector<Shape*>()),
                                    lights(vector<LightSource*>()),
                                    ambient(Color(0.25, 0.25, 0.25)),
                                    camera(Camera()) {
    std::ifstream input_scene (fileName.c_str());
    // Read the file and add specified shapes.
    // We need to figure out what our syntax/grammar is first though.
}

Color Scene::raytrace(const Ray& camera_ray) const {
    const Shape *nearest_shape = NULL;
    float nearest_distance2 = std::numeric_limits<float>::max();
    Ray nearest_hit;
    for (vector<Shape*>::const_iterator it = shapes.begin(); it != shapes.end(); it++) {
        const Shape *shape = *it;
        auto_ptr<Ray> intersection(shape->getIntersection(camera_ray));
        if (intersection.get() == NULL) // Didn't hit this shape
            continue;
        float int_distance2 = Ray::makeRay(camera_ray.getOrigin(),
                intersection->getOrigin()).getDir().magnitude2();
        if (int_distance2 < nearest_distance2) {
            // Found a closer hit
            nearest_shape = shape;
            nearest_distance2 = int_distance2;
            nearest_hit = *intersection;
        }
    }
    if (nearest_shape == NULL) {
        // Didn't hit anything
        return Color(1, 0, 1); // Magenta
    } else {
        return shade(nearest_shape, nearest_hit);
    }
}

Color Scene::shade(const Shape *obj, Ray hit) const{
    /*
    if(hit.getDir().i==0 && hit.getDir().j==1 && hit.getDir().k==0){
        std::cout << hit.getOrigin().x << "\n";
        hit.getOrigin().x << ", " << hit.getOrigin().y << ", " << hit.getOrigin() << "\n";
        //return obj->getColor();

    }
    */
    for(vector<LightSource*>::const_iterator it = lights.begin(); it != lights.end(); it++) {
        LightSource *light = *it;
        Ray shadow = Ray::makeRay(hit.getOrigin(), light->getPoint());
        Color result = Color(ambient) * obj->getAmbientCoefficient();
        bool collision = false;
        // Detect collisions, for now do nothing if there is a collision
        for(vector<Shape*>::const_iterator sh = shapes.begin(); sh != shapes.end(); sh++) {
            Shape *shape = *sh;
            if (shape != obj){
                auto_ptr<Ray> hit(shape->getIntersection(shadow));
                if (hit.get() != NULL && hit->getOrigin() != shadow.getOrigin()) {
                    Vector toHit(hit->getOrigin().x-shadow.getOrigin().x,
                        hit->getOrigin().y-shadow.getOrigin().y,
                        hit->getOrigin().z-shadow.getOrigin().z);
                    if(fabs(toHit.i) <= fabs(shadow.getDir().i) &&
                        fabs(toHit.j) <= fabs(shadow.getDir().j) &&
                        fabs(toHit.k) <= fabs(shadow.getDir().k)){
                        collision = true;
                        break;
                    }
                }
            }
        }
        // Calculate local illumination
        if(!collision) {
            // Normalize the direction vectors before calculations
            shadow.normalize();
            hit.normalize();

            float cos_theta = (shadow.getDir()).dotProduct(hit.getDir());
            /*
            if(!(hit.getDir().i==0 && hit.getDir().j==1 && hit.getDir().k==0)){
                //zprint:Vector(hit.getDir());
                std::cout<< hit.getDir().i << ",";
                std::cout<< hit.getDir().j << ",";
                std::cout<< hit.getDir().k << "\n";
            }
            */
            if(cos_theta < 0)
                cos_theta = 0;
            /*
            if(hit.getDir().i==0 && hit.getDir().j==1 && hit.getDir().k==0){
                std::cout<<cos_theta;
            }
            */
            Color diffuse = cos_theta * obj->getDiffuseCoefficient()
                * light->getColor();
            result = result + diffuse;
        }/*
        if(hit.getDir().i==0 && hit.getDir().j==1 && hit.getDir().k==0){

            std::cout<< result.red << ",";
            std::cout<< result.blue << ",";
            std::cout<< result.green << "\n";

        }*/
        result = result * obj->getColor();
        return result;
    }
}
Scene::~Scene() {
    for(vector<Shape*>::iterator it = shapes.begin(); it != shapes.end(); it++) {
        delete *it;
    }
    for(vector<LightSource*>::iterator it = lights.begin(); it != lights.end(); it++) {
        delete *it;
    }
}

Ray Scene::get_camera_ray(float x, float y) const {
    return camera.get_ray(x, -y);
}
class print{
    static void Vector(Vector v){
        std::cout<< v.i << ",";
        std::cout<< v.j << ",";
        std::cout<< v.k << "\n";
    }
};
<commit_msg>uncommented side and back wall in the scene constructor<commit_after>#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <cmath>
#include <memory>
#include <limits>

#include "scene.hpp"
#include "light.hpp"

using std::vector;
using std::auto_ptr;

/*
 * In the case of an empty constructor, Scene will generate a predefined
 * scene for rendering.
 */
Scene::Scene() : shapes(vector<Shape*>()),
                 lights(vector<LightSource*>()),
                 ambient(Color(0.25, 0.25, 0.25)),
                 camera(Camera())
{
    //floor
    shapes.push_back(new Plane(Point(0, -3, 0), Vector(0, 1, 0), Color(0, 1, 0), 1, 0.5, 0.5, 0.5));

    //back wall
    shapes.push_back(new Plane(Point(0, 0, 15), Vector(0, 0, -1), Color(1, 1, 0), 1, 0.5, 0.5, 0.5));

    //left side wall
    shapes.push_back(new Plane(Point(-3, 0, 0), Vector(1, 0, 0), Color(0, 1, 1), 1, 0.5, 0.5, 0.5));

    //right sphere (red)
    shapes.push_back(new Sphere(Point(3, -1, 5), 2,
                Color(1, 0, 0), 1, 0.9, 0.5, 0.5));

    //left sphere (blue)
    shapes.push_back(new Sphere(Point(-1, 2, 5), 1,
                Color(0, 0, 1), 1, 0.3, 0.5, 0.5));

    //light source 1
    //lights.push_back(new PointLight(Color(1, 1, 1), Point(0, .001, 2)));

    //light source 2
    lights.push_back(new PointLight(Color(1, 1, 1), Point(0, 5, 0)));
}

Scene::Scene(std::string fileName): shapes(vector<Shape*>()),
                                    lights(vector<LightSource*>()),
                                    ambient(Color(0.25, 0.25, 0.25)),
                                    camera(Camera()) {
    std::ifstream input_scene (fileName.c_str());
    // Read the file and add specified shapes.
    // We need to figure out what our syntax/grammar is first though.
}

Color Scene::raytrace(const Ray& camera_ray) const {
    const Shape *nearest_shape = NULL;
    float nearest_distance2 = std::numeric_limits<float>::max();
    Ray nearest_hit;
    for (vector<Shape*>::const_iterator it = shapes.begin(); it != shapes.end(); it++) {
        const Shape *shape = *it;
        auto_ptr<Ray> intersection(shape->getIntersection(camera_ray));
        if (intersection.get() == NULL) // Didn't hit this shape
            continue;
        float int_distance2 = Ray::makeRay(camera_ray.getOrigin(),
                intersection->getOrigin()).getDir().magnitude2();
        if (int_distance2 < nearest_distance2) {
            // Found a closer hit
            nearest_shape = shape;
            nearest_distance2 = int_distance2;
            nearest_hit = *intersection;
        }
    }
    if (nearest_shape == NULL) {
        // Didn't hit anything
        return Color(1, 0, 1); // Magenta
    } else {
        return shade(nearest_shape, nearest_hit);
    }
}

Color Scene::shade(const Shape *obj, Ray hit) const{
    /*
    if(hit.getDir().i==0 && hit.getDir().j==1 && hit.getDir().k==0){
        std::cout << hit.getOrigin().x << "\n";
        hit.getOrigin().x << ", " << hit.getOrigin().y << ", " << hit.getOrigin() << "\n";
        //return obj->getColor();

    }
    */
    for(vector<LightSource*>::const_iterator it = lights.begin(); it != lights.end(); it++) {
        LightSource *light = *it;
        Ray shadow = Ray::makeRay(hit.getOrigin(), light->getPoint());
        Color result = Color(ambient) * obj->getAmbientCoefficient();
        bool collision = false;
        // Detect collisions, for now do nothing if there is a collision
        for(vector<Shape*>::const_iterator sh = shapes.begin(); sh != shapes.end(); sh++) {
            Shape *shape = *sh;
            if (shape != obj){
                auto_ptr<Ray> hit(shape->getIntersection(shadow));
                if (hit.get() != NULL && hit->getOrigin() != shadow.getOrigin()) {
                    Vector toHit(hit->getOrigin().x-shadow.getOrigin().x,
                        hit->getOrigin().y-shadow.getOrigin().y,
                        hit->getOrigin().z-shadow.getOrigin().z);
                    if(fabs(toHit.i) <= fabs(shadow.getDir().i) &&
                        fabs(toHit.j) <= fabs(shadow.getDir().j) &&
                        fabs(toHit.k) <= fabs(shadow.getDir().k)){
                        collision = true;
                        break;
                    }
                }
            }
        }
        // Calculate local illumination
        if(!collision) {
            // Normalize the direction vectors before calculations
            shadow.normalize();
            hit.normalize();

            float cos_theta = (shadow.getDir()).dotProduct(hit.getDir());
            /*
            if(!(hit.getDir().i==0 && hit.getDir().j==1 && hit.getDir().k==0)){
                //zprint:Vector(hit.getDir());
                std::cout<< hit.getDir().i << ",";
                std::cout<< hit.getDir().j << ",";
                std::cout<< hit.getDir().k << "\n";
            }
            */
            if(cos_theta < 0)
                cos_theta = 0;
            /*
            if(hit.getDir().i==0 && hit.getDir().j==1 && hit.getDir().k==0){
                std::cout<<cos_theta;
            }
            */
            Color diffuse = cos_theta * obj->getDiffuseCoefficient()
                * light->getColor();
            result = result + diffuse;
        }/*
        if(hit.getDir().i==0 && hit.getDir().j==1 && hit.getDir().k==0){

            std::cout<< result.red << ",";
            std::cout<< result.blue << ",";
            std::cout<< result.green << "\n";

        }*/
        result = result * obj->getColor();
        return result;
    }
}
Scene::~Scene() {
    for(vector<Shape*>::iterator it = shapes.begin(); it != shapes.end(); it++) {
        delete *it;
    }
    for(vector<LightSource*>::iterator it = lights.begin(); it != lights.end(); it++) {
        delete *it;
    }
}

Ray Scene::get_camera_ray(float x, float y) const {
    return camera.get_ray(x, -y);
}
class print{
    static void Vector(Vector v){
        std::cout<< v.i << ",";
        std::cout<< v.j << ",";
        std::cout<< v.k << "\n";
    }
};
<|endoftext|>


<commit_before>// Copyright (c) 2014 Eugene Zhuk.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.

#include "spawn/spawn.h"

extern char ** environ;

int spawn(std::string const & path)
{
    pid_t pid = 0;
    char * argv[] = {
        const_cast<char *>(path.c_str()),
        nullptr
    };

    return posix_spawn(&pid, path.c_str(), nullptr, nullptr, argv, environ);
}
<commit_msg>Provide direct access to environ on OS X.<commit_after>// Copyright (c) 2014 Eugene Zhuk.
// Use of this source code is governed by the MIT license that can be found
// in the LICENSE file.

#include "spawn/spawn.h"

#if defined(__APPLE__)
// On OS X shared libraries and bundles don't have direct access to environ,
// which is only available to ld(1) when a complete program is being linked.
// Although the environment routines are still available, the _NSGetEnviron()
// function needs to be used if direct access to environ is required.
#include <crt_externs.h>
char ** getenviron(void) { return * _NSGetEnviron(); }
#else
extern "C" char ** environ;
char ** getenviron(void) { return environ; }
#endif

int spawn(std::string const & path)
{
    pid_t pid = 0;
    char * argv[] = {
        const_cast<char *>(path.c_str()),
        nullptr
    };

    return posix_spawn(&pid, path.c_str(), nullptr, nullptr, argv,
        getenviron());
}
<|endoftext|>


<commit_before>

#include "sync.h"
#include "net.h"
#include "key.h"
#include "util.h"
#include "base58.h"
#include "protocol.h"
#include "spork.h"
#include "main.h"
#include "masternode-budget.h"
#include <boost/lexical_cast.hpp>

using namespace std;
using namespace boost;

class CSporkMessage;
class CSporkManager;

CSporkManager sporkManager;

std::map<uint256, CSporkMessage> mapSporks;
std::map<int, CSporkMessage> mapSporksActive;

void ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
    if(fLiteMode) return; //disable all darksend/masternode related functionality

    if (strCommand == "spork")
    {
        //LogPrintf("ProcessSpork::spork\n");
        CDataStream vMsg(vRecv);
        CSporkMessage spork;
        vRecv >> spork;

        if(chainActive.Tip() == NULL) return;

        uint256 hash = spork.GetHash();
        if(mapSporksActive.count(spork.nSporkID)) {
            if(mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned){
                if(fDebug) LogPrintf("spork - seen %s block %d \n", hash.ToString(), chainActive.Tip()->nHeight);
                return;
            } else {
                if(fDebug) LogPrintf("spork - got updated spork %s block %d \n", hash.ToString(), chainActive.Tip()->nHeight);
            }
        }

        LogPrintf("spork - new %s ID %d Time %d bestHeight %d\n", hash.ToString(), spork.nSporkID, spork.nValue, chainActive.Tip()->nHeight);

        if(!sporkManager.CheckSignature(spork)){
            LogPrintf("spork - invalid signature\n");
            Misbehaving(pfrom->GetId(), 100);
            return;
        }

        mapSporks[hash] = spork;
        mapSporksActive[spork.nSporkID] = spork;
        sporkManager.Relay(spork);

        //does a task if needed
        ExecuteSpork(spork.nSporkID, spork.nValue);
    }
    if (strCommand == "getsporks")
    {
        std::map<int, CSporkMessage>::iterator it = mapSporksActive.begin();

        while(it != mapSporksActive.end()) {
            pfrom->PushMessage("spork", it->second);
            it++;
        }
    }

}

// grab the spork, otherwise say it's off
bool IsSporkActive(int nSporkID)
{
    int64_t r = -1;

    if(mapSporksActive.count(nSporkID)){
        r = mapSporksActive[nSporkID].nValue;
    } else {
        if(nSporkID == SPORK_2_INSTANTX) r = SPORK_2_INSTANTX_DEFAULT;
        if(nSporkID == SPORK_3_INSTANTX_BLOCK_FILTERING) r = SPORK_3_INSTANTX_BLOCK_FILTERING_DEFAULT;
        if(nSporkID == SPORK_5_MAX_VALUE) r = SPORK_5_MAX_VALUE_DEFAULT;
        if(nSporkID == SPORK_7_MASTERNODE_SCANNING) r = SPORK_7_MASTERNODE_SCANNING_DEFAULT;
        if(nSporkID == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT;
        if(nSporkID == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) r = SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT;
        if(nSporkID == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT;
        if(nSporkID == SPORK_11_RESET_BUDGET) r = SPORK_11_RESET_BUDGET_DEFAULT;
        if(nSporkID == SPORK_12_RECONSIDER_BLOCKS) r = SPORK_12_RECONSIDER_BLOCKS_DEFAULT;
        if(nSporkID == SPORK_13_ENABLE_SUPERBLOCKS) r = SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT;

        if(r == -1) LogPrintf("GetSpork::Unknown Spork %d\n", nSporkID);
    }
    if(r == -1) r = 4070908800; //return 2099-1-1 by default

    return r < GetTime();
}

// grab the value of the spork on the network, or the default
int GetSporkValue(int nSporkID)
{
    int r = 0;

    if(mapSporksActive.count(nSporkID)){
        r = mapSporksActive[nSporkID].nValue;
    } else {
        if(nSporkID == SPORK_2_INSTANTX) r = SPORK_2_INSTANTX_DEFAULT;
        if(nSporkID == SPORK_3_INSTANTX_BLOCK_FILTERING) r = SPORK_3_INSTANTX_BLOCK_FILTERING_DEFAULT;
        if(nSporkID == SPORK_5_MAX_VALUE) r = SPORK_5_MAX_VALUE_DEFAULT;
        if(nSporkID == SPORK_7_MASTERNODE_SCANNING) r = SPORK_7_MASTERNODE_SCANNING_DEFAULT;
        if(nSporkID == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT;
        if(nSporkID == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) r = SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT;
        if(nSporkID == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT;
        if(nSporkID == SPORK_11_RESET_BUDGET) r = SPORK_11_RESET_BUDGET_DEFAULT;
        if(nSporkID == SPORK_12_RECONSIDER_BLOCKS) r = SPORK_12_RECONSIDER_BLOCKS_DEFAULT;
        if(nSporkID == SPORK_13_ENABLE_SUPERBLOCKS) r = SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT;

        if(r == 0) LogPrintf("GetSpork::Unknown Spork %d\n", nSporkID);
    }

    return r;
}

void ExecuteSpork(int nSporkID, int nValue)
{
    if(nSporkID == SPORK_11_RESET_BUDGET && nValue == 1){
        budget.Clear();
    }

    //correct fork via spork technology
    if(nSporkID == SPORK_12_RECONSIDER_BLOCKS && nValue > 0) {
        LogPrintf("Spork::ExecuteSpork -- Reconcider Last %d Blocks\n", nValue);

        CValidationState state;
        {
            LOCK(cs_main);

            DisconnectBlocksAndReprocess(nValue);
        }

        if (state.IsValid()) {
            ActivateBestChain(state);
        }
    }
}

bool CSporkManager::CheckSignature(CSporkMessage& spork)
{
    //note: need to investigate why this is failing
    std::string strMessage = boost::lexical_cast<std::string>(spork.nSporkID) + boost::lexical_cast<std::string>(spork.nValue) + boost::lexical_cast<std::string>(spork.nTimeSigned);
    CPubKey pubkey(ParseHex(Params().SporkKey()));

    std::string errorMessage = "";
    if(!darkSendSigner.VerifyMessage(pubkey, spork.vchSig, strMessage, errorMessage)){
        return false;
    }

    return true;
}

bool CSporkManager::Sign(CSporkMessage& spork)
{
    std::string strMessage = boost::lexical_cast<std::string>(spork.nSporkID) + boost::lexical_cast<std::string>(spork.nValue) + boost::lexical_cast<std::string>(spork.nTimeSigned);

    CKey key2;
    CPubKey pubkey2;
    std::string errorMessage = "";

    if(!darkSendSigner.SetKey(strMasterPrivKey, errorMessage, key2, pubkey2))
    {
        LogPrintf("CMasternodePayments::Sign - ERROR: Invalid masternodeprivkey: '%s'\n", errorMessage);
        return false;
    }

    if(!darkSendSigner.SignMessage(strMessage, errorMessage, spork.vchSig, key2)) {
        LogPrintf("CMasternodePayments::Sign - Sign message failed");
        return false;
    }

    if(!darkSendSigner.VerifyMessage(pubkey2, spork.vchSig, strMessage, errorMessage)) {
        LogPrintf("CMasternodePayments::Sign - Verify message failed");
        return false;
    }

    return true;
}

bool CSporkManager::UpdateSpork(int nSporkID, int64_t nValue)
{

    CSporkMessage msg;
    msg.nSporkID = nSporkID;
    msg.nValue = nValue;
    msg.nTimeSigned = GetTime();

    if(Sign(msg)){
        Relay(msg);
        mapSporks[msg.GetHash()] = msg;
        mapSporksActive[nSporkID] = msg;
        return true;
    }

    return false;
}

void CSporkManager::Relay(CSporkMessage& msg)
{
    CInv inv(MSG_SPORK, msg.GetHash());
    RelayInv(inv);
}

bool CSporkManager::SetPrivKey(std::string strPrivKey)
{
    CSporkMessage msg;

    // Test signing successful, proceed
    strMasterPrivKey = strPrivKey;

    Sign(msg);

    if(CheckSignature(msg)){
        LogPrintf("CSporkManager::SetPrivKey - Successfully initialized as spork signer\n");
        return true;
    } else {
        return false;
    }
}

int CSporkManager::GetSporkIDByName(std::string strName)
{
    if(strName == "SPORK_2_INSTANTX") return SPORK_2_INSTANTX;
    if(strName == "SPORK_3_INSTANTX_BLOCK_FILTERING") return SPORK_3_INSTANTX_BLOCK_FILTERING;
    if(strName == "SPORK_5_MAX_VALUE") return SPORK_5_MAX_VALUE;
    if(strName == "SPORK_7_MASTERNODE_SCANNING") return SPORK_7_MASTERNODE_SCANNING;
    if(strName == "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT") return SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT;
    if(strName == "SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT") return SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT;
    if(strName == "SPORK_10_MASTERNODE_PAY_UPDATED_NODES") return SPORK_10_MASTERNODE_PAY_UPDATED_NODES;
    if(strName == "SPORK_11_RESET_BUDGET") return SPORK_11_RESET_BUDGET;
    if(strName == "SPORK_12_RECONSIDER_BLOCKS") return SPORK_12_RECONSIDER_BLOCKS;
    if(strName == "SPORK_13_ENABLE_SUPERBLOCKS") return SPORK_13_ENABLE_SUPERBLOCKS;

    return -1;
}

std::string CSporkManager::GetSporkNameByID(int id)
{
    if(id == SPORK_2_INSTANTX) return "SPORK_2_INSTANTX";
    if(id == SPORK_3_INSTANTX_BLOCK_FILTERING) return "SPORK_3_INSTANTX_BLOCK_FILTERING";
    if(id == SPORK_5_MAX_VALUE) return "SPORK_5_MAX_VALUE";
    if(id == SPORK_7_MASTERNODE_SCANNING) return "SPORK_7_MASTERNODE_SCANNING";
    if(id == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) return "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT";
    if(id == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) return "SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT";
    if(id == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) return "SPORK_10_MASTERNODE_PAY_UPDATED_NODES";
    if(id == SPORK_11_RESET_BUDGET) return "SPORK_11_RESET_BUDGET";
    if(id == SPORK_12_RECONSIDER_BLOCKS) return "SPORK_12_RECONSIDER_BLOCKS";
    if(id == SPORK_13_ENABLE_SUPERBLOCKS) return "SPORK_13_ENABLE_SUPERBLOCKS";

    return "Unknown";
}
<commit_msg>Reprocess before disconnect for rescan<commit_after>

#include "sync.h"
#include "net.h"
#include "key.h"
#include "util.h"
#include "base58.h"
#include "protocol.h"
#include "spork.h"
#include "main.h"
#include "masternode-budget.h"
#include <boost/lexical_cast.hpp>

using namespace std;
using namespace boost;

class CSporkMessage;
class CSporkManager;

CSporkManager sporkManager;

std::map<uint256, CSporkMessage> mapSporks;
std::map<int, CSporkMessage> mapSporksActive;

void ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
    if(fLiteMode) return; //disable all darksend/masternode related functionality

    if (strCommand == "spork")
    {
        //LogPrintf("ProcessSpork::spork\n");
        CDataStream vMsg(vRecv);
        CSporkMessage spork;
        vRecv >> spork;

        if(chainActive.Tip() == NULL) return;

        uint256 hash = spork.GetHash();
        if(mapSporksActive.count(spork.nSporkID)) {
            if(mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned){
                if(fDebug) LogPrintf("spork - seen %s block %d \n", hash.ToString(), chainActive.Tip()->nHeight);
                return;
            } else {
                if(fDebug) LogPrintf("spork - got updated spork %s block %d \n", hash.ToString(), chainActive.Tip()->nHeight);
            }
        }

        LogPrintf("spork - new %s ID %d Time %d bestHeight %d\n", hash.ToString(), spork.nSporkID, spork.nValue, chainActive.Tip()->nHeight);

        if(!sporkManager.CheckSignature(spork)){
            LogPrintf("spork - invalid signature\n");
            Misbehaving(pfrom->GetId(), 100);
            return;
        }

        mapSporks[hash] = spork;
        mapSporksActive[spork.nSporkID] = spork;
        sporkManager.Relay(spork);

        //does a task if needed
        ExecuteSpork(spork.nSporkID, spork.nValue);
    }
    if (strCommand == "getsporks")
    {
        std::map<int, CSporkMessage>::iterator it = mapSporksActive.begin();

        while(it != mapSporksActive.end()) {
            pfrom->PushMessage("spork", it->second);
            it++;
        }
    }

}

// grab the spork, otherwise say it's off
bool IsSporkActive(int nSporkID)
{
    int64_t r = -1;

    if(mapSporksActive.count(nSporkID)){
        r = mapSporksActive[nSporkID].nValue;
    } else {
        if(nSporkID == SPORK_2_INSTANTX) r = SPORK_2_INSTANTX_DEFAULT;
        if(nSporkID == SPORK_3_INSTANTX_BLOCK_FILTERING) r = SPORK_3_INSTANTX_BLOCK_FILTERING_DEFAULT;
        if(nSporkID == SPORK_5_MAX_VALUE) r = SPORK_5_MAX_VALUE_DEFAULT;
        if(nSporkID == SPORK_7_MASTERNODE_SCANNING) r = SPORK_7_MASTERNODE_SCANNING_DEFAULT;
        if(nSporkID == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT;
        if(nSporkID == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) r = SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT;
        if(nSporkID == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT;
        if(nSporkID == SPORK_11_RESET_BUDGET) r = SPORK_11_RESET_BUDGET_DEFAULT;
        if(nSporkID == SPORK_12_RECONSIDER_BLOCKS) r = SPORK_12_RECONSIDER_BLOCKS_DEFAULT;
        if(nSporkID == SPORK_13_ENABLE_SUPERBLOCKS) r = SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT;

        if(r == -1) LogPrintf("GetSpork::Unknown Spork %d\n", nSporkID);
    }
    if(r == -1) r = 4070908800; //return 2099-1-1 by default

    return r < GetTime();
}

// grab the value of the spork on the network, or the default
int GetSporkValue(int nSporkID)
{
    int r = 0;

    if(mapSporksActive.count(nSporkID)){
        r = mapSporksActive[nSporkID].nValue;
    } else {
        if(nSporkID == SPORK_2_INSTANTX) r = SPORK_2_INSTANTX_DEFAULT;
        if(nSporkID == SPORK_3_INSTANTX_BLOCK_FILTERING) r = SPORK_3_INSTANTX_BLOCK_FILTERING_DEFAULT;
        if(nSporkID == SPORK_5_MAX_VALUE) r = SPORK_5_MAX_VALUE_DEFAULT;
        if(nSporkID == SPORK_7_MASTERNODE_SCANNING) r = SPORK_7_MASTERNODE_SCANNING_DEFAULT;
        if(nSporkID == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT;
        if(nSporkID == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) r = SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT;
        if(nSporkID == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT;
        if(nSporkID == SPORK_11_RESET_BUDGET) r = SPORK_11_RESET_BUDGET_DEFAULT;
        if(nSporkID == SPORK_12_RECONSIDER_BLOCKS) r = SPORK_12_RECONSIDER_BLOCKS_DEFAULT;
        if(nSporkID == SPORK_13_ENABLE_SUPERBLOCKS) r = SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT;

        if(r == 0) LogPrintf("GetSpork::Unknown Spork %d\n", nSporkID);
    }

    return r;
}

void ExecuteSpork(int nSporkID, int nValue)
{
    if(nSporkID == SPORK_11_RESET_BUDGET && nValue == 1){
        budget.Clear();
    }

    //correct fork via spork technology
    if(nSporkID == SPORK_12_RECONSIDER_BLOCKS && nValue > 0) {
        LogPrintf("Spork::ExecuteSpork -- Reconcider Last %d Blocks\n", nValue);

        CBlockIndex* pindexPrev = chainActive.Tip();
        int count = 0;

        for (unsigned int i = 1; pindexPrev && pindexPrev->nHeight > 0; i++) {
            count++;
            if(count >= nValue) return;

            CValidationState state;
            {
                LOCK(cs_main);

                LogPrintf("Spork::ExecuteSpork -- Reconcider %s\n", pindexPrev->phashBlock->ToString());
                ReconsiderBlock(state, pindexPrev);
            }

            if (pindexPrev->pprev == NULL) { assert(pindexPrev); break; }
            pindexPrev = pindexPrev->pprev;
        }

        CValidationState state;
        {
            LOCK(cs_main);

            DisconnectBlocksAndReprocess(nValue);
        }

        if (state.IsValid()) {
            ActivateBestChain(state);
        }
    }
}

bool CSporkManager::CheckSignature(CSporkMessage& spork)
{
    //note: need to investigate why this is failing
    std::string strMessage = boost::lexical_cast<std::string>(spork.nSporkID) + boost::lexical_cast<std::string>(spork.nValue) + boost::lexical_cast<std::string>(spork.nTimeSigned);
    CPubKey pubkey(ParseHex(Params().SporkKey()));

    std::string errorMessage = "";
    if(!darkSendSigner.VerifyMessage(pubkey, spork.vchSig, strMessage, errorMessage)){
        return false;
    }

    return true;
}

bool CSporkManager::Sign(CSporkMessage& spork)
{
    std::string strMessage = boost::lexical_cast<std::string>(spork.nSporkID) + boost::lexical_cast<std::string>(spork.nValue) + boost::lexical_cast<std::string>(spork.nTimeSigned);

    CKey key2;
    CPubKey pubkey2;
    std::string errorMessage = "";

    if(!darkSendSigner.SetKey(strMasterPrivKey, errorMessage, key2, pubkey2))
    {
        LogPrintf("CMasternodePayments::Sign - ERROR: Invalid masternodeprivkey: '%s'\n", errorMessage);
        return false;
    }

    if(!darkSendSigner.SignMessage(strMessage, errorMessage, spork.vchSig, key2)) {
        LogPrintf("CMasternodePayments::Sign - Sign message failed");
        return false;
    }

    if(!darkSendSigner.VerifyMessage(pubkey2, spork.vchSig, strMessage, errorMessage)) {
        LogPrintf("CMasternodePayments::Sign - Verify message failed");
        return false;
    }

    return true;
}

bool CSporkManager::UpdateSpork(int nSporkID, int64_t nValue)
{

    CSporkMessage msg;
    msg.nSporkID = nSporkID;
    msg.nValue = nValue;
    msg.nTimeSigned = GetTime();

    if(Sign(msg)){
        Relay(msg);
        mapSporks[msg.GetHash()] = msg;
        mapSporksActive[nSporkID] = msg;
        return true;
    }

    return false;
}

void CSporkManager::Relay(CSporkMessage& msg)
{
    CInv inv(MSG_SPORK, msg.GetHash());
    RelayInv(inv);
}

bool CSporkManager::SetPrivKey(std::string strPrivKey)
{
    CSporkMessage msg;

    // Test signing successful, proceed
    strMasterPrivKey = strPrivKey;

    Sign(msg);

    if(CheckSignature(msg)){
        LogPrintf("CSporkManager::SetPrivKey - Successfully initialized as spork signer\n");
        return true;
    } else {
        return false;
    }
}

int CSporkManager::GetSporkIDByName(std::string strName)
{
    if(strName == "SPORK_2_INSTANTX") return SPORK_2_INSTANTX;
    if(strName == "SPORK_3_INSTANTX_BLOCK_FILTERING") return SPORK_3_INSTANTX_BLOCK_FILTERING;
    if(strName == "SPORK_5_MAX_VALUE") return SPORK_5_MAX_VALUE;
    if(strName == "SPORK_7_MASTERNODE_SCANNING") return SPORK_7_MASTERNODE_SCANNING;
    if(strName == "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT") return SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT;
    if(strName == "SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT") return SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT;
    if(strName == "SPORK_10_MASTERNODE_PAY_UPDATED_NODES") return SPORK_10_MASTERNODE_PAY_UPDATED_NODES;
    if(strName == "SPORK_11_RESET_BUDGET") return SPORK_11_RESET_BUDGET;
    if(strName == "SPORK_12_RECONSIDER_BLOCKS") return SPORK_12_RECONSIDER_BLOCKS;
    if(strName == "SPORK_13_ENABLE_SUPERBLOCKS") return SPORK_13_ENABLE_SUPERBLOCKS;

    return -1;
}

std::string CSporkManager::GetSporkNameByID(int id)
{
    if(id == SPORK_2_INSTANTX) return "SPORK_2_INSTANTX";
    if(id == SPORK_3_INSTANTX_BLOCK_FILTERING) return "SPORK_3_INSTANTX_BLOCK_FILTERING";
    if(id == SPORK_5_MAX_VALUE) return "SPORK_5_MAX_VALUE";
    if(id == SPORK_7_MASTERNODE_SCANNING) return "SPORK_7_MASTERNODE_SCANNING";
    if(id == SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT) return "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT";
    if(id == SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT) return "SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT";
    if(id == SPORK_10_MASTERNODE_PAY_UPDATED_NODES) return "SPORK_10_MASTERNODE_PAY_UPDATED_NODES";
    if(id == SPORK_11_RESET_BUDGET) return "SPORK_11_RESET_BUDGET";
    if(id == SPORK_12_RECONSIDER_BLOCKS) return "SPORK_12_RECONSIDER_BLOCKS";
    if(id == SPORK_13_ENABLE_SUPERBLOCKS) return "SPORK_13_ENABLE_SUPERBLOCKS";

    return "Unknown";
}
<|endoftext|>


<commit_before>#include "dbstore.h"
#include "print.h"
#include "story-branches/story_B.h"
#include "story-branches/story_D.h"
#include "story-branches/story_E.h"
#include "story-branches/story_L.h"
#include "story-branches/story_S.h"
#include "story_item.h"
#include "userin.h"
#include <iostream>
#include <string>
using namespace std;

Database db_s = Database();

void story_join_pirates()
{
    start_story_S();
}
void story_line_guns_blazeing()
{
    start_story_E();
}

void story_line_stealth()
{
    start_story_D();
}

void find_lasergun()
{
    print("\nYou find a laser gun with rechargeable ammo\n", "green");

    db_s.add_to_inventory("Lazer gun");

    if (db_s.do_i_have("Lazer gun")) {
        print("You now have a Lazer gun");
    } else {
        print("You do not have a Lazer gun");
    }
}

void repair_and_take_off()
{
    StoryItem* repairAndTakeOffItem = new StoryItem();

    print("\nYou go back and repair your ship and you're able to go in to orbit, hoping to find your space station.\n ", "green");

    repairAndTakeOffItem->preText = "As you're exiting the atmosphere of the Gem-435-ini, in the distance you see your space station,\nbut there is already a ship docked. As you examine the ship thoroughly you come to the conclusion that\nthis ship is not anyone from Earth, so...";

    repairAndTakeOffItem->preTextColour = "magenta";

    repairAndTakeOffItem->prompt = "Do you:";

    repairAndTakeOffItem->options = {
        "Attempt to dock elsewhere",
        "Leave your ship without docking and use you space suit to board silently",
        "Attempt to contact who ever is aboard"
    };

    int choice = repairAndTakeOffItem->run();

    if (choice == 1) {
        story_line_guns_blazeing();
    } else if (choice == 2) {
        story_line_stealth();
    } else if (choice == 3) {
        story_join_pirates();
    }
}

void scavenge_for_supplies()
{
    StoryItem* scavengeForSuppliesItem = new StoryItem();

    print("You go into the first building and find carefully stashed protein rich molecular bars.", "green");

    scavengeForSuppliesItem->preText = "After looking through other buildings trying to find something to survive you see something hidden behind\nan empty rocket fuel barrel. You move the barrel and see it's a space diagnostics examinator and a fully\nautomatic repair robot kit.\n";

    scavengeForSuppliesItem->preTextColour = "magenta";

    scavengeForSuppliesItem->prompt = "Do you:";

    scavengeForSuppliesItem->options = {
        "Keep looking for supplies",
        "Rush to your ship"
    };

    int choice = scavengeForSuppliesItem->run();

    if (choice == 1) {
        find_lasergun();
        repair_and_take_off();
    }
    if (choice == 2) {
        repair_and_take_off();
    }
}

void shout_for_help()
{
    StoryItem* shoutForHelpItem = new StoryItem();

    shoutForHelpItem->preText = "You yell for help, but there is no response.";

    shoutForHelpItem->preTextColour = "green";

    shoutForHelpItem->prompt = "Do you:";

    shoutForHelpItem->options = {
        "Go back to your ship immediately",
        "Stay for the night",
        "Call again for help"
    };

    int answer = shoutForHelpItem->run();

    if (answer == 1) {
        repair_and_take_off();
    }
    if (answer == 2) {
        print("\nYou stay for the night and in the morning you find yourself on the other end of a gun and you get shot in the head by desert pirates", "red");
    }
    if (answer == 3) {
        print("\nYou yell again but still no response. After a while you hear someone approaching. You go out to see who it is , but you are gunned down by desert pirates", "red");
    }
}

void go_to_the_town()
{
    StoryItem* goToTheTownItem = new StoryItem();

    goToTheTownItem->preText = "You reach the town and see it has been abandoned.\nIt has a scary vibe and looked like it had been under attack at some point.";

    goToTheTownItem->preTextColour = "green";

    goToTheTownItem->prompt = "What do you do?";

    goToTheTownItem->options = {
        "Have a look around quietly ",
        "Go back to your ship ",
        "Shout for help"
    };

    int choice = goToTheTownItem->run();

    if (choice == 1) {
        scavenge_for_supplies();
    } else if (choice == 2) {
        print("\nYou stayed in the wrecked ship for 6 days before you starved to death", "red");
    } else if (choice == 3) {
        shout_for_help();
    }
}

void explore_new_planet()
{
    StoryItem* exploreNewPlanetItem = new StoryItem();

    exploreNewPlanetItem->preText = "You get up and climb the capsule, so that you can examine the terrain around you.\nAfter staring in the distance for a while you spot a small town.";

    exploreNewPlanetItem->preTextColour = "green";

    exploreNewPlanetItem->prompt = "Do you go to the town?:";

    exploreNewPlanetItem->options = {
        "Yes",
        "No"
    };

    int choice = exploreNewPlanetItem->run();

    if (choice == 1) {
        go_to_the_town();
    } else if (choice == 2) {
        print("\nYou stayed in the wrecked ship for 6 days before you starved to death", "red");
    }
}

void start_story()
{
    StoryItem* startItem = new StoryItem();

    startItem->preText = "You wake up in an emergency space ejection capsule with a severe headache and empty stomach.\n"
                         "The last thing you remember was prepairing your space station to maintain orbit around a hostile\n"
                         "planet called Gem-435-ini. You don't remember how you ended up here, so you try to contact your\n"
                         "space station but the coms in the capsule are broken. Left with no food and way to establish contact,\n"
                         "with your crew members, you try to gather your thoughts and figure out how to get back up there.";

    startItem->preTextColour = "magenta";

    startItem->prompt = "What do you do?";

    startItem->options = {
        "Kill yourself", // 1
        "Get up and explore", // 2
        "Stay in the wrecked ship and wait for help" // 3
    };

    int choice = startItem->run();

    if (choice == 1) {
        print("\nYou put a spike on the ground and climb on top of your ship. You jump and while you are falling you see a small town in the distance, but it's too late and you die.", "red");
    } else if (choice == 2) {
        explore_new_planet();
    } else if (choice == 3) {
        print("\nYou stayed in the wrecked ship for 6 days before you starved to death", "red");
    }
}
<commit_msg>Commented story lazer gun method<commit_after>#include "dbstore.h"
#include "print.h"
#include "story-branches/story_B.h"
#include "story-branches/story_D.h"
#include "story-branches/story_E.h"
#include "story-branches/story_L.h"
#include "story-branches/story_S.h"
#include "story_item.h"
#include "userin.h"
#include <iostream>
#include <string>
using namespace std;

Database db_s = Database();

void story_join_pirates()
{
    start_story_S();
}
void story_line_guns_blazeing()
{
    start_story_E();
}

void story_line_stealth()
{
    start_story_D();
}

void find_lasergun()
{
    // Player has found a lazer gun
    print("\nYou find a laser gun with rechargeable ammo\n", "green");

    // Lazer gun is added to the user's inventory via a database method
    db_s.add_to_inventory("Lazer gun");

    // Another method is used to check that there is now a lazer gun in the inventory
    if (db_s.do_i_have("Lazer gun")) {
        print("You now have a Lazer gun");
    } else {
        print("You do not have a Lazer gun");
    }
}

void repair_and_take_off()
{
    StoryItem* repairAndTakeOffItem = new StoryItem();

    print("\nYou go back and repair your ship and you're able to go in to orbit, hoping to find your space station.\n ", "green");

    repairAndTakeOffItem->preText = "As you're exiting the atmosphere of the Gem-435-ini, in the distance you see your space station,\nbut there is already a ship docked. As you examine the ship thoroughly you come to the conclusion that\nthis ship is not anyone from Earth, so...";

    repairAndTakeOffItem->preTextColour = "magenta";

    repairAndTakeOffItem->prompt = "Do you:";

    repairAndTakeOffItem->options = {
        "Attempt to dock elsewhere",
        "Leave your ship without docking and use you space suit to board silently",
        "Attempt to contact who ever is aboard"
    };

    int choice = repairAndTakeOffItem->run();

    if (choice == 1) {
        story_line_guns_blazeing();
    } else if (choice == 2) {
        story_line_stealth();
    } else if (choice == 3) {
        story_join_pirates();
    }
}

void scavenge_for_supplies()
{
    StoryItem* scavengeForSuppliesItem = new StoryItem();

    print("You go into the first building and find carefully stashed protein rich molecular bars.", "green");

    scavengeForSuppliesItem->preText = "After looking through other buildings trying to find something to survive you see something hidden behind\nan empty rocket fuel barrel. You move the barrel and see it's a space diagnostics examinator and a fully\nautomatic repair robot kit.\n";

    scavengeForSuppliesItem->preTextColour = "magenta";

    scavengeForSuppliesItem->prompt = "Do you:";

    scavengeForSuppliesItem->options = {
        "Keep looking for supplies",
        "Rush to your ship"
    };

    int choice = scavengeForSuppliesItem->run();

    if (choice == 1) {
        find_lasergun();
        repair_and_take_off();
    }
    if (choice == 2) {
        repair_and_take_off();
    }
}

void shout_for_help()
{
    StoryItem* shoutForHelpItem = new StoryItem();

    shoutForHelpItem->preText = "You yell for help, but there is no response.";

    shoutForHelpItem->preTextColour = "green";

    shoutForHelpItem->prompt = "Do you:";

    shoutForHelpItem->options = {
        "Go back to your ship immediately",
        "Stay for the night",
        "Call again for help"
    };

    int answer = shoutForHelpItem->run();

    if (answer == 1) {
        repair_and_take_off();
    }
    if (answer == 2) {
        print("\nYou stay for the night and in the morning you find yourself on the other end of a gun and you get shot in the head by desert pirates", "red");
    }
    if (answer == 3) {
        print("\nYou yell again but still no response. After a while you hear someone approaching. You go out to see who it is , but you are gunned down by desert pirates", "red");
    }
}

void go_to_the_town()
{
    StoryItem* goToTheTownItem = new StoryItem();

    goToTheTownItem->preText = "You reach the town and see it has been abandoned.\nIt has a scary vibe and looked like it had been under attack at some point.";

    goToTheTownItem->preTextColour = "green";

    goToTheTownItem->prompt = "What do you do?";

    goToTheTownItem->options = {
        "Have a look around quietly ",
        "Go back to your ship ",
        "Shout for help"
    };

    int choice = goToTheTownItem->run();

    if (choice == 1) {
        scavenge_for_supplies();
    } else if (choice == 2) {
        print("\nYou stayed in the wrecked ship for 6 days before you starved to death", "red");
    } else if (choice == 3) {
        shout_for_help();
    }
}

void explore_new_planet()
{
    StoryItem* exploreNewPlanetItem = new StoryItem();

    exploreNewPlanetItem->preText = "You get up and climb the capsule, so that you can examine the terrain around you.\nAfter staring in the distance for a while you spot a small town.";

    exploreNewPlanetItem->preTextColour = "green";

    exploreNewPlanetItem->prompt = "Do you go to the town?:";

    exploreNewPlanetItem->options = {
        "Yes",
        "No"
    };

    int choice = exploreNewPlanetItem->run();

    if (choice == 1) {
        go_to_the_town();
    } else if (choice == 2) {
        print("\nYou stayed in the wrecked ship for 6 days before you starved to death", "red");
    }
}

void start_story()
{
    StoryItem* startItem = new StoryItem();

    startItem->preText = "You wake up in an emergency space ejection capsule with a severe headache and empty stomach.\n"
                         "The last thing you remember was prepairing your space station to maintain orbit around a hostile\n"
                         "planet called Gem-435-ini. You don't remember how you ended up here, so you try to contact your\n"
                         "space station but the coms in the capsule are broken. Left with no food and way to establish contact,\n"
                         "with your crew members, you try to gather your thoughts and figure out how to get back up there.";

    startItem->preTextColour = "magenta";

    startItem->prompt = "What do you do?";

    startItem->options = {
        "Kill yourself", // 1
        "Get up and explore", // 2
        "Stay in the wrecked ship and wait for help" // 3
    };

    int choice = startItem->run();

    if (choice == 1) {
        print("\nYou put a spike on the ground and climb on top of your ship. You jump and while you are falling you see a small town in the distance, but it's too late and you die.", "red");
    } else if (choice == 2) {
        explore_new_planet();
    } else if (choice == 3) {
        print("\nYou stayed in the wrecked ship for 6 days before you starved to death", "red");
    }
}
<|endoftext|>


<commit_before>// (The MIT License)

// Copyright (c) 2012 Thomas Blobaum <tblobaum@gmail.com>

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

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

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

#include <v8.h>
#include <node.h>
#include <syslog.h>
#include <string>

using namespace std;
using namespace node;
using namespace v8;

extern "C" {

  char title[1024];

  static v8::Handle<v8::Value> open(const v8::Arguments& args) {
    args[0]->ToString()->WriteAscii((char*) &title);
    int facility = args[1]->ToInteger()->Int32Value();
    int log_upto = args[2]->ToInteger()->Int32Value();
    setlogmask(LOG_UPTO(log_upto));
    openlog(title, LOG_PID | LOG_NDELAY, facility);

    return String::New("true");
  }

  static v8::Handle<v8::Value> exit(const v8::Arguments& args) {
    closelog();

    return String::New("true");
  }

  static v8::Handle<v8::Value> log(const v8::Arguments& args) {
    int severity = args[0]->ToInteger()->Int32Value();
    v8::String::Utf8Value message(args[1]->ToString());
    syslog(severity, "%s", *message );

    return String::New("true");
  }

  void init(v8::Handle<v8::Object> target) {
    NODE_SET_METHOD(target, "open", open);
    NODE_SET_METHOD(target, "exit", exit);
    NODE_SET_METHOD(target, "log", log);
  }

}
<commit_msg>Update syslog.cc to work with node 0.10.x<commit_after>// (The MIT License)

// Copyright (c) 2012 Thomas Blobaum <tblobaum@gmail.com>

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

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

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

#include <v8.h>
#include <node.h>
#include <syslog.h>
#include <string>

using namespace std;
using namespace node;
using namespace v8;

extern "C" {

  char title[1024];

  static v8::Handle<v8::Value> open(const v8::Arguments& args) {
    args[0]->ToString()->WriteAscii((char*) &title);
    int facility = args[1]->ToInteger()->Int32Value();
    int log_upto = args[2]->ToInteger()->Int32Value();
    setlogmask(LOG_UPTO(log_upto));
    openlog(title, LOG_PID | LOG_NDELAY, facility);

    return String::New("true");
  }

  static v8::Handle<v8::Value> exit(const v8::Arguments& args) {
    closelog();

    return String::New("true");
  }

  static v8::Handle<v8::Value> log(const v8::Arguments& args) {
    int severity = args[0]->ToInteger()->Int32Value();
    v8::String::Utf8Value message(args[1]->ToString());
    syslog(severity, "%s", *message );

    return String::New("true");
  }

  void init(v8::Handle<v8::Object> target) {
    NODE_SET_METHOD(target, "open", open);
    NODE_SET_METHOD(target, "exit", exit);
    NODE_SET_METHOD(target, "log", log);
  }

  NODE_MODULE(syslog, init)

}
<|endoftext|>