<commit_before>#include "search.h"
#include "evaluate.h"
#include <climits>
#include <array>
#include <cassert>
#include <functional>
#include <iostream> // TEMP

namespace lesschess {

// be careful to avoid overflow from INT_MIN == -INT_MIN
constexpr int INFINITY = INT_MAX - 1;
constexpr int DRAW = 0;
constexpr int CHECKMATE = INFINITY - 1; // TODO: does it matter if it is infinity or not?
constexpr int STALEMATE = DRAW;
constexpr int FIFTY_MOVE_RULE_DRAW = DRAW;

// Number of moves upper bound:
// K -> 8 + 2 castles
// Q -> 27
// R -> 14 x 2 = 28
// N -> 8 x 2 = 16
// P -> (2 moves + 2 captures) x 8 = 32 (same as if all 8 pawns could promote)
// --> 139
//
// Worst worst case is 7 promoted queens => 7 x 27 + 8 x 2 = 394
// 128 is probably safe? 256 is definitely safe since willing to bet the the 7 Qs
// position isn't going to happen -- will either be checkmate or stalemate.

// TODO: what is the maximum number of possible moves in a position?
using Moves = std::vector<Move>; // TODO: change this back to std::array<Move, 256>?

constexpr int MAX_DEPTH = 2;

int negamax(Position& position, int alpha, int beta, int depth, Moves& pv)
{
    // TODO: check if terminal node (mate, stalemate, etc)
    //       not sure if the fastest way to do that is to check if `nmoves == 0`?
    if (depth == 0) {
        int score = evaluate(position);
        return position.white_to_move() ? -score : score;
    }

    // TODO: check for 3-move repetition
    if (position.fifty_move_rule_moves() >= 50) {
        return FIFTY_MOVE_RULE_DRAW;
    }

    int value = -INFINITY;
    Savepos sp;
    Moves moves{256};
    int nmoves = position.generate_legal_moves(&moves[0]);
    if (nmoves == 0) {
        // TODO: cache `checkers` from generate_legal_moves() so we can check if mate or stalemate
        if (position.in_check(position.color_to_move())) {
            return position.white_to_move() ? CHECKMATE : -CHECKMATE;
        } else {
            return STALEMATE;
        }
    }
    assert(nmoves > 0);
    for (int i = 0; i < nmoves; ++i) {
        position.make_move(sp, moves[i]);
        pv.push_back(moves[i]);
        value = std::max(value, negamax(position, /*alpha*/-beta, /*beta*/-alpha, depth - 1, pv));
        pv.pop_back();
        position.undo_move(sp, moves[i]);
        alpha = std::max(alpha, value);
        if (alpha >= beta) {
            break;
        }
    }
    return -value;
}

SearchResult search(Position& position)
{
    int bestmove = -1;
    int bestscore = -INFINITY;
    Savepos sp;
    Moves moves{256};
    int nmoves = position.generate_legal_moves(&moves[0]);
    Moves pv;
    for (int i = 0; i < nmoves; ++i) {
        position.make_move(sp, moves[i]);
        pv.push_back(moves[i]);
        int score = negamax(position, /*alpha*/-INFINITY, /*beta*/INFINITY, /*depth*/MAX_DEPTH, pv);
        position.undo_move(sp, moves[i]);
        pv.pop_back();
        if (score > bestscore) {
            bestscore = score;
            bestmove = i;
        }
    }
    assert(bestmove != -1);
    bestscore = position.white_to_move() ? bestscore : -bestscore;
    return {moves[bestmove], bestscore};
}

} // ~namespace lesschess
<commit_msg>Use array for holding principal variation<commit_after>#include "search.h"
#include "evaluate.h"
#include <climits>
#include <array>
#include <cassert>
#include <functional>
#include <iostream> // TEMP

namespace lesschess {

// be careful to avoid overflow from INT_MIN == -INT_MIN
constexpr int INFINITY = INT_MAX - 1;
constexpr int DRAW = 0;
constexpr int CHECKMATE = INFINITY - 1; // TODO: does it matter if it is infinity or not?
constexpr int STALEMATE = DRAW;
constexpr int FIFTY_MOVE_RULE_DRAW = DRAW;

// Number of moves upper bound:
// K -> 8 + 2 castles
// Q -> 27
// R -> 14 x 2 = 28
// N -> 8 x 2 = 16
// P -> (2 moves + 2 captures) x 8 = 32 (same as if all 8 pawns could promote)
// --> 139
//
// Worst worst case is 7 promoted queens => 7 x 27 + 8 x 2 = 394
// 128 is probably safe? 256 is definitely safe since willing to bet the the 7 Qs
// position isn't going to happen -- will either be checkmate or stalemate.

// TODO: what is the maximum number of possible moves in a position?
using Moves = std::vector<Move>; // TODO: change this back to std::array<Move, 256>?

template <int N>
struct PrimaryVariation {
    void push(Move m) noexcept { assert(count < moves.size()); moves[count++] = m; }
    void pop() noexcept { --count; }
    Move* begin() noexcept { return &moves[0]; }
    Move* end() noexcept { return &moves[count]; }

    std::array<Move, N+1> moves;
    int                   count = 0;
};

constexpr int MAX_DEPTH = 2;
using PV = PrimaryVariation<MAX_DEPTH>;

int negamax(Position& position, int alpha, int beta, int depth, PV& pv)
{
    if (depth == 0) {
        int score = evaluate(position);
        return position.white_to_move() ? -score : score;
    }

    // TODO: check for 3-move repetition
    if (position.fifty_move_rule_moves() >= 50) {
        return FIFTY_MOVE_RULE_DRAW;
    }

    int value = -INFINITY;
    Savepos sp;
    Moves moves{256};
    int nmoves = position.generate_legal_moves(&moves[0]);
    if (nmoves == 0) {
        // TODO: cache `checkers` from generate_legal_moves() so we can check if mate or stalemate
        if (position.in_check(position.color_to_move())) {
            return position.white_to_move() ? CHECKMATE : -CHECKMATE;
        } else {
            return STALEMATE;
        }
    }
    assert(nmoves > 0);
    for (int i = 0; i < nmoves; ++i) {
        position.make_move(sp, moves[i]);
        pv.push(moves[i]);
        value = std::max(value, negamax(position, /*alpha*/-beta, /*beta*/-alpha, depth - 1, pv));
        pv.pop();
        position.undo_move(sp, moves[i]);
        alpha = std::max(alpha, value);
        if (alpha >= beta) {
            break;
        }
    }
    return -value;
}

SearchResult search(Position& position)
{
    int bestmove = -1;
    int bestscore = -INFINITY;
    Savepos sp;
    Moves moves{256};
    int nmoves = position.generate_legal_moves(&moves[0]);
    PV pv;
    for (int i = 0; i < nmoves; ++i) {
        position.make_move(sp, moves[i]);
        pv.push(moves[i]);
        int score = negamax(position, /*alpha*/-INFINITY, /*beta*/INFINITY, /*depth*/MAX_DEPTH, pv);
        position.undo_move(sp, moves[i]);
        pv.pop();
        if (score > bestscore) {
            bestscore = score;
            bestmove = i;
        }
    }
    assert(bestmove != -1);
    bestscore = position.white_to_move() ? bestscore : -bestscore;
    return {moves[bestmove], bestscore};
}

} // ~namespace lesschess
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */

#include "stdafx.h"

// Tests overlapped calls to Functions, LiveData and Procedures

#include "Connector/Functions.h"
#include "Connector/LiveData.h"
#include "Connector/Procedures.h"

LOGGING (com.opengamma.language.connector.OverlappedTest);

#define TEST_LANGUAGE		TEXT ("test")
#define TIMEOUT_STARTUP		30000
#define TIMEOUT_CALL		3000
#define RETRIES				10

static CConnector *g_poConnector;
static double g_tOverlappedQuery = 0;
static double g_tInlineQuery = 0;

static void StartConnector () {
	g_poConnector = CConnector::Start (TEST_LANGUAGE);
	ASSERT (g_poConnector);
	ASSERT (g_poConnector->WaitForStartup (TIMEOUT_STARTUP));
}

static void StopConnector () {
	ASSERT (g_poConnector->Stop ());
	CConnector::Release (g_poConnector);
	g_poConnector = NULL;
}

static void QueryAvailableOverlapped () {
	g_tOverlappedQuery = 0;
	int i;
	for (i = 0; i < RETRIES; i++) {
		g_tOverlappedQuery -= GetTickCount ();
		CFunctionQueryAvailable queryFunctions (g_poConnector);
		CLiveDataQueryAvailable queryLiveData (g_poConnector);
		CProcedureQueryAvailable queryProcedures (g_poConnector);
		ASSERT (queryFunctions.Send ());
		ASSERT (queryLiveData.Send ());
		ASSERT (queryProcedures.Send ());
		ASSERT (queryFunctions.Recv (CRequestBuilder::GetDefaultTimeout ()));
		ASSERT (queryLiveData.Recv (CRequestBuilder::GetDefaultTimeout ()));
		ASSERT (queryProcedures.Recv (CRequestBuilder::GetDefaultTimeout ()));
		g_tOverlappedQuery += GetTickCount ();
		LOGDEBUG (TEXT ("Overlapped QueryAvailable = ") << (g_tOverlappedQuery / (double)(i + 1)) << TEXT ("ms"));
	}
	g_tOverlappedQuery /= (double)RETRIES;
	LOGINFO (TEXT ("Overlapped QueryAvailable = ") << g_tOverlappedQuery << TEXT ("ms"));
}

static void DoQueryAvailableOverlapped () {
	QueryAvailableOverlapped ();
	QueryAvailableOverlapped ();
}

static void QueryAvailableInline () {
	int i;
	for (i = 0; i < RETRIES; i++) {
		g_tInlineQuery -= GetTickCount ();
		CFunctionQueryAvailable queryFunctions (g_poConnector);
		ASSERT (queryFunctions.Send ());
		ASSERT (queryFunctions.Recv (CRequestBuilder::GetDefaultTimeout ()));
		CLiveDataQueryAvailable queryLiveData (g_poConnector);
		ASSERT (queryLiveData.Send ());
		ASSERT (queryLiveData.Recv (CRequestBuilder::GetDefaultTimeout ()));
		CProcedureQueryAvailable queryProcedures (g_poConnector);
		ASSERT (queryProcedures.Send ());
		ASSERT (queryProcedures.Recv (CRequestBuilder::GetDefaultTimeout ()));
		g_tInlineQuery += GetTickCount ();
		LOGDEBUG (TEXT ("Inline QueryAvailable = ") << (g_tInlineQuery / (double)(i + 1)) << TEXT ("ms"));
	}
	g_tInlineQuery /= (double)RETRIES;
	LOGINFO (TEXT ("Inline QueryAvailable = ") << g_tInlineQuery << TEXT ("ms"));
}

static void DoQueryAvailableInline () {
	QueryAvailableInline ();
	QueryAvailableInline ();
	ASSERT (g_tOverlappedQuery < g_tInlineQuery);
}

BEGIN_TESTS(OverlappedTest)
	TEST (DoQueryAvailableOverlapped)
	TEST (DoQueryAvailableInline)
	BEFORE_TEST (StartConnector)
	AFTER_TEST (StopConnector)
END_TESTS
<commit_msg>Clear the inline query time and make more retries to smooth out JVM performance discrepencies.<commit_after>/**
 * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */

#include "stdafx.h"

// Tests overlapped calls to Functions, LiveData and Procedures

#include "Connector/Functions.h"
#include "Connector/LiveData.h"
#include "Connector/Procedures.h"

LOGGING (com.opengamma.language.connector.OverlappedTest);

#define TEST_LANGUAGE		TEXT ("test")
#define TIMEOUT_STARTUP		30000
#define TIMEOUT_CALL		3000
#define RETRIES				20

static CConnector *g_poConnector;
static double g_tOverlappedQuery = 0;
static double g_tInlineQuery = 0;

static void StartConnector () {
	g_poConnector = CConnector::Start (TEST_LANGUAGE);
	ASSERT (g_poConnector);
	ASSERT (g_poConnector->WaitForStartup (TIMEOUT_STARTUP));
}

static void StopConnector () {
	ASSERT (g_poConnector->Stop ());
	CConnector::Release (g_poConnector);
	g_poConnector = NULL;
}

static void QueryAvailableOverlapped () {
	g_tOverlappedQuery = 0;
	int i;
	for (i = 0; i < RETRIES; i++) {
		g_tOverlappedQuery -= GetTickCount ();
		CFunctionQueryAvailable queryFunctions (g_poConnector);
		CLiveDataQueryAvailable queryLiveData (g_poConnector);
		CProcedureQueryAvailable queryProcedures (g_poConnector);
		ASSERT (queryFunctions.Send ());
		ASSERT (queryLiveData.Send ());
		ASSERT (queryProcedures.Send ());
		ASSERT (queryFunctions.Recv (CRequestBuilder::GetDefaultTimeout ()));
		ASSERT (queryLiveData.Recv (CRequestBuilder::GetDefaultTimeout ()));
		ASSERT (queryProcedures.Recv (CRequestBuilder::GetDefaultTimeout ()));
		g_tOverlappedQuery += GetTickCount ();
		LOGDEBUG (TEXT ("Overlapped QueryAvailable = ") << (g_tOverlappedQuery / (double)(i + 1)) << TEXT ("ms"));
	}
	g_tOverlappedQuery /= (double)RETRIES;
	LOGINFO (TEXT ("Overlapped QueryAvailable = ") << g_tOverlappedQuery << TEXT ("ms"));
}

static void DoQueryAvailableOverlapped () {
	QueryAvailableOverlapped ();
	QueryAvailableOverlapped ();
}

static void QueryAvailableInline () {
	g_tInlineQuery = 0;
	int i;
	for (i = 0; i < RETRIES; i++) {
		g_tInlineQuery -= GetTickCount ();
		CFunctionQueryAvailable queryFunctions (g_poConnector);
		ASSERT (queryFunctions.Send ());
		ASSERT (queryFunctions.Recv (CRequestBuilder::GetDefaultTimeout ()));
		CLiveDataQueryAvailable queryLiveData (g_poConnector);
		ASSERT (queryLiveData.Send ());
		ASSERT (queryLiveData.Recv (CRequestBuilder::GetDefaultTimeout ()));
		CProcedureQueryAvailable queryProcedures (g_poConnector);
		ASSERT (queryProcedures.Send ());
		ASSERT (queryProcedures.Recv (CRequestBuilder::GetDefaultTimeout ()));
		g_tInlineQuery += GetTickCount ();
		LOGDEBUG (TEXT ("Inline QueryAvailable = ") << (g_tInlineQuery / (double)(i + 1)) << TEXT ("ms"));
	}
	g_tInlineQuery /= (double)RETRIES;
	LOGINFO (TEXT ("Inline QueryAvailable = ") << g_tInlineQuery << TEXT ("ms"));
}

static void DoQueryAvailableInline () {
	QueryAvailableInline ();
	QueryAvailableInline ();
	ASSERT (g_tOverlappedQuery < g_tInlineQuery);
}

BEGIN_TESTS(OverlappedTest)
	TEST (DoQueryAvailableOverlapped)
	TEST (DoQueryAvailableInline)
	BEFORE_TEST (StartConnector)
	AFTER_TEST (StopConnector)
END_TESTS
<|endoftext|>


<commit_before>/*
 * Copyright (c), Recep Aslantas.
 *
 * MIT License (MIT), http://opensource.org/licenses/MIT
 * Full license can be found in the LICENSE file
 */

#include "sig.h"
#include "sig-ctx.h"

#include <string.h>
#include <vector>

static int s_sig_context_last_id = 1000;

enum sig_reserved_context_id {
  kSigReservedContextId_Default = 0,
  kSigReservedContextId_Sys     = 1
};

sig_context_s::sig_context_s(int id) : ctx_id(id) { }

const sig_context_t *
sig_ctx_default() {
  static  sig_context_t * __sig_default_ctx;
  if (!__sig_default_ctx) {
    __sig_default_ctx = new sig_context_t(kSigReservedContextId_Default);
  }
  return __sig_default_ctx;
}

const sig_context_t *
sig_ctx_sys() {
  static  sig_context_t * __sig_sys_ctx;
  if (!__sig_sys_ctx) {
    __sig_sys_ctx = new sig_context_t(kSigReservedContextId_Sys);
  }
  return __sig_sys_ctx;
}

const sig_context_t *
sig_ctx_new() {
  int next_id = ++s_sig_context_last_id;
  sig_context_t * new_ctx = new sig_context_t(next_id);
  return new_ctx;
}

namespace sig {

template <typename T>
context_manager<T>::sig_signal_req_t::sig_signal_req_t(T signal,
                                                       sig_observer_cb2_t cb)
  : m_signal_id(signal),
    m_cb(cb) { }

//template <typename T>
//template <typename ... _Types>
//void
//context_manager<T>::sig_signal_req_t::
//operator()(_Types ... _Args) const {
//  m_cb(_Args...);
//}

template <typename T>
void
context_manager<T>::sig_signal_req_t::operator() (sig_signal_t s) const {
  m_cb(s);
}

template <typename T>
bool
context_manager<T>::sig_signal_req_t::operator== (const T& r1) const {
  return m_signal_id == r1;
}

template < >
bool
context_manager<CStringPtr>::sig_signal_req_t::operator==
  (const CStringPtr& r1) const {
  return strcmp(m_signal_id, r1) == 0;
}

template <typename T>
context_manager<T>::context_manager(const sig_context_t * sig_ctx) {
  m_observers = new std::vector<sig_signal_req_t>;
}

template <typename T>
void
context_manager<T>::add(T signal, sig_observer_cb2_t cb) const {
  sig_signal_req_t sig_req(signal, cb);
  m_observers->push_back(sig_req);
}

template <typename T>
void
context_manager<T>::fire(T signal, void * object) const {
  typename std::vector<sig_signal_req_t>::iterator it = m_observers->begin();
  for (; it != m_observers->end(); it++) {
     sig_signal_req_t sig_req = *it;
     if (sig_req == signal) {
       sig_signal_t signal_object(object, // TODO:
                                  m_ctx,
                                  object);
       sig_req(signal_object);
     }
  }
}

template <typename T>
const sig_context_t *
context_manager<T>::ctx() const {
  return m_ctx;
}

template <typename T>
context_manager<T>::~context_manager() {
  m_observers->clear();
  delete m_observers;
}

// default context managers
context_manager<int> __sig_def_ctx_mngr(sig_ctx_default());
context_manager<CStringPtr> __sig_def_ctx_mngr_s(sig_ctx_sys());

// explicit instantiation
template class context_manager<int>;
template class context_manager<CStringPtr>;

};
<commit_msg>fix default ctx manager initialization<commit_after>/*
 * Copyright (c), Recep Aslantas.
 *
 * MIT License (MIT), http://opensource.org/licenses/MIT
 * Full license can be found in the LICENSE file
 */

#include "sig.h"
#include "sig-ctx.h"

#include <string.h>
#include <vector>

static int s_sig_context_last_id = 1000;

enum sig_reserved_context_id {
  kSigReservedContextId_Default = 0,
  kSigReservedContextId_Sys     = 1
};

sig_context_s::sig_context_s(int id) : ctx_id(id) { }

const sig_context_t *
sig_ctx_default() {
  static  sig_context_t * __sig_default_ctx;
  if (!__sig_default_ctx) {
    __sig_default_ctx = new sig_context_t(kSigReservedContextId_Default);
  }
  return __sig_default_ctx;
}

const sig_context_t *
sig_ctx_sys() {
  static  sig_context_t * __sig_sys_ctx;
  if (!__sig_sys_ctx) {
    __sig_sys_ctx = new sig_context_t(kSigReservedContextId_Sys);
  }
  return __sig_sys_ctx;
}

const sig_context_t *
sig_ctx_new() {
  int next_id = ++s_sig_context_last_id;
  sig_context_t * new_ctx = new sig_context_t(next_id);
  return new_ctx;
}

namespace sig {

template <typename T>
context_manager<T>::sig_signal_req_t::sig_signal_req_t(T signal,
                                                       sig_observer_cb2_t cb)
  : m_signal_id(signal),
    m_cb(cb) { }

//template <typename T>
//template <typename ... _Types>
//void
//context_manager<T>::sig_signal_req_t::
//operator()(_Types ... _Args) const {
//  m_cb(_Args...);
//}

template <typename T>
void
context_manager<T>::sig_signal_req_t::operator() (sig_signal_t s) const {
  m_cb(s);
}

template <typename T>
bool
context_manager<T>::sig_signal_req_t::operator== (const T& r1) const {
  return m_signal_id == r1;
}

template < >
bool
context_manager<CStringPtr>::sig_signal_req_t::operator==
  (const CStringPtr& r1) const {
  return strcmp(m_signal_id, r1) == 0;
}

template <typename T>
context_manager<T>::context_manager(const sig_context_t * sig_ctx) {
  m_observers = new std::vector<sig_signal_req_t>;
}

template <typename T>
void
context_manager<T>::add(T signal, sig_observer_cb2_t cb) const {
  sig_signal_req_t sig_req(signal, cb);
  m_observers->push_back(sig_req);
}

template <typename T>
void
context_manager<T>::fire(T signal, void * object) const {
  typename std::vector<sig_signal_req_t>::iterator it = m_observers->begin();
  for (; it != m_observers->end(); it++) {
     sig_signal_req_t sig_req = *it;
     if (sig_req == signal) {
       sig_signal_t signal_object(object, // TODO:
                                  m_ctx,
                                  object);
       sig_req(signal_object);
     }
  }
}

template <typename T>
const sig_context_t *
context_manager<T>::ctx() const {
  return m_ctx;
}

template <typename T>
context_manager<T>::~context_manager() {
  m_observers->clear();
  delete m_observers;
}

// default context managers
context_manager<int> __sig_def_ctx_mngr(sig_ctx_default());
context_manager<CStringPtr> __sig_def_ctx_mngr_s(sig_ctx_default());

// explicit instantiation
template class context_manager<int>;
template class context_manager<CStringPtr>;

};
<|endoftext|>


<commit_before>/*
 * =====================================================================================
 *
 *       Filename:  socket.cpp
 *
 *    Description:  Socket control
 *
 *        Version:  1.1
 *        Created:  27/01/13 20:55:15
 *       Revision:  none
 *       Compiler:  g++
 *
 *         Author:  Daniel Bugl <Daniel.Bugl@touchlay.com>
 *   Organization:  TouchLay
 *
 * =====================================================================================
 */

// Headers
#include "socket.h"

/* Socket: Constructor */
Socket::Socket(int port) {
 // Clear the file descriptor sets
 FD_ZERO(&master);
 FD_ZERO(&rfds);

 // Prevent SIGPIPE from killing the server
 signal(SIGPIPE, SIG_IGN);

 // Create socket
 if ((tdata.listener=socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  std::cout << "[ERROR] [socket      ] Couldn't create socket." << std::endl;
  close(tdata.listener);
  exit(EXIT_FAILURE);
 }

 // Make the socket non-blocking
 if ((fcntl(tdata.listener, F_SETFL, O_NONBLOCK)) < 0) {
  std::cout << "[ERROR] [socket      ] Couldn't make the socket non-blocking." << std::endl;
  close(tdata.listener);
  exit(EXIT_FAILURE);
 }

 // Get rid of address already in use errors
 int on = 1;
 if ((setsockopt(tdata.listener, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on))) < 0) std::cout << "[WARN ] [socket      ] setsockopt failed, this isn't critical, continuing." << std::endl;

 std::cout << "[INFO ] [socket      ] Created socket at port " << port << "." << std::endl;

 // Initialise sockaddr
 struct sockaddr_in sockaddr;
 memset(&sockaddr, 0, sizeof(sockaddr));
 sockaddr.sin_port = htons(port); // Set port
 sockaddr.sin_family = AF_INET;
 sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);

 // Bind socket
 if (bind(tdata.listener, (struct sockaddr *)&sockaddr, sizeof(sockaddr)) < 0) {
  std::cout << "[ERROR] [socket      ] Couldn't bind to socket." << std::endl;
  exit(EXIT_FAILURE);
 }
 #ifdef DEBUG
 std::cout << "[DEBUG] [socket      ] Bound to socket." << std::endl;
 #endif

 // Listen to socket
 if (listen(tdata.listener, LISTENQ) < 0) {
  std::cout << "[ERROR] [socket      ] Couldn't listen to socket." << std::endl;
  exit(EXIT_FAILURE);
 }
 #ifdef DEBUG
 std::cout << "[DEBUG] [socket      ] Listening to socket." << std::endl;
 #endif

 // Add listener to the master set
 FD_SET(tdata.listener, &master);
 fdmax = tdata.listener;
}

void *newconn(void *ptr) {
 conndata *tdata;
 tdata = (conndata *)ptr;

 try {
  // Deallocate resources upon return
  if ((pthread_detach(pthread_self())) < 0) std::cout << "[WARN ] [child       ] Couldn't detach thread." << std::endl;

  #ifdef DEBUG
  std::cout << "[DEBUG] [child       ] New connection. Forked child process." << std::endl;
  #endif

  if ((tdata->cip = inet_ntoa(tdata->client.sin_addr)) < 0) {
   std::cout << "[ERROR] [child       ] Failed to get peer address." << std::endl;
   pthread_exit(0);
  }
  #ifdef DEBUG
  std::cout << "[DEBUG] [child       ] Peer address: " << tdata->cip << std::endl;
  #endif

  RequestHandler(tdata->connection, tdata->cip); // Initialise request handler
  if (close(tdata->connection) < 0) std::cout << "[WARN ] [child       ] Couldn't close connection." << std::endl;
  #ifdef DEBUG
  else std::cout << "[DEBUG] [child       ] Connection closed. Killing child process." << std::endl;
  #endif
 } catch (std::exception &e) {
  std::cout << "[ERROR] [child       ] Caught an exception: " << e.what() << std::endl;
 }
 pthread_exit(0); // Kill thread
}

/* loop: Main loop for the socket */
int Socket::loop() {
 // Initialise client struct
 sockaddr_in client;
 client.sin_family = AF_INET;
 socklen_t clen = sizeof(client);
 tdata.cip = NULL;
 pthread_t thread;

 while (true) {
  rfds = master;

  // Wait for activities on the sockets, timeout NULL, so it waits forever
  if (((select(fdmax+1, &rfds, NULL, NULL, NULL)) < 0) && (errno != EINTR)) { std::cout << "[WARN ] [socket      ] Couldn't select connection. (ERRNO: " << errno << ")" << std::endl;
   exit(-1);
  }
  // Something happened on the listener socket, incoming connection
  if (FD_ISSET(tdata.listener, &rfds)) {
   // Accept connection if available
   if ((tdata.connection=accept(tdata.listener, (struct sockaddr*)&tdata.client, &clen)) < 0) {
    if (errno != EWOULDBLOCK) {
     std::cout << "[WARN ] [socket      ] Couldn't accept connection. (ERRNO: " << errno << ")" << std::endl;
     usleep(1000000);
     continue;
    }
   } else {
    pthread_create(&thread, NULL, newconn, (void *)&tdata);
    //pthread_join(thread, NULL);
    //pthread_cancel(thread);
   }
  }
 }

 return EXIT_FAILURE; // Something bad happened, exit parent
}
<commit_msg>Catching all exceptions now.<commit_after>/*
 * =====================================================================================
 *
 *       Filename:  socket.cpp
 *
 *    Description:  Socket control
 *
 *        Version:  1.1
 *        Created:  27/01/13 20:55:15
 *       Revision:  none
 *       Compiler:  g++
 *
 *         Author:  Daniel Bugl <Daniel.Bugl@touchlay.com>
 *   Organization:  TouchLay
 *
 * =====================================================================================
 */

// Headers
#include "socket.h"

/* Socket: Constructor */
Socket::Socket(int port) {
 // Clear the file descriptor sets
 FD_ZERO(&master);
 FD_ZERO(&rfds);

 // Prevent SIGPIPE from killing the server
 signal(SIGPIPE, SIG_IGN);

 // Create socket
 if ((tdata.listener=socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  std::cout << "[ERROR] [socket      ] Couldn't create socket." << std::endl;
  close(tdata.listener);
  exit(EXIT_FAILURE);
 }

 // Make the socket non-blocking
 if ((fcntl(tdata.listener, F_SETFL, O_NONBLOCK)) < 0) {
  std::cout << "[ERROR] [socket      ] Couldn't make the socket non-blocking." << std::endl;
  close(tdata.listener);
  exit(EXIT_FAILURE);
 }

 // Get rid of address already in use errors
 int on = 1;
 if ((setsockopt(tdata.listener, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on))) < 0) std::cout << "[WARN ] [socket      ] setsockopt failed, this isn't critical, continuing." << std::endl;

 std::cout << "[INFO ] [socket      ] Created socket at port " << port << "." << std::endl;

 // Initialise sockaddr
 struct sockaddr_in sockaddr;
 memset(&sockaddr, 0, sizeof(sockaddr));
 sockaddr.sin_port = htons(port); // Set port
 sockaddr.sin_family = AF_INET;
 sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);

 // Bind socket
 if (bind(tdata.listener, (struct sockaddr *)&sockaddr, sizeof(sockaddr)) < 0) {
  std::cout << "[ERROR] [socket      ] Couldn't bind to socket." << std::endl;
  exit(EXIT_FAILURE);
 }
 #ifdef DEBUG
 std::cout << "[DEBUG] [socket      ] Bound to socket." << std::endl;
 #endif

 // Listen to socket
 if (listen(tdata.listener, LISTENQ) < 0) {
  std::cout << "[ERROR] [socket      ] Couldn't listen to socket." << std::endl;
  exit(EXIT_FAILURE);
 }
 #ifdef DEBUG
 std::cout << "[DEBUG] [socket      ] Listening to socket." << std::endl;
 #endif

 // Add listener to the master set
 FD_SET(tdata.listener, &master);
 fdmax = tdata.listener;
}

void *newconn(void *ptr) {
 conndata *tdata;
 tdata = (conndata *)ptr;

 try {
  // Deallocate resources upon return
  if ((pthread_detach(pthread_self())) < 0) std::cout << "[WARN ] [child       ] Couldn't detach thread." << std::endl;

  #ifdef DEBUG
  std::cout << "[DEBUG] [child       ] New connection. Forked child process." << std::endl;
  #endif

  if ((tdata->cip = inet_ntoa(tdata->client.sin_addr)) < 0) {
   std::cout << "[ERROR] [child       ] Failed to get peer address." << std::endl;
   pthread_exit(0);
  }
  #ifdef DEBUG
  std::cout << "[DEBUG] [child       ] Peer address: " << tdata->cip << std::endl;
  #endif

  RequestHandler(tdata->connection, tdata->cip); // Initialise request handler
  if (close(tdata->connection) < 0) std::cout << "[WARN ] [child       ] Couldn't close connection." << std::endl;
  #ifdef DEBUG
  else std::cout << "[DEBUG] [child       ] Connection closed. Killing child process." << std::endl;
  #endif
 } catch (const std::exception &e) {
  std::cout << "[ERROR] [child       ] Caught an exception: " << e.what() << std::endl;
 } catch (...) {
  std::cout << "[ERROR] [child       ] Caught an unknown exception." << std::endl;
 }
 pthread_exit(0); // Kill thread
}

/* loop: Main loop for the socket */
int Socket::loop() {
 // Initialise client struct
 sockaddr_in client;
 client.sin_family = AF_INET;
 socklen_t clen = sizeof(client);
 tdata.cip = NULL;
 pthread_t thread;

 while (true) {
  rfds = master;

  // Wait for activities on the sockets, timeout NULL, so it waits forever
  if (((select(fdmax+1, &rfds, NULL, NULL, NULL)) < 0) && (errno != EINTR)) { std::cout << "[WARN ] [socket      ] Couldn't select connection. (ERRNO: " << errno << ")" << std::endl;
   exit(-1);
  }
  // Something happened on the listener socket, incoming connection
  if (FD_ISSET(tdata.listener, &rfds)) {
   // Accept connection if available
   if ((tdata.connection=accept(tdata.listener, (struct sockaddr*)&tdata.client, &clen)) < 0) {
    if (errno != EWOULDBLOCK) {
     std::cout << "[WARN ] [socket      ] Couldn't accept connection. (ERRNO: " << errno << ")" << std::endl;
     usleep(1000000);
     continue;
    }
   } else {
    pthread_create(&thread, NULL, newconn, (void *)&tdata);
    //pthread_join(thread, NULL);
    //pthread_cancel(thread);
   }
  }
 }

 return EXIT_FAILURE; // Something bad happened, exit parent
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

/* Internal dependencies */
#include "structure.h"
#include "solver.h"
#include "utils.h"

#define SIZE 100

using namespace std;

int main() {
    char input[SIZE] = "";
    char* indent = (char*) malloc(sizeof(char) * 4);

    // Display logo
    logo();

    // Ask for equation
    cout << "\nEnter a system to solve : ";
    fgets(input, SIZE, stdin);

    // Remove new line of stop if empty
    if(input != NULL){
        size_t len = strlen(input);
        if (len > 0 && input[len-1] == '\n')
            input[--len] = '\0';
    } else {
        cout << "Empty systems..." << endl;
        return 0;
    }

    ///////////////////
    // Explore
    /////

    Equation *head;
    Equation *tail;

    Array *systems = cut(input, hook, ',', 0);
    if(systems == NULL){
        cout << input << endl;
        cout << " ^ No systems detected..." << endl;
        return 0;
    }

	while(systems != NULL) {
        strcpy(indent, "    ");
        cout << endl << indent << "+- System : " << systems->value << endl;
        systems->value = substr(systems->value, 1, strlen(systems->value) - 2);

        // Reset if old value
        head = tail = NULL;
        bool br = false;

        Array *equations = cut(systems->value, hook, ',', 0);
        while(equations != NULL) {
            cout << indent << "+- Equation : " << equations->value << endl;
            if(equations->next != NULL)
                indent = addChar(indent, "|  ");
            else
                indent = addChar(indent, "   ");

            equations->value = substr(equations->value, 1, strlen(equations->value) - 2);
            Equation *equation = new Equation;
            equation->next = NULL;

            Array *arbres = cut(equations->value, bracket, ',', 0);
            int i = size(arbres);
            if(i != 2) {
                if(i < 2)
                    error(" ^ Missing arguments (Two expected)", strlen(indent));
                else
                    error(" ^ Too many arguments (Two expected)", strlen(indent));

                br = true;
                break;
            }

            bool valid = true;
            int j = 0;
            while(arbres != NULL) {
                Arbre *arbre = get_structure(arbres->value);
                equation->args[j++] = arbre;
                if(arbre->typ_terme == 0)
                    valid = false;
                explore(arbre, 0, indent, arbres->next != NULL);
                arbres = arbres->next;
            }

            // Ignore if not a valid equation (f > 3 for exemple)
            if(valid) {
                if(tail != NULL)
                    tail->next = equation;

                tail = equation;

                if(head == NULL)
                    head = equation;
            }

            indent = substr(indent, 0, strlen(indent) - 3);
            equations = equations->next;
        }

        if(br){
            systems = systems->next;
            continue;
        }

        cout << indent << endl;
        indent = substr(indent, 0, strlen(indent) - 3);

        ///////////////////
        // Solve
        /////

        cout << "Equation : +- ";
        printEquation(head);
        cout << endl;

        // Resolve the system
        Arguments *result = resolve(head);

        cout << "Solution : +- ";
        if(result == NULL)
            cout << "The system has no solution." << endl;
        else {
            int i = 1;
            Arguments *temp = result;
            cout << "{";
            while(temp != NULL) {
                if(temp->value != NULL){
                    cout << "x" << i++ << "=";
                    printArbre(temp->value);
                }
                temp = temp->next;
                if(temp != NULL)
                    cout << "; ";
            }
            cout << "}" << endl;

            // Simplifie the result
            temp = simplify(result);
            i = 1;

            cout << "           +- " << "{";
            while(temp != NULL) {
                if(temp->value != NULL){
                    cout << "x" << i++ << "=";
                    printArbre(temp->value);
                }
                temp = temp->next;
                if(temp != NULL)
                    cout << "; ";
            }
            cout << "}" << endl << endl;
        }

        freeSystems(head);
        systems = systems->next;
    }

    if(indent)
        free(indent);

    return 0;
}

/**
 * Display error message
 */
void error(const char* message, int space) {
    char spacer[space];
    for(int i = 0; i < space; i++)
        spacer[i] = ' ';
    cout << spacer << message << endl;
}

/**
 * Display main logo
 */
void logo(){
	cout << "#----------------------------------------------#      \n";
	cout << "  __  __      _   _      ___      _                   \n";
	cout << " |  \\/  |__ _| |_| |_   / __| ___| |_ _____ _ _      \n";
	cout << " | |\\/| / _` |  _| ' \\  \\__ \\/ _ \\ \\ V / -_) '_|\n";
	cout << " |_|  |_\\__,_|\\__|_||_|_|___/\\___/_|\\_/\\___|_|   \n";
	cout << "                     |___|                            \n";
	cout << "#----------------------------------------------#      \n";
}<commit_msg>Fix S.F caused by empty system<commit_after>#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

/* Internal dependencies */
#include "structure.h"
#include "solver.h"
#include "utils.h"

#define SIZE 100

using namespace std;

int main() {
    char input[SIZE] = "";
    char* indent = (char*) malloc(sizeof(char) * 4);

    // Display logo
    logo();

    // Ask for equation
    cout << "\nEnter a system to solve : ";
    fgets(input, SIZE, stdin);

    // Remove new line of stop if empty
    if(input[0] != '\n'){
        size_t len = strlen(input);
        if (len > 0 && input[len-1] == '\n')
            input[--len] = '\0';
    } else {
        cout << "No system..." << endl;
        return 0;
    }

    ///////////////////
    // Explore
    /////

    Equation *head;
    Equation *tail;

    Array *systems = cut(input, hook, ',', 0);
    if(systems == NULL){
        cout << input << endl;
        cout << " ^ No systems detected..." << endl;
        return 0;
    }

	while(systems != NULL) {
        cout << endl << "+- System : " << systems->value << endl;
        strcpy(indent, "    ");
        systems->value = substr(systems->value, 1, strlen(systems->value) - 2);

        // Reset if old value
        head = tail = NULL;
        bool br = false;

        Array *equations = cut(systems->value, hook, ',', 0);
        while(equations != NULL) {
            cout << indent << "+- Equation : " << equations->value << endl;
            if(equations->next != NULL)
                indent = addChar(indent, "|  ");
            else
                indent = addChar(indent, "   ");

            equations->value = substr(equations->value, 1, strlen(equations->value) - 2);
            Equation *equation = new Equation;
            equation->next = NULL;

            Array *arbres = cut(equations->value, bracket, ',', 0);
            int i = size(arbres);
            if(i != 2) {
                if(i < 2)
                    error(" ^ Missing arguments (Two expected)", strlen(indent));
                else
                    error(" ^ Too many arguments (Two expected)", strlen(indent));

                br = true;
                break;
            }

            bool valid = true;
            int j = 0;
            while(arbres != NULL) {
                Arbre *arbre = get_structure(arbres->value);
                equation->args[j++] = arbre;
                if(arbre->typ_terme == 0)
                    valid = false;
                explore(arbre, 0, indent, arbres->next != NULL);
                arbres = arbres->next;
            }

            // Ignore if not a valid equation (f > 3 for exemple)
            if(valid) {
                if(tail != NULL)
                    tail->next = equation;

                tail = equation;

                if(head == NULL)
                    head = equation;
            }

            indent = substr(indent, 0, strlen(indent) - 3);
            equations = equations->next;
        }

        if(br){
            systems = systems->next;
            continue;
        }

        cout << indent << endl;
        indent = substr(indent, 0, strlen(indent) - 3);

        ///////////////////
        // Solve
        /////

        cout << "Equation : +- ";
        printEquation(head);
        cout << endl;

        // Resolve the system
        Arguments *result = resolve(head);

        cout << "Solution : +- ";
        if(result == NULL)
            cout << "The system has no solution." << endl;
        else {
            int i = 1;
            Arguments *temp = result;
            cout << "{";
            while(temp != NULL) {
                if(temp->value != NULL){
                    cout << "x" << i++ << "=";
                    printArbre(temp->value);
                }
                temp = temp->next;
                if(temp != NULL)
                    cout << "; ";
            }
            cout << "}" << endl;

            // Simplifie the result
            temp = simplify(result);
            i = 1;

            cout << "           +- " << "{";
            while(temp != NULL) {
                if(temp->value != NULL){
                    cout << "x" << i++ << "=";
                    printArbre(temp->value);
                }
                temp = temp->next;
                if(temp != NULL)
                    cout << "; ";
            }
            cout << "}" << endl << endl;
        }

        freeSystems(head);
        systems = systems->next;
    }

    if(indent)
        free(indent);

    return 0;
}

/**
 * Display error message
 */
void error(const char* message, int space) {
    char spacer[space];
    for(int i = 0; i < space; i++)
        spacer[i] = ' ';
    cout << spacer << message << endl;
}

/**
 * Display main logo
 */
void logo(){
	cout << "#----------------------------------------------#      \n";
	cout << "  __  __      _   _      ___      _                   \n";
	cout << " |  \\/  |__ _| |_| |_   / __| ___| |_ _____ _ _      \n";
	cout << " | |\\/| / _` |  _| ' \\  \\__ \\/ _ \\ \\ V / -_) '_|\n";
	cout << " |_|  |_\\__,_|\\__|_||_|_|___/\\___/_|\\_/\\___|_|   \n";
	cout << "                     |___|                            \n";
	cout << "#----------------------------------------------#      \n";
}<|endoftext|>


<commit_before>/*
 * String hash map.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef BENG_PROXY_STRMAP_HXX
#define BENG_PROXY_STRMAP_HXX

#include <inline/compiler.h>

#include <boost/intrusive/set.hpp>

#include <utility>

struct pool;

struct strmap {
    struct Item : boost::intrusive::set_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> {
        const char *key, *value;

        Item(const char *_key, const char *_value)
            :key(_key), value(_value) {}

        class Compare {
            gcc_pure
            bool Less(const char *a, const char *b) const;

        public:
            gcc_pure
            bool operator()(const char *a, const Item &b) const {
                return Less(a, b.key);
            }

            gcc_pure
            bool operator()(const Item &a, const char *b) const {
                return Less(a.key, b);
            }

            gcc_pure
            bool operator()(const Item &a, const Item &b) const {
                return Less(a.key, b.key);
            }
        };
    };

    struct pool &pool;

    typedef boost::intrusive::multiset<Item,
                                       boost::intrusive::compare<Item::Compare>,
                                       boost::intrusive::constant_time_size<false>> Map;

    typedef Map::const_iterator const_iterator;

    Map map;

    explicit strmap(struct pool &_pool):pool(_pool) {}

    strmap(struct pool &_pool, const strmap &src);

    strmap(const strmap &) = delete;

    strmap(strmap &&src)
        :pool(src.pool), map(std::move(src.map)) {}

    const_iterator begin() const {
        return map.begin();
    }

    const_iterator end() const {
        return map.end();
    }

    void Add(const char *key, const char *value);
    const char *Set(const char *key, const char *value);
    const char *Remove(const char *key);

    gcc_pure
    const char *Get(const char *key) const;

    gcc_pure
    std::pair<const_iterator, const_iterator> EqualRange(const char *key) const;
};

struct strmap *gcc_malloc
strmap_new(struct pool *pool);

struct strmap *gcc_malloc
strmap_dup(struct pool *pool, const struct strmap *src);

/**
 * This variation of strmap::Remove() allows the caller to pass
 * map=nullptr.
 */
static inline const char *
strmap_remove_checked(struct strmap *map, const char *key)
{
    return map != nullptr
        ? map->Remove(key)
        : nullptr;
}

/**
 * This variation of strmap::Get() allows the caller to pass
 * map=nullptr.
 */
gcc_pure
static inline const char *
strmap_get_checked(const struct strmap *map, const char *key)
{
    return map != nullptr
        ? map->Get(key)
        : nullptr;
}

#endif
<commit_msg>strmap: use "default" move constructor<commit_after>/*
 * String hash map.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef BENG_PROXY_STRMAP_HXX
#define BENG_PROXY_STRMAP_HXX

#include <inline/compiler.h>

#include <boost/intrusive/set.hpp>

#include <utility>

struct pool;

struct strmap {
    struct Item : boost::intrusive::set_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> {
        const char *key, *value;

        Item(const char *_key, const char *_value)
            :key(_key), value(_value) {}

        class Compare {
            gcc_pure
            bool Less(const char *a, const char *b) const;

        public:
            gcc_pure
            bool operator()(const char *a, const Item &b) const {
                return Less(a, b.key);
            }

            gcc_pure
            bool operator()(const Item &a, const char *b) const {
                return Less(a.key, b);
            }

            gcc_pure
            bool operator()(const Item &a, const Item &b) const {
                return Less(a.key, b.key);
            }
        };
    };

    struct pool &pool;

    typedef boost::intrusive::multiset<Item,
                                       boost::intrusive::compare<Item::Compare>,
                                       boost::intrusive::constant_time_size<false>> Map;

    typedef Map::const_iterator const_iterator;

    Map map;

    explicit strmap(struct pool &_pool):pool(_pool) {}

    strmap(struct pool &_pool, const strmap &src);

    strmap(const strmap &) = delete;

    strmap(strmap &&src) = default;

    const_iterator begin() const {
        return map.begin();
    }

    const_iterator end() const {
        return map.end();
    }

    void Add(const char *key, const char *value);
    const char *Set(const char *key, const char *value);
    const char *Remove(const char *key);

    gcc_pure
    const char *Get(const char *key) const;

    gcc_pure
    std::pair<const_iterator, const_iterator> EqualRange(const char *key) const;
};

struct strmap *gcc_malloc
strmap_new(struct pool *pool);

struct strmap *gcc_malloc
strmap_dup(struct pool *pool, const struct strmap *src);

/**
 * This variation of strmap::Remove() allows the caller to pass
 * map=nullptr.
 */
static inline const char *
strmap_remove_checked(struct strmap *map, const char *key)
{
    return map != nullptr
        ? map->Remove(key)
        : nullptr;
}

/**
 * This variation of strmap::Get() allows the caller to pass
 * map=nullptr.
 */
gcc_pure
static inline const char *
strmap_get_checked(const struct strmap *map, const char *key)
{
    return map != nullptr
        ? map->Get(key)
        : nullptr;
}

#endif
<|endoftext|>


<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/fastos/fastos.h>
#include "indexproperties.h"
#include "properties.h"
#include <limits>

namespace search {
namespace fef {
namespace indexproperties {

namespace {

vespalib::string
lookupString(const Properties &props, const vespalib::string &name,
             const vespalib::string &defaultValue)
{
    Property p = props.lookup(name);
    if (p.found()) {
        return p.get();
    }
    return defaultValue;
}

std::vector<vespalib::string>
lookupStringVector(const Properties &props, const vespalib::string &name,
                   const std::vector<vespalib::string> &defaultValue)
{
    Property p = props.lookup(name);
    if (p.found()) {
        std::vector<vespalib::string> retval;
        for (uint32_t i = 0; i < p.size(); ++i) {
            retval.push_back(p.getAt(i));
        }
        return retval;
    }
    return defaultValue;
}

double
lookupDouble(const Properties &props, const vespalib::string &name, double defaultValue)
{
    Property p = props.lookup(name);
    if (p.found()) {
        return strtod(p.get().c_str(), NULL);
    }
    return defaultValue;
}

uint32_t
lookupUint32(const Properties &props, const vespalib::string &name, uint32_t defaultValue)
{
    Property p = props.lookup(name);
    if (p.found()) {
        return atoi(p.get().c_str());
    }
    return defaultValue;
}

bool
lookupBool(const Properties &props, const vespalib::string &name, bool defaultValue)
{
    Property p = props.lookup(name);
    if (p.found()) {
        return (p.get() == "true");
    }
    return defaultValue;
}

bool
checkIfTrue(const Properties &props, const vespalib::string &name,
            const vespalib::string &defaultValue)
{
    return (props.lookup(name).get(defaultValue) == "true");
}

}

namespace rank {

const vespalib::string FirstPhase::NAME("vespa.rank.firstphase");
const vespalib::string FirstPhase::DEFAULT_VALUE("nativeRank");

vespalib::string
FirstPhase::lookup(const Properties &props)
{
    return lookupString(props, NAME, DEFAULT_VALUE);
}

const vespalib::string SecondPhase::NAME("vespa.rank.secondphase");
const vespalib::string SecondPhase::DEFAULT_VALUE("");

vespalib::string
SecondPhase::lookup(const Properties &props)
{
    return lookupString(props, NAME, DEFAULT_VALUE);
}

} // namespace rank

namespace summary {

const vespalib::string Feature::NAME("vespa.summary.feature");
const std::vector<vespalib::string> Feature::DEFAULT_VALUE;

std::vector<vespalib::string>
Feature::lookup(const Properties &props)
{
    return lookupStringVector(props, NAME, DEFAULT_VALUE);
}

} // namespace summary

namespace dump {

const vespalib::string Feature::NAME("vespa.dump.feature");
const std::vector<vespalib::string> Feature::DEFAULT_VALUE;

std::vector<vespalib::string>
Feature::lookup(const Properties &props)
{
    return lookupStringVector(props, NAME, DEFAULT_VALUE);
}

const vespalib::string IgnoreDefaultFeatures::NAME("vespa.dump.ignoredefaultfeatures");
const vespalib::string IgnoreDefaultFeatures::DEFAULT_VALUE("false");

bool
IgnoreDefaultFeatures::check(const Properties &props)
{
    return checkIfTrue(props, NAME, DEFAULT_VALUE);
}

} // namespace dump

namespace matching {

const vespalib::string TermwiseLimit::NAME("vespa.matching.termwise_limit");
const double TermwiseLimit::DEFAULT_VALUE(1.0);

double
TermwiseLimit::lookup(const Properties &props)
{
    return lookupDouble(props, NAME, DEFAULT_VALUE);
}

const vespalib::string NumThreadsPerSearch::NAME("vespa.matching.numthreadspersearch");
const uint32_t NumThreadsPerSearch::DEFAULT_VALUE(std::numeric_limits<uint32_t>::max());

uint32_t
NumThreadsPerSearch::lookup(const Properties &props)
{
    return lookupUint32(props, NAME, DEFAULT_VALUE);
}

const vespalib::string NumSearchPartitions::NAME("vespa.matching.numsearchpartitions");
const uint32_t NumSearchPartitions::DEFAULT_VALUE(1);

uint32_t
NumSearchPartitions::lookup(const Properties &props)
{
    return lookupUint32(props, NAME, DEFAULT_VALUE);
}

const vespalib::string MinHitsPerThread::NAME("vespa.matching.minhitsperthread");
const uint32_t MinHitsPerThread::DEFAULT_VALUE(0);

uint32_t
MinHitsPerThread::lookup(const Properties &props)
{
    return lookupUint32(props, NAME, DEFAULT_VALUE);
}

} // namespace matching

namespace softtimeout {

const vespalib::string Enabled::NAME("vespa.softtimeout.enabled");
const bool Enabled::DEFAULT_VALUE(false);

bool Enabled::lookup(const Properties &props) {
    return lookupBool(props, NAME, DEFAULT_VALUE);
}

bool Enabled::lookup(const Properties &props, bool defaultValue) {
    return lookupBool(props, NAME, defaultValue);
}

const vespalib::string TailCost::NAME("vespa.softtimeout.tailcost");
const double TailCost::DEFAULT_VALUE(0.1);

double TailCost::lookup(const Properties &props) {
    return lookupDouble(props, NAME, DEFAULT_VALUE);
}

const vespalib::string Factor::NAME("vespa.softtimeout.factor");
const double Factor::DEFAULT_VALUE(0.5);

double Factor::lookup(const Properties &props) {
    return lookupDouble(props, NAME, DEFAULT_VALUE);
}
double Factor::lookup(const Properties &props, double defaultValue) {
    return lookupDouble(props, NAME, defaultValue);
}

}

namespace matchphase {

const vespalib::string DegradationAttribute::NAME("vespa.matchphase.degradation.attribute");
const vespalib::string DegradationAttribute::DEFAULT_VALUE("");

const vespalib::string DegradationAscendingOrder::NAME("vespa.matchphase.degradation.ascendingorder");
const bool DegradationAscendingOrder::DEFAULT_VALUE(false);

const vespalib::string DegradationMaxHits::NAME("vespa.matchphase.degradation.maxhits");
const uint32_t DegradationMaxHits::DEFAULT_VALUE(0);

const vespalib::string DegradationSamplePercentage::NAME("vespa.matchphase.degradation.samplepercentage");
const double DegradationSamplePercentage::DEFAULT_VALUE(0.2);

const vespalib::string DegradationMaxFilterCoverage::NAME("vespa.matchphase.degradation.maxfiltercoverage");
const double DegradationMaxFilterCoverage::DEFAULT_VALUE(0.2);

const vespalib::string DegradationPostFilterMultiplier::NAME("vespa.matchphase.degradation.postfiltermultiplier");
const double DegradationPostFilterMultiplier::DEFAULT_VALUE(1.0);

const vespalib::string DiversityAttribute::NAME("vespa.matchphase.diversity.attribute");
const vespalib::string DiversityAttribute::DEFAULT_VALUE("");

const vespalib::string DiversityMinGroups::NAME("vespa.matchphase.diversity.mingroups");
const uint32_t DiversityMinGroups::DEFAULT_VALUE(1);

const vespalib::string DiversityCutoffFactor::NAME("vespa.matchphase.diversity.cutoff.factor");
const double DiversityCutoffFactor::DEFAULT_VALUE(10.0);

const vespalib::string DiversityCutoffStrategy::NAME("vespa.matchphase.diversity.cutoff.strategy");
const vespalib::string DiversityCutoffStrategy::DEFAULT_VALUE("loose");

vespalib::string
DegradationAttribute::lookup(const Properties &props)
{
    return lookupString(props, NAME, DEFAULT_VALUE);
}

bool
DegradationAscendingOrder::lookup(const Properties &props)
{
    return lookupBool(props, NAME, DEFAULT_VALUE);
}

uint32_t
DegradationMaxHits::lookup(const Properties &props)
{
    return lookupUint32(props, NAME, DEFAULT_VALUE);
}

double
DegradationSamplePercentage::lookup(const Properties &props)
{
    return lookupDouble(props, NAME, DEFAULT_VALUE);
}

double
DegradationMaxFilterCoverage::lookup(const Properties &props)
{
    return lookupDouble(props, NAME, DEFAULT_VALUE);
}

double
DegradationPostFilterMultiplier::lookup(const Properties &props)
{
    return lookupDouble(props, NAME, DEFAULT_VALUE);
}

vespalib::string
DiversityAttribute::lookup(const Properties &props)
{
    return lookupString(props, NAME, DEFAULT_VALUE);
}

uint32_t
DiversityMinGroups::lookup(const Properties &props)
{
    return lookupUint32(props, NAME, DEFAULT_VALUE);
}

double
DiversityCutoffFactor::lookup(const Properties &props)
{
    return lookupDouble(props, NAME, DEFAULT_VALUE);
}

vespalib::string
DiversityCutoffStrategy::lookup(const Properties &props)
{
    return lookupString(props, NAME, DEFAULT_VALUE);
}

}

namespace hitcollector {

const vespalib::string HeapSize::NAME("vespa.hitcollector.heapsize");
const uint32_t HeapSize::DEFAULT_VALUE(100);

uint32_t
HeapSize::lookup(const Properties &props)
{
    return lookupUint32(props, NAME, DEFAULT_VALUE);
}

const vespalib::string ArraySize::NAME("vespa.hitcollector.arraysize");
const uint32_t ArraySize::DEFAULT_VALUE(10000);

uint32_t
ArraySize::lookup(const Properties &props)
{
    return lookupUint32(props, NAME, DEFAULT_VALUE);
}

const vespalib::string EstimatePoint::NAME("vespa.hitcollector.estimatepoint");
const uint32_t EstimatePoint::DEFAULT_VALUE(0xffffffff);

uint32_t
EstimatePoint::lookup(const Properties &props)
{
    return lookupUint32(props, NAME, DEFAULT_VALUE);
}

const vespalib::string EstimateLimit::NAME("vespa.hitcollector.estimatelimit");
const uint32_t EstimateLimit::DEFAULT_VALUE(0xffffffff);

uint32_t
EstimateLimit::lookup(const Properties &props)
{
    return lookupUint32(props, NAME, DEFAULT_VALUE);
}

const vespalib::string RankScoreDropLimit::NAME("vespa.hitcollector.rankscoredroplimit");
const feature_t RankScoreDropLimit::DEFAULT_VALUE(-std::numeric_limits<feature_t>::quiet_NaN());

feature_t
RankScoreDropLimit::lookup(const Properties &props)
{
    return lookupDouble(props, NAME, DEFAULT_VALUE);
}

} // namspace hitcollector

const vespalib::string FieldWeight::BASE_NAME("vespa.fieldweight.");
const uint32_t FieldWeight::DEFAULT_VALUE(100);

uint32_t
FieldWeight::lookup(const Properties &props, const vespalib::string &fieldName)
{
    return lookupUint32(props, BASE_NAME + fieldName, DEFAULT_VALUE);
}

const vespalib::string IsFilterField::BASE_NAME("vespa.isfilterfield.");
const vespalib::string IsFilterField::DEFAULT_VALUE("false");

void
IsFilterField::set(Properties &props, const vespalib::string &fieldName)
{
    props.add(BASE_NAME + fieldName, "true");
}

bool
IsFilterField::check(const Properties &props, const vespalib::string &fieldName)
{
    return checkIfTrue(props, BASE_NAME + fieldName, DEFAULT_VALUE);
}

namespace type {

const vespalib::string Attribute::BASE_NAME("vespa.type.attribute.");
const vespalib::string Attribute::DEFAULT_VALUE("");

vespalib::string
Attribute::lookup(const Properties &props, const vespalib::string &attributeName)
{
    return lookupString(props, BASE_NAME + attributeName, DEFAULT_VALUE);
}

void
Attribute::set(Properties &props, const vespalib::string &attributeName, const vespalib::string &type)
{
    props.add(BASE_NAME + attributeName, type);
}

const vespalib::string QueryFeature::BASE_NAME("vespa.type.query.");
const vespalib::string QueryFeature::DEFAULT_VALUE("");

vespalib::string
QueryFeature::lookup(const Properties &props, const vespalib::string &queryFeatureName)
{
    return lookupString(props, BASE_NAME + queryFeatureName, DEFAULT_VALUE);
}

void
QueryFeature::set(Properties &props, const vespalib::string &queryFeatureName, const vespalib::string &type)
{
    props.add(BASE_NAME + queryFeatureName, type);
}

} // namespace type

} // namespace indexproperties
} // namespace fef
} // namespace search
<commit_msg>enabled -> enable<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/fastos/fastos.h>
#include "indexproperties.h"
#include "properties.h"
#include <limits>

namespace search {
namespace fef {
namespace indexproperties {

namespace {

vespalib::string
lookupString(const Properties &props, const vespalib::string &name,
             const vespalib::string &defaultValue)
{
    Property p = props.lookup(name);
    if (p.found()) {
        return p.get();
    }
    return defaultValue;
}

std::vector<vespalib::string>
lookupStringVector(const Properties &props, const vespalib::string &name,
                   const std::vector<vespalib::string> &defaultValue)
{
    Property p = props.lookup(name);
    if (p.found()) {
        std::vector<vespalib::string> retval;
        for (uint32_t i = 0; i < p.size(); ++i) {
            retval.push_back(p.getAt(i));
        }
        return retval;
    }
    return defaultValue;
}

double
lookupDouble(const Properties &props, const vespalib::string &name, double defaultValue)
{
    Property p = props.lookup(name);
    if (p.found()) {
        return strtod(p.get().c_str(), NULL);
    }
    return defaultValue;
}

uint32_t
lookupUint32(const Properties &props, const vespalib::string &name, uint32_t defaultValue)
{
    Property p = props.lookup(name);
    if (p.found()) {
        return atoi(p.get().c_str());
    }
    return defaultValue;
}

bool
lookupBool(const Properties &props, const vespalib::string &name, bool defaultValue)
{
    Property p = props.lookup(name);
    if (p.found()) {
        return (p.get() == "true");
    }
    return defaultValue;
}

bool
checkIfTrue(const Properties &props, const vespalib::string &name,
            const vespalib::string &defaultValue)
{
    return (props.lookup(name).get(defaultValue) == "true");
}

}

namespace rank {

const vespalib::string FirstPhase::NAME("vespa.rank.firstphase");
const vespalib::string FirstPhase::DEFAULT_VALUE("nativeRank");

vespalib::string
FirstPhase::lookup(const Properties &props)
{
    return lookupString(props, NAME, DEFAULT_VALUE);
}

const vespalib::string SecondPhase::NAME("vespa.rank.secondphase");
const vespalib::string SecondPhase::DEFAULT_VALUE("");

vespalib::string
SecondPhase::lookup(const Properties &props)
{
    return lookupString(props, NAME, DEFAULT_VALUE);
}

} // namespace rank

namespace summary {

const vespalib::string Feature::NAME("vespa.summary.feature");
const std::vector<vespalib::string> Feature::DEFAULT_VALUE;

std::vector<vespalib::string>
Feature::lookup(const Properties &props)
{
    return lookupStringVector(props, NAME, DEFAULT_VALUE);
}

} // namespace summary

namespace dump {

const vespalib::string Feature::NAME("vespa.dump.feature");
const std::vector<vespalib::string> Feature::DEFAULT_VALUE;

std::vector<vespalib::string>
Feature::lookup(const Properties &props)
{
    return lookupStringVector(props, NAME, DEFAULT_VALUE);
}

const vespalib::string IgnoreDefaultFeatures::NAME("vespa.dump.ignoredefaultfeatures");
const vespalib::string IgnoreDefaultFeatures::DEFAULT_VALUE("false");

bool
IgnoreDefaultFeatures::check(const Properties &props)
{
    return checkIfTrue(props, NAME, DEFAULT_VALUE);
}

} // namespace dump

namespace matching {

const vespalib::string TermwiseLimit::NAME("vespa.matching.termwise_limit");
const double TermwiseLimit::DEFAULT_VALUE(1.0);

double
TermwiseLimit::lookup(const Properties &props)
{
    return lookupDouble(props, NAME, DEFAULT_VALUE);
}

const vespalib::string NumThreadsPerSearch::NAME("vespa.matching.numthreadspersearch");
const uint32_t NumThreadsPerSearch::DEFAULT_VALUE(std::numeric_limits<uint32_t>::max());

uint32_t
NumThreadsPerSearch::lookup(const Properties &props)
{
    return lookupUint32(props, NAME, DEFAULT_VALUE);
}

const vespalib::string NumSearchPartitions::NAME("vespa.matching.numsearchpartitions");
const uint32_t NumSearchPartitions::DEFAULT_VALUE(1);

uint32_t
NumSearchPartitions::lookup(const Properties &props)
{
    return lookupUint32(props, NAME, DEFAULT_VALUE);
}

const vespalib::string MinHitsPerThread::NAME("vespa.matching.minhitsperthread");
const uint32_t MinHitsPerThread::DEFAULT_VALUE(0);

uint32_t
MinHitsPerThread::lookup(const Properties &props)
{
    return lookupUint32(props, NAME, DEFAULT_VALUE);
}

} // namespace matching

namespace softtimeout {

const vespalib::string Enabled::NAME("vespa.softtimeout.enable");
const bool Enabled::DEFAULT_VALUE(false);

bool Enabled::lookup(const Properties &props) {
    return lookupBool(props, NAME, DEFAULT_VALUE);
}

bool Enabled::lookup(const Properties &props, bool defaultValue) {
    return lookupBool(props, NAME, defaultValue);
}

const vespalib::string TailCost::NAME("vespa.softtimeout.tailcost");
const double TailCost::DEFAULT_VALUE(0.1);

double TailCost::lookup(const Properties &props) {
    return lookupDouble(props, NAME, DEFAULT_VALUE);
}

const vespalib::string Factor::NAME("vespa.softtimeout.factor");
const double Factor::DEFAULT_VALUE(0.5);

double Factor::lookup(const Properties &props) {
    return lookupDouble(props, NAME, DEFAULT_VALUE);
}
double Factor::lookup(const Properties &props, double defaultValue) {
    return lookupDouble(props, NAME, defaultValue);
}

}

namespace matchphase {

const vespalib::string DegradationAttribute::NAME("vespa.matchphase.degradation.attribute");
const vespalib::string DegradationAttribute::DEFAULT_VALUE("");

const vespalib::string DegradationAscendingOrder::NAME("vespa.matchphase.degradation.ascendingorder");
const bool DegradationAscendingOrder::DEFAULT_VALUE(false);

const vespalib::string DegradationMaxHits::NAME("vespa.matchphase.degradation.maxhits");
const uint32_t DegradationMaxHits::DEFAULT_VALUE(0);

const vespalib::string DegradationSamplePercentage::NAME("vespa.matchphase.degradation.samplepercentage");
const double DegradationSamplePercentage::DEFAULT_VALUE(0.2);

const vespalib::string DegradationMaxFilterCoverage::NAME("vespa.matchphase.degradation.maxfiltercoverage");
const double DegradationMaxFilterCoverage::DEFAULT_VALUE(0.2);

const vespalib::string DegradationPostFilterMultiplier::NAME("vespa.matchphase.degradation.postfiltermultiplier");
const double DegradationPostFilterMultiplier::DEFAULT_VALUE(1.0);

const vespalib::string DiversityAttribute::NAME("vespa.matchphase.diversity.attribute");
const vespalib::string DiversityAttribute::DEFAULT_VALUE("");

const vespalib::string DiversityMinGroups::NAME("vespa.matchphase.diversity.mingroups");
const uint32_t DiversityMinGroups::DEFAULT_VALUE(1);

const vespalib::string DiversityCutoffFactor::NAME("vespa.matchphase.diversity.cutoff.factor");
const double DiversityCutoffFactor::DEFAULT_VALUE(10.0);

const vespalib::string DiversityCutoffStrategy::NAME("vespa.matchphase.diversity.cutoff.strategy");
const vespalib::string DiversityCutoffStrategy::DEFAULT_VALUE("loose");

vespalib::string
DegradationAttribute::lookup(const Properties &props)
{
    return lookupString(props, NAME, DEFAULT_VALUE);
}

bool
DegradationAscendingOrder::lookup(const Properties &props)
{
    return lookupBool(props, NAME, DEFAULT_VALUE);
}

uint32_t
DegradationMaxHits::lookup(const Properties &props)
{
    return lookupUint32(props, NAME, DEFAULT_VALUE);
}

double
DegradationSamplePercentage::lookup(const Properties &props)
{
    return lookupDouble(props, NAME, DEFAULT_VALUE);
}

double
DegradationMaxFilterCoverage::lookup(const Properties &props)
{
    return lookupDouble(props, NAME, DEFAULT_VALUE);
}

double
DegradationPostFilterMultiplier::lookup(const Properties &props)
{
    return lookupDouble(props, NAME, DEFAULT_VALUE);
}

vespalib::string
DiversityAttribute::lookup(const Properties &props)
{
    return lookupString(props, NAME, DEFAULT_VALUE);
}

uint32_t
DiversityMinGroups::lookup(const Properties &props)
{
    return lookupUint32(props, NAME, DEFAULT_VALUE);
}

double
DiversityCutoffFactor::lookup(const Properties &props)
{
    return lookupDouble(props, NAME, DEFAULT_VALUE);
}

vespalib::string
DiversityCutoffStrategy::lookup(const Properties &props)
{
    return lookupString(props, NAME, DEFAULT_VALUE);
}

}

namespace hitcollector {

const vespalib::string HeapSize::NAME("vespa.hitcollector.heapsize");
const uint32_t HeapSize::DEFAULT_VALUE(100);

uint32_t
HeapSize::lookup(const Properties &props)
{
    return lookupUint32(props, NAME, DEFAULT_VALUE);
}

const vespalib::string ArraySize::NAME("vespa.hitcollector.arraysize");
const uint32_t ArraySize::DEFAULT_VALUE(10000);

uint32_t
ArraySize::lookup(const Properties &props)
{
    return lookupUint32(props, NAME, DEFAULT_VALUE);
}

const vespalib::string EstimatePoint::NAME("vespa.hitcollector.estimatepoint");
const uint32_t EstimatePoint::DEFAULT_VALUE(0xffffffff);

uint32_t
EstimatePoint::lookup(const Properties &props)
{
    return lookupUint32(props, NAME, DEFAULT_VALUE);
}

const vespalib::string EstimateLimit::NAME("vespa.hitcollector.estimatelimit");
const uint32_t EstimateLimit::DEFAULT_VALUE(0xffffffff);

uint32_t
EstimateLimit::lookup(const Properties &props)
{
    return lookupUint32(props, NAME, DEFAULT_VALUE);
}

const vespalib::string RankScoreDropLimit::NAME("vespa.hitcollector.rankscoredroplimit");
const feature_t RankScoreDropLimit::DEFAULT_VALUE(-std::numeric_limits<feature_t>::quiet_NaN());

feature_t
RankScoreDropLimit::lookup(const Properties &props)
{
    return lookupDouble(props, NAME, DEFAULT_VALUE);
}

} // namspace hitcollector

const vespalib::string FieldWeight::BASE_NAME("vespa.fieldweight.");
const uint32_t FieldWeight::DEFAULT_VALUE(100);

uint32_t
FieldWeight::lookup(const Properties &props, const vespalib::string &fieldName)
{
    return lookupUint32(props, BASE_NAME + fieldName, DEFAULT_VALUE);
}

const vespalib::string IsFilterField::BASE_NAME("vespa.isfilterfield.");
const vespalib::string IsFilterField::DEFAULT_VALUE("false");

void
IsFilterField::set(Properties &props, const vespalib::string &fieldName)
{
    props.add(BASE_NAME + fieldName, "true");
}

bool
IsFilterField::check(const Properties &props, const vespalib::string &fieldName)
{
    return checkIfTrue(props, BASE_NAME + fieldName, DEFAULT_VALUE);
}

namespace type {

const vespalib::string Attribute::BASE_NAME("vespa.type.attribute.");
const vespalib::string Attribute::DEFAULT_VALUE("");

vespalib::string
Attribute::lookup(const Properties &props, const vespalib::string &attributeName)
{
    return lookupString(props, BASE_NAME + attributeName, DEFAULT_VALUE);
}

void
Attribute::set(Properties &props, const vespalib::string &attributeName, const vespalib::string &type)
{
    props.add(BASE_NAME + attributeName, type);
}

const vespalib::string QueryFeature::BASE_NAME("vespa.type.query.");
const vespalib::string QueryFeature::DEFAULT_VALUE("");

vespalib::string
QueryFeature::lookup(const Properties &props, const vespalib::string &queryFeatureName)
{
    return lookupString(props, BASE_NAME + queryFeatureName, DEFAULT_VALUE);
}

void
QueryFeature::set(Properties &props, const vespalib::string &queryFeatureName, const vespalib::string &type)
{
    props.add(BASE_NAME + queryFeatureName, type);
}

} // namespace type

} // namespace indexproperties
} // namespace fef
} // namespace search
<|endoftext|>


<commit_before>#include <OpenMesh/Core/IO/Options.hh>
#include <OpenMesh/Core/IO/MeshIO.hh>
#include <Eigen/Core>
#include "mesh_definitions.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <GLUT/glut.h>
#include "simplex/simplexnoise.h"
#include <time.h>
#include <stdlib.h>
#include "chamber.h"

using namespace Eigen;
using namespace std;
using namespace OpenMesh;

double tileSize = 1;
int maxDistort = 12;
OpenMesh::VPropHandleT<int> v_index;

// Number of vertices and faces of the mesh
int n_vertices = 0, n_faces = 0;

void randomOrder(vector<Wall>* arr){
  srand(time(NULL));
  for (int i = 0; i < arr->size(); i++){
    int swap = rand() % arr->size();
    Wall temp = (*arr)[i];
    (*arr)[i] = (*arr)[swap];
    (*arr)[swap] = temp;
  }
}

void generateMesh(int width, int length, int height, vector <vector <vector<Chamber> > > cells) { //note that this is lwh of actual cells (including walls)
  Mesh maze;
  srand(time(NULL));
  maze.request_face_normals();
  maze.request_vertex_normals();
  maze.request_vertex_texcoords2D();
  //maze.add_property(v_index);
  //GENERATE MAIN VERTICES THAT WILL ANCHOR THE WALLS
  Mesh::VertexHandle mainVert[length+1][height+1][width+1];
  for (int i = 0; i <= height; i++){
    for (int j = 0; j <= width; j++){
      for (int k = 0; k <= length; k++){
        double distortx = (double)(rand() % maxDistort)/(1.8*maxDistort/tileSize);
        double distorty = (double)(rand() % maxDistort)/(1.8*maxDistort/tileSize);
        double distortz = (double)(rand() % maxDistort)/(2*maxDistort/tileSize);
        if (k != length-1 && (k%2==1 || k == 0)) distortx = -distortx;
        if (j != width-1 && (j%2==1 || j == 0)) distortz = -distortz;
        if (i != height-1 && (i%2==1 || i == 0)) distorty = -distorty;
        Vec3f point(k * tileSize + distortx, i * tileSize + distorty, j * tileSize + distortz);
        mainVert[k][i][j] = maze.add_vertex(point);
        //maze.property(v_index, mainVert[k][i][j]) = i*height + j*width + k;
        //maze.set_texcoord2D(mainVert[k][i][j], Vec2f(0,0));
      }
    }
  }
  //LINK UP MESH
  vector<Mesh::VertexHandle> face_vhandles;
  for (int i = 0; i < height; i++){
    for (int j = 0; j < width; j++){
      for (int k = 0; k < length; k++){
        if (cells[k][i][j].isWall()){ //if it is a wall
          int type = cells[k][i][j].type();
          if (type == FC || type == YWALL){
            //bottom
            if (i == 0 || !cells[k][i-1][j].isWall() ){
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k][i][j]);
              face_vhandles.push_back(mainVert[k+1][i][j+1]);
              face_vhandles.push_back(mainVert[k][i][j+1]);
              maze.add_face(face_vhandles);
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k+1][i][j]);
              face_vhandles.push_back(mainVert[k+1][i][j+1]);
              face_vhandles.push_back(mainVert[k][i][j]);
              maze.add_face(face_vhandles);
              n_faces += 2;
            }
            //top
            if (i == height-1 || !cells[k][i+1][j].isWall()){
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k][i+1][j]);
              face_vhandles.push_back(mainVert[k][i+1][j+1]);
              face_vhandles.push_back(mainVert[k+1][i+1][j+1]);
              maze.add_face(face_vhandles);
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k][i+1][j]);
              face_vhandles.push_back(mainVert[k+1][i+1][j+1]);
              face_vhandles.push_back(mainVert[k+1][i+1][j]);
              maze.add_face(face_vhandles);
              n_faces += 2;
            }
          }
          if(type == FC || type == CORE || type == XWALL){
            //left
            if (k == 0 || !cells[k-1][i][j].isWall()){
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k][i][j]);
              face_vhandles.push_back(mainVert[k][i+1][j+1]);
              face_vhandles.push_back(mainVert[k][i+1][j]);
              maze.add_face(face_vhandles);
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k][i][j]);
              face_vhandles.push_back(mainVert[k][i][j+1]);
              face_vhandles.push_back(mainVert[k][i+1][j+1]);
              maze.add_face(face_vhandles);
              n_faces += 2;
            }
            //right
            if (k == length-1 || !cells[k+1][i][j].isWall()){
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k+1][i][j]);
              face_vhandles.push_back(mainVert[k+1][i+1][j]);
              face_vhandles.push_back(mainVert[k+1][i+1][j+1]);
              maze.add_face(face_vhandles);
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k+1][i][j]);
              face_vhandles.push_back(mainVert[k+1][i+1][j+1]);
              face_vhandles.push_back(mainVert[k+1][i][j+1]);
              maze.add_face(face_vhandles);
              n_faces += 2;
            }
          }
          if(type == FC || type == CORE || type == ZWALL){
            //close
            if (j == 0 || !cells[k][i][j-1].isWall()){
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k][i][j]);
              face_vhandles.push_back(mainVert[k][i+1][j]);
              face_vhandles.push_back(mainVert[k+1][i+1][j]);
              maze.add_face(face_vhandles);
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k][i][j]);
              face_vhandles.push_back(mainVert[k+1][i+1][j]);
              face_vhandles.push_back(mainVert[k+1][i][j]);
              maze.add_face(face_vhandles);
              n_faces += 2;
            }
            //far
            if (j == width-1 || !cells[k][i][j+1].isWall()){
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k][i][j+1]);
              face_vhandles.push_back(mainVert[k+1][i+1][j+1]);
              face_vhandles.push_back(mainVert[k][i+1][j+1]);
              maze.add_face(face_vhandles);
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k][i][j+1]);
              face_vhandles.push_back(mainVert[k+1][i][j+1]);
              face_vhandles.push_back(mainVert[k+1][i+1][j+1]);
              maze.add_face(face_vhandles);
              n_faces += 2;
            }
          }

        }
      }
    }
  }

  // subdivide
  Loop sDivide;
  sDivide.attach(maze);
  bool success = sDivide(3);
  sDivide.detach();
  maze.update_normals();

  double scale = max(max(length, width), height)*tileSize;
  for (Mesh::ConstVertexIter vIt = maze.vertices_begin(); vIt != maze.vertices_end(); ++vIt){
    Vec3f vert = maze.point(vIt);
    double effect = 0.4*tileSize * octave_noise_3d(6.0, .75, 2, vert[0]/scale, vert[1]/scale, vert[2]/scale);
    Vec3f shift(effect*maze.normal(vIt)[0], effect*maze.normal(vIt)[1], effect*maze.normal(vIt)[2]);
    maze.set_point(vIt, vert - shift);
    maze.set_texcoord2D(vIt, Vec2f(0,0));
  }
  maze.update_normals();

  //WRITE OBJ FILE
  IO::Options wopt;
  wopt += IO::Options::VertexNormal;
  wopt += IO::Options::VertexTexCoord;
  if (!OpenMesh::IO::write_mesh(maze, "maze.obj", wopt))
  {
    std::cerr << "write error\n";
    exit(1);
  }

}

void generateMaze(int width, int length, int height, double scale){
  //Use Kruskal's algorithm to get a maze starting with a 3d set of walls (i.e. cubes)
  tileSize = scale;
	width = width*2+1;
	length = length*2+1;
	height = height*2+1;
  n_vertices = (width+1)*(length+1)*(height+1);
	vector<Wall> mazeWalls; //these are only walls which may be removed
	//Chamber cells[length][height][width];
  vector <vector <vector<Chamber> > > cells(length, vector<vector<Chamber> >(height, vector<Chamber>(width) ) );
  //GENERATE ORIGINAL GRID OF WALLS AND CHAMBERS
	for (int i = 0; i < height; i++){ //for each level (Y direction)
  	for(int j = 0; j < width; j++){ //for each row (Z direction)
  		for(int k = 0; k < length; k++){ //for each element in row (X direction)
        cells[k][i][j].parent = &(cells[k][i][j]);
        // if (i == 0 || j == 0 || k == 0 || i == height-1 || j == width-1 || k == length-1){
        //   cells[k][i][j].setType(BORDER);
        //   continue;
        // }
  			if (i%2 == 0){	//even level
  				if (j%2 == 1 && k%2 == 1){ //odd-odd cells are floor/ceilings that can be removed
  					Wall w = Wall(k, i, j, YWALL);
            cells[k][i][j].setType(YWALL);
            if (i == 0 || j == 0 || k == 0 || i == height-1 || j == width-1 || k == length-1) continue;
            mazeWalls.push_back(w);
  				}	else { //other cells are floor/ceilings that can't be removed
            cells[k][i][j].setType(FC);
          }
  			} else { //odd level
  				if (k%2 == 1){
            if (j%2 == 0){//odd x, even z - this is a wall
              Wall w = Wall(k, i, j, ZWALL);
              cells[k][i][j].setType(ZWALL);
              if (i == 0 || j == 0 || k == 0 || i == height-1 || j == width-1 || k == length-1) continue;
              mazeWalls.push_back(w);
            } //else: odd x, odd z - this is an open chamber aka default
  				} else {
            if (j%2 == 1){ //even x, odd z - this is a wall
              Wall w = Wall(k, i, j, XWALL);
              cells[k][i][j].setType(XWALL);
              if (i == 0 || j == 0 || k == 0 || i == height-1 || j == width-1 || k == length-1) continue;
              mazeWalls.push_back(w);
            } else { //even x, even z - this is a core wall
              cells[k][i][j].setType(CORE);
            }
          }
  			}
  		}
  	}
	}
  // cout << mazeWalls.size() << endl;
  //SHUFFLE WALLS
  randomOrder(&mazeWalls);
  //DELETE WALLS UNTIL CONNECTED
  for (int i = 0; i < mazeWalls.size(); i++){
    Wall w = mazeWalls[i];
    Chamber* one = cells[w.ax][w.ay][w.az].getRoot();
    Chamber* two = cells[w.bx][w.by][w.bz].getRoot();
    if (one != two){ //if the wall separates unconnected chambers
      //combine chambers
      cUnion(&cells[w.ax][w.ay][w.az], &cells[w.bx][w.by][w.bz]);
      cells[w.sx][w.sy][w.sz].setType(NOTWALL);
    }
  }

  //FOR TESTING PURPOSES: PRINT MAZE IN LAYERS
  for (int i = 0; i < height; i++){
    cout << endl << "Level " << i << endl;
    for (int j = 0; j < width; j++){
      for (int k = 0; k < length; k++){
        if (cells[k][i][j].isWall()){
          int type = cells[k][i][j].type();
          switch(type){
            case FC:
              cout << "F";
              break;
            case YWALL:
              cout << "Y";
              break;
            case XWALL:
              cout << "X";
              break;
            case ZWALL:
              cout << "Z";
              break;
            case CORE:
              cout << "C";
              break;
            case BORDER:
              cout << "B";
              break;
            default:
              cout << type;
              break;
          }
        } else {
          cout << "_";
        }
      }
      cout << endl;
    }
  }

  generateMesh(width, length, height, cells);

}

int main(int argc, char** argv){
  if (argc > 3){
    if (argc == 5) {
      generateMaze(atof(argv[1]), atof(argv[2]), atof(argv[3]), atof(argv[4]));
    } else {
      generateMaze(atof(argv[1]), atof(argv[2]), atof(argv[3]), 1);
    }
  } else {
    generateMaze(3, 4, 3, 1);
  }
  return 0;
}
<commit_msg>switched back zdistort<commit_after>#include <OpenMesh/Core/IO/Options.hh>
#include <OpenMesh/Core/IO/MeshIO.hh>
#include <Eigen/Core>
#include "mesh_definitions.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <GLUT/glut.h>
#include "simplex/simplexnoise.h"
#include <time.h>
#include <stdlib.h>
#include "chamber.h"

using namespace Eigen;
using namespace std;
using namespace OpenMesh;

double tileSize = 1;
int maxDistort = 12;
OpenMesh::VPropHandleT<int> v_index;

// Number of vertices and faces of the mesh
int n_vertices = 0, n_faces = 0;

void randomOrder(vector<Wall>* arr){
  srand(time(NULL));
  for (int i = 0; i < arr->size(); i++){
    int swap = rand() % arr->size();
    Wall temp = (*arr)[i];
    (*arr)[i] = (*arr)[swap];
    (*arr)[swap] = temp;
  }
}

void generateMesh(int width, int length, int height, vector <vector <vector<Chamber> > > cells) { //note that this is lwh of actual cells (including walls)
  Mesh maze;
  srand(time(NULL));
  maze.request_face_normals();
  maze.request_vertex_normals();
  maze.request_vertex_texcoords2D();
  //maze.add_property(v_index);
  //GENERATE MAIN VERTICES THAT WILL ANCHOR THE WALLS
  Mesh::VertexHandle mainVert[length+1][height+1][width+1];
  for (int i = 0; i <= height; i++){
    for (int j = 0; j <= width; j++){
      for (int k = 0; k <= length; k++){
        double distortx = (double)(rand() % maxDistort)/(1.8*maxDistort/tileSize);
        double distorty = (double)(rand() % maxDistort)/(1.8*maxDistort/tileSize);
        double distortz = (double)(rand() % maxDistort)/(1.8*maxDistort/tileSize);
        if (k != length-1 && (k%2==1 || k == 0)) distortx = -distortx;
        if (j != width-1 && (j%2==1 || j == 0)) distortz = -distortz;
        if (i != height-1 && (i%2==1 || i == 0)) distorty = -distorty;
        Vec3f point(k * tileSize + distortx, i * tileSize + distorty, j * tileSize + distortz);
        mainVert[k][i][j] = maze.add_vertex(point);
        //maze.property(v_index, mainVert[k][i][j]) = i*height + j*width + k;
        //maze.set_texcoord2D(mainVert[k][i][j], Vec2f(0,0));
      }
    }
  }
  //LINK UP MESH
  vector<Mesh::VertexHandle> face_vhandles;
  for (int i = 0; i < height; i++){
    for (int j = 0; j < width; j++){
      for (int k = 0; k < length; k++){
        if (cells[k][i][j].isWall()){ //if it is a wall
          int type = cells[k][i][j].type();
          if (type == FC || type == YWALL){
            //bottom
            if (i == 0 || !cells[k][i-1][j].isWall() ){
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k][i][j]);
              face_vhandles.push_back(mainVert[k+1][i][j+1]);
              face_vhandles.push_back(mainVert[k][i][j+1]);
              maze.add_face(face_vhandles);
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k+1][i][j]);
              face_vhandles.push_back(mainVert[k+1][i][j+1]);
              face_vhandles.push_back(mainVert[k][i][j]);
              maze.add_face(face_vhandles);
              n_faces += 2;
            }
            //top
            if (i == height-1 || !cells[k][i+1][j].isWall()){
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k][i+1][j]);
              face_vhandles.push_back(mainVert[k][i+1][j+1]);
              face_vhandles.push_back(mainVert[k+1][i+1][j+1]);
              maze.add_face(face_vhandles);
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k][i+1][j]);
              face_vhandles.push_back(mainVert[k+1][i+1][j+1]);
              face_vhandles.push_back(mainVert[k+1][i+1][j]);
              maze.add_face(face_vhandles);
              n_faces += 2;
            }
          }
          if(type == FC || type == CORE || type == XWALL){
            //left
            if (k == 0 || !cells[k-1][i][j].isWall()){
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k][i][j]);
              face_vhandles.push_back(mainVert[k][i+1][j+1]);
              face_vhandles.push_back(mainVert[k][i+1][j]);
              maze.add_face(face_vhandles);
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k][i][j]);
              face_vhandles.push_back(mainVert[k][i][j+1]);
              face_vhandles.push_back(mainVert[k][i+1][j+1]);
              maze.add_face(face_vhandles);
              n_faces += 2;
            }
            //right
            if (k == length-1 || !cells[k+1][i][j].isWall()){
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k+1][i][j]);
              face_vhandles.push_back(mainVert[k+1][i+1][j]);
              face_vhandles.push_back(mainVert[k+1][i+1][j+1]);
              maze.add_face(face_vhandles);
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k+1][i][j]);
              face_vhandles.push_back(mainVert[k+1][i+1][j+1]);
              face_vhandles.push_back(mainVert[k+1][i][j+1]);
              maze.add_face(face_vhandles);
              n_faces += 2;
            }
          }
          if(type == FC || type == CORE || type == ZWALL){
            //close
            if (j == 0 || !cells[k][i][j-1].isWall()){
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k][i][j]);
              face_vhandles.push_back(mainVert[k][i+1][j]);
              face_vhandles.push_back(mainVert[k+1][i+1][j]);
              maze.add_face(face_vhandles);
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k][i][j]);
              face_vhandles.push_back(mainVert[k+1][i+1][j]);
              face_vhandles.push_back(mainVert[k+1][i][j]);
              maze.add_face(face_vhandles);
              n_faces += 2;
            }
            //far
            if (j == width-1 || !cells[k][i][j+1].isWall()){
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k][i][j+1]);
              face_vhandles.push_back(mainVert[k+1][i+1][j+1]);
              face_vhandles.push_back(mainVert[k][i+1][j+1]);
              maze.add_face(face_vhandles);
              face_vhandles.clear();
              face_vhandles.push_back(mainVert[k][i][j+1]);
              face_vhandles.push_back(mainVert[k+1][i][j+1]);
              face_vhandles.push_back(mainVert[k+1][i+1][j+1]);
              maze.add_face(face_vhandles);
              n_faces += 2;
            }
          }

        }
      }
    }
  }

  // subdivide
  Loop sDivide;
  sDivide.attach(maze);
  bool success = sDivide(3);
  sDivide.detach();
  maze.update_normals();

  double scale = max(max(length, width), height)*tileSize;
  for (Mesh::ConstVertexIter vIt = maze.vertices_begin(); vIt != maze.vertices_end(); ++vIt){
    Vec3f vert = maze.point(vIt);
    double effect = 0.4*tileSize * octave_noise_3d(6.0, .75, 2, vert[0]/scale, vert[1]/scale, vert[2]/scale);
    Vec3f shift(effect*maze.normal(vIt)[0], effect*maze.normal(vIt)[1], effect*maze.normal(vIt)[2]);
    maze.set_point(vIt, vert - shift);
    maze.set_texcoord2D(vIt, Vec2f(0,0));
  }
  maze.update_normals();

  //WRITE OBJ FILE
  IO::Options wopt;
  wopt += IO::Options::VertexNormal;
  wopt += IO::Options::VertexTexCoord;
  if (!OpenMesh::IO::write_mesh(maze, "maze.obj", wopt))
  {
    std::cerr << "write error\n";
    exit(1);
  }

}

void generateMaze(int width, int length, int height, double scale){
  //Use Kruskal's algorithm to get a maze starting with a 3d set of walls (i.e. cubes)
  tileSize = scale;
	width = width*2+1;
	length = length*2+1;
	height = height*2+1;
  n_vertices = (width+1)*(length+1)*(height+1);
	vector<Wall> mazeWalls; //these are only walls which may be removed
	//Chamber cells[length][height][width];
  vector <vector <vector<Chamber> > > cells(length, vector<vector<Chamber> >(height, vector<Chamber>(width) ) );
  //GENERATE ORIGINAL GRID OF WALLS AND CHAMBERS
	for (int i = 0; i < height; i++){ //for each level (Y direction)
  	for(int j = 0; j < width; j++){ //for each row (Z direction)
  		for(int k = 0; k < length; k++){ //for each element in row (X direction)
        cells[k][i][j].parent = &(cells[k][i][j]);
        // if (i == 0 || j == 0 || k == 0 || i == height-1 || j == width-1 || k == length-1){
        //   cells[k][i][j].setType(BORDER);
        //   continue;
        // }
  			if (i%2 == 0){	//even level
  				if (j%2 == 1 && k%2 == 1){ //odd-odd cells are floor/ceilings that can be removed
  					Wall w = Wall(k, i, j, YWALL);
            cells[k][i][j].setType(YWALL);
            if (i == 0 || j == 0 || k == 0 || i == height-1 || j == width-1 || k == length-1) continue;
            mazeWalls.push_back(w);
  				}	else { //other cells are floor/ceilings that can't be removed
            cells[k][i][j].setType(FC);
          }
  			} else { //odd level
  				if (k%2 == 1){
            if (j%2 == 0){//odd x, even z - this is a wall
              Wall w = Wall(k, i, j, ZWALL);
              cells[k][i][j].setType(ZWALL);
              if (i == 0 || j == 0 || k == 0 || i == height-1 || j == width-1 || k == length-1) continue;
              mazeWalls.push_back(w);
            } //else: odd x, odd z - this is an open chamber aka default
  				} else {
            if (j%2 == 1){ //even x, odd z - this is a wall
              Wall w = Wall(k, i, j, XWALL);
              cells[k][i][j].setType(XWALL);
              if (i == 0 || j == 0 || k == 0 || i == height-1 || j == width-1 || k == length-1) continue;
              mazeWalls.push_back(w);
            } else { //even x, even z - this is a core wall
              cells[k][i][j].setType(CORE);
            }
          }
  			}
  		}
  	}
	}
  // cout << mazeWalls.size() << endl;
  //SHUFFLE WALLS
  randomOrder(&mazeWalls);
  //DELETE WALLS UNTIL CONNECTED
  for (int i = 0; i < mazeWalls.size(); i++){
    Wall w = mazeWalls[i];
    Chamber* one = cells[w.ax][w.ay][w.az].getRoot();
    Chamber* two = cells[w.bx][w.by][w.bz].getRoot();
    if (one != two){ //if the wall separates unconnected chambers
      //combine chambers
      cUnion(&cells[w.ax][w.ay][w.az], &cells[w.bx][w.by][w.bz]);
      cells[w.sx][w.sy][w.sz].setType(NOTWALL);
    }
  }

  //FOR TESTING PURPOSES: PRINT MAZE IN LAYERS
  for (int i = 0; i < height; i++){
    cout << endl << "Level " << i << endl;
    for (int j = 0; j < width; j++){
      for (int k = 0; k < length; k++){
        if (cells[k][i][j].isWall()){
          int type = cells[k][i][j].type();
          switch(type){
            case FC:
              cout << "F";
              break;
            case YWALL:
              cout << "Y";
              break;
            case XWALL:
              cout << "X";
              break;
            case ZWALL:
              cout << "Z";
              break;
            case CORE:
              cout << "C";
              break;
            case BORDER:
              cout << "B";
              break;
            default:
              cout << type;
              break;
          }
        } else {
          cout << "_";
        }
      }
      cout << endl;
    }
  }

  generateMesh(width, length, height, cells);

}

int main(int argc, char** argv){
  if (argc > 3){
    if (argc == 5) {
      generateMaze(atof(argv[1]), atof(argv[2]), atof(argv[3]), atof(argv[4]));
    } else {
      generateMaze(atof(argv[1]), atof(argv[2]), atof(argv[3]), 1);
    }
  } else {
    generateMaze(3, 4, 3, 1);
  }
  return 0;
}
<|endoftext|>