<commit_before>/*
 * High level HTTP client.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "http_request.hxx"
#include "http_response.hxx"
#include "http_client.hxx"
#include "http_headers.hxx"
#include "http_address.hxx"
#include "header_writer.hxx"
#include "tcp_stock.hxx"
#include "tcp_balancer.hxx"
#include "stock/GetHandler.hxx"
#include "stock/Item.hxx"
#include "stock/Lease.hxx"
#include "failure.hxx"
#include "istream/istream.hxx"
#include "istream/UnusedHoldPtr.hxx"
#include "filtered_socket.hxx"
#include "pool.hxx"
#include "GException.hxx"
#include "net/SocketAddress.hxx"
#include "util/Cancellable.hxx"

#include <inline/compiler.h>

#include <string.h>

struct HttpRequest final
    : Cancellable, StockGetHandler, HttpResponseHandler {

    struct pool &pool;
    EventLoop &event_loop;

    TcpBalancer &tcp_balancer;

    const unsigned session_sticky;

    const SocketFilter *const filter;
    SocketFilterFactory *const filter_factory;

    StockItem *stock_item;
    SocketAddress current_address;

    const http_method_t method;
    const HttpAddress &address;
    HttpHeaders headers;
    UnusedHoldIstreamPtr body;

    unsigned retries;

    HttpResponseHandler &handler;
    CancellablePointer cancel_ptr;

    HttpRequest(struct pool &_pool, EventLoop &_event_loop,
                TcpBalancer &_tcp_balancer,
                unsigned _session_sticky,
                const SocketFilter *_filter,
                SocketFilterFactory *_filter_factory,
                http_method_t _method,
                const HttpAddress &_address,
                HttpHeaders &&_headers,
                Istream *_body,
                HttpResponseHandler &_handler,
                CancellablePointer &_cancel_ptr)
        :pool(_pool), event_loop(_event_loop), tcp_balancer(_tcp_balancer),
         session_sticky(_session_sticky),
         filter(_filter), filter_factory(_filter_factory),
         method(_method), address(_address),
         headers(std::move(_headers)), body(pool, _body),
         /* can only retry if there is no request body */
         retries(_body != nullptr ? 2 : 0),
         handler(_handler)
    {
        _cancel_ptr = *this;
    }

    void Destroy() {
        DeleteFromPool(pool, this);
    }

    void BeginConnect() {
        tcp_balancer_get(tcp_balancer, pool,
                         false, SocketAddress::Null(),
                         session_sticky,
                         address.addresses,
                         30,
                         *this, cancel_ptr);
    }

    void Failed(GError *error) {
        body.Clear();
        handler.InvokeError(error);
        Destroy();
    }

    /* virtual methods from class Cancellable */
    void Cancel() override {
        body.Clear();
        CancellablePointer c(std::move(cancel_ptr));
        Destroy();
        c.Cancel();
    }

    /* virtual methods from class StockGetHandler */
    void OnStockItemReady(StockItem &item) override;
    void OnStockItemError(GError *error) override;

private:
    /* virtual methods from class HttpResponseHandler */
    void OnHttpResponse(http_status_t status, StringMap &&headers,
                        Istream *body) override;
    void OnHttpError(GError *error) override;
};

/**
 * Is the specified error a server failure, that justifies
 * blacklisting the server for a while?
 */
static bool
is_server_failure(GError *error)
{
    return error->domain == http_client_quark() &&
        error->code != HTTP_CLIENT_UNSPECIFIED;
}

/*
 * HTTP response handler
 *
 */

void
HttpRequest::OnHttpResponse(http_status_t status, StringMap &&_headers,
                            Istream *_body)
{
    failure_unset(current_address, FAILURE_RESPONSE);

    handler.InvokeResponse(status, std::move(_headers), _body);
    Destroy();
}

void
HttpRequest::OnHttpError(GError *error)
{
    if (retries > 0 &&
        error->domain == http_client_quark() &&
        error->code == HTTP_CLIENT_REFUSED) {
        /* the server has closed the connection prematurely, maybe
           because it didn't want to get any further requests on that
           TCP connection.  Let's try again. */

        g_error_free(error);

        --retries;
        BeginConnect();
    } else {
        if (is_server_failure(error))
            failure_set(current_address, FAILURE_RESPONSE,
                        std::chrono::seconds(20));

        Failed(error);
    }
}

/*
 * stock callback
 *
 */

void
HttpRequest::OnStockItemReady(StockItem &item)
{
    stock_item = &item;
    current_address = tcp_balancer_get_last();

    void *filter_ctx = nullptr;
    if (filter_factory != nullptr) {
        try {
            filter_ctx = filter_factory->CreateFilter();
        } catch (const std::runtime_error &e) {
            item.Put(false);
            Failed(ToGError(e));
            return;
        }
    }

    auto *lease = NewFromPool<StockItemLease>(pool, item);

    http_client_request(pool, event_loop,
                        tcp_stock_item_get(item),
                        tcp_stock_item_get_domain(item) == AF_LOCAL
                        ? FdType::FD_SOCKET : FdType::FD_TCP,
                        *lease,
                        item.GetStockName(),
                        filter, filter_ctx,
                        method, address.path, std::move(headers),
                        body.Steal(), true,
                        *this, cancel_ptr);
}

void
HttpRequest::OnStockItemError(GError *error)
{
    Failed(error);
}

/*
 * constructor
 *
 */

void
http_request(struct pool &pool, EventLoop &event_loop,
             TcpBalancer &tcp_balancer,
             unsigned session_sticky,
             const SocketFilter *filter, SocketFilterFactory *filter_factory,
             http_method_t method,
             const HttpAddress &uwa,
             HttpHeaders &&headers,
             Istream *body,
             HttpResponseHandler &handler,
             CancellablePointer &_cancel_ptr)
{
    assert(uwa.host_and_port != nullptr);
    assert(uwa.path != nullptr);
    assert(body == nullptr || !body->HasHandler());

    auto hr = NewFromPool<HttpRequest>(pool, pool, event_loop, tcp_balancer,
                                       session_sticky, filter, filter_factory,
                                       method, uwa, std::move(headers), body,
                                       handler, _cancel_ptr);

    if (uwa.host_and_port != nullptr)
        hr->headers.Write("host", uwa.host_and_port);

    hr->headers.Write("connection", "keep-alive");

    hr->BeginConnect();
}
<commit_msg>http_request: use tcp_stock_item_get_address()<commit_after>/*
 * High level HTTP client.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "http_request.hxx"
#include "http_response.hxx"
#include "http_client.hxx"
#include "http_headers.hxx"
#include "http_address.hxx"
#include "header_writer.hxx"
#include "tcp_stock.hxx"
#include "tcp_balancer.hxx"
#include "stock/GetHandler.hxx"
#include "stock/Item.hxx"
#include "stock/Lease.hxx"
#include "failure.hxx"
#include "istream/istream.hxx"
#include "istream/UnusedHoldPtr.hxx"
#include "filtered_socket.hxx"
#include "pool.hxx"
#include "GException.hxx"
#include "net/SocketAddress.hxx"
#include "util/Cancellable.hxx"

#include <inline/compiler.h>

#include <string.h>

struct HttpRequest final
    : Cancellable, StockGetHandler, HttpResponseHandler {

    struct pool &pool;
    EventLoop &event_loop;

    TcpBalancer &tcp_balancer;

    const unsigned session_sticky;

    const SocketFilter *const filter;
    SocketFilterFactory *const filter_factory;

    StockItem *stock_item;

    const http_method_t method;
    const HttpAddress &address;
    HttpHeaders headers;
    UnusedHoldIstreamPtr body;

    unsigned retries;

    HttpResponseHandler &handler;
    CancellablePointer cancel_ptr;

    HttpRequest(struct pool &_pool, EventLoop &_event_loop,
                TcpBalancer &_tcp_balancer,
                unsigned _session_sticky,
                const SocketFilter *_filter,
                SocketFilterFactory *_filter_factory,
                http_method_t _method,
                const HttpAddress &_address,
                HttpHeaders &&_headers,
                Istream *_body,
                HttpResponseHandler &_handler,
                CancellablePointer &_cancel_ptr)
        :pool(_pool), event_loop(_event_loop), tcp_balancer(_tcp_balancer),
         session_sticky(_session_sticky),
         filter(_filter), filter_factory(_filter_factory),
         method(_method), address(_address),
         headers(std::move(_headers)), body(pool, _body),
         /* can only retry if there is no request body */
         retries(_body != nullptr ? 2 : 0),
         handler(_handler)
    {
        _cancel_ptr = *this;
    }

    void Destroy() {
        DeleteFromPool(pool, this);
    }

    void BeginConnect() {
        tcp_balancer_get(tcp_balancer, pool,
                         false, SocketAddress::Null(),
                         session_sticky,
                         address.addresses,
                         30,
                         *this, cancel_ptr);
    }

    void Failed(GError *error) {
        body.Clear();
        handler.InvokeError(error);
        Destroy();
    }

    /* virtual methods from class Cancellable */
    void Cancel() override {
        body.Clear();
        CancellablePointer c(std::move(cancel_ptr));
        Destroy();
        c.Cancel();
    }

    /* virtual methods from class StockGetHandler */
    void OnStockItemReady(StockItem &item) override;
    void OnStockItemError(GError *error) override;

private:
    /* virtual methods from class HttpResponseHandler */
    void OnHttpResponse(http_status_t status, StringMap &&headers,
                        Istream *body) override;
    void OnHttpError(GError *error) override;
};

/**
 * Is the specified error a server failure, that justifies
 * blacklisting the server for a while?
 */
static bool
is_server_failure(GError *error)
{
    return error->domain == http_client_quark() &&
        error->code != HTTP_CLIENT_UNSPECIFIED;
}

/*
 * HTTP response handler
 *
 */

void
HttpRequest::OnHttpResponse(http_status_t status, StringMap &&_headers,
                            Istream *_body)
{
    failure_unset(tcp_stock_item_get_address(*stock_item), FAILURE_RESPONSE);

    handler.InvokeResponse(status, std::move(_headers), _body);
    Destroy();
}

void
HttpRequest::OnHttpError(GError *error)
{
    if (retries > 0 &&
        error->domain == http_client_quark() &&
        error->code == HTTP_CLIENT_REFUSED) {
        /* the server has closed the connection prematurely, maybe
           because it didn't want to get any further requests on that
           TCP connection.  Let's try again. */

        g_error_free(error);

        --retries;
        BeginConnect();
    } else {
        if (is_server_failure(error))
            failure_set(tcp_stock_item_get_address(*stock_item),
                        FAILURE_RESPONSE,
                        std::chrono::seconds(20));

        Failed(error);
    }
}

/*
 * stock callback
 *
 */

void
HttpRequest::OnStockItemReady(StockItem &item)
{
    stock_item = &item;

    void *filter_ctx = nullptr;
    if (filter_factory != nullptr) {
        try {
            filter_ctx = filter_factory->CreateFilter();
        } catch (const std::runtime_error &e) {
            item.Put(false);
            Failed(ToGError(e));
            return;
        }
    }

    auto *lease = NewFromPool<StockItemLease>(pool, item);

    http_client_request(pool, event_loop,
                        tcp_stock_item_get(item),
                        tcp_stock_item_get_domain(item) == AF_LOCAL
                        ? FdType::FD_SOCKET : FdType::FD_TCP,
                        *lease,
                        item.GetStockName(),
                        filter, filter_ctx,
                        method, address.path, std::move(headers),
                        body.Steal(), true,
                        *this, cancel_ptr);
}

void
HttpRequest::OnStockItemError(GError *error)
{
    Failed(error);
}

/*
 * constructor
 *
 */

void
http_request(struct pool &pool, EventLoop &event_loop,
             TcpBalancer &tcp_balancer,
             unsigned session_sticky,
             const SocketFilter *filter, SocketFilterFactory *filter_factory,
             http_method_t method,
             const HttpAddress &uwa,
             HttpHeaders &&headers,
             Istream *body,
             HttpResponseHandler &handler,
             CancellablePointer &_cancel_ptr)
{
    assert(uwa.host_and_port != nullptr);
    assert(uwa.path != nullptr);
    assert(body == nullptr || !body->HasHandler());

    auto hr = NewFromPool<HttpRequest>(pool, pool, event_loop, tcp_balancer,
                                       session_sticky, filter, filter_factory,
                                       method, uwa, std::move(headers), body,
                                       handler, _cancel_ptr);

    if (uwa.host_and_port != nullptr)
        hr->headers.Write("host", uwa.host_and_port);

    hr->headers.Write("connection", "keep-alive");

    hr->BeginConnect();
}
<|endoftext|>


<commit_before>#include "statement.hpp"
namespace backend {

ret::ret(const std::shared_ptr<expression> &val)
    : statement(*this),
      m_val(val) {}

const expression& ret::val(void) const {
    return *m_val;
}

bind::bind(const std::shared_ptr<expression> &lhs,
           const std::shared_ptr<expression> &rhs)
    : statement(*this),
      m_lhs(lhs), m_rhs(rhs) {}

const expression& bind::lhs(void) const {
    return *m_lhs;
}
const expression& bind::rhs(void) const {
    return *m_rhs;
}

call::call(const std::shared_ptr<apply> &n)
    : statement(*this), m_sub(n) {}

const apply& call::sub(void) const {
    return *m_sub;
}

procedure::procedure(const std::shared_ptr<name> &id,
                     const std::shared_ptr<tuple> &args,
                     const std::shared_ptr<suite> &stmts,
                     const std::shared_ptr<type_t> &type,
                     const std::shared_ptr<ctype::type_t> &ctype,
                     const std::string &place)
        : statement(*this),
          m_id(id), m_args(args), m_stmts(stmts), m_type(type),
          m_ctype(ctype), m_place(place) {}

const name& procedure::id(void) const {
    return *m_id;
}

const tuple& procedure::args(void) const {
    return *m_args;
}

const suite& procedure::stmts(void) const {
    return *m_stmts;
}
const type_t& procedure::type(void) const {
    return *m_type;
}
const ctype::type_t& procedure::ctype(void) const {
    return *m_ctype;
}

const std::string& procedure::place(void) const {
    return m_place;
}

conditional::conditional(std::shared_ptr<expression> cond,
                         std::shared_ptr<suite> then,
                         std::shared_ptr<suite> orelse)
    : statement(*this), m_cond(cond),
      m_then(then), m_orelse(orelse) {}

const expression& conditional::cond(void) const {
        return *m_cond;
    }
const suite& conditional::then(void) const {
    return *m_then;
}
const suite& conditional::orelse(void) const {
        return *m_orelse;
}

suite::suite(std::vector<std::shared_ptr<statement> > &&stmts)
    : node(*this),
      m_stmts(std::move(stmts)) {}
suite::const_iterator suite::begin() const {
    return boost::make_indirect_iterator(m_stmts.cbegin());
}

suite::const_iterator suite::end() const {
    return boost::make_indirect_iterator(m_stmts.cend());
}

int suite::size() const {
    return m_stmts.size();
}

}

<commit_msg>Straggler.<commit_after>#include "statement.hpp"
namespace backend {

ret::ret(const std::shared_ptr<expression> &val)
    : statement(*this),
      m_val(val) {}

const expression& ret::val(void) const {
    return *m_val;
}

bind::bind(const std::shared_ptr<expression> &lhs,
           const std::shared_ptr<expression> &rhs)
    : statement(*this),
      m_lhs(lhs), m_rhs(rhs) {}

const expression& bind::lhs(void) const {
    return *m_lhs;
}
const expression& bind::rhs(void) const {
    return *m_rhs;
}

call::call(const std::shared_ptr<apply> &n)
    : statement(*this), m_sub(n) {}

const apply& call::sub(void) const {
    return *m_sub;
}

procedure::procedure(const std::shared_ptr<name> &id,
                     const std::shared_ptr<tuple> &args,
                     const std::shared_ptr<suite> &stmts,
                     const std::shared_ptr<type_t> &type,
                     const std::shared_ptr<ctype::type_t> &ctype,
                     const std::string &place)
        : statement(*this),
          m_id(id), m_args(args), m_stmts(stmts), m_type(type),
          m_ctype(ctype), m_place(place) {}

const name& procedure::id(void) const {
    return *m_id;
}

const tuple& procedure::args(void) const {
    return *m_args;
}

const suite& procedure::stmts(void) const {
    return *m_stmts;
}
const type_t& procedure::type(void) const {
    return *m_type;
}
const ctype::type_t& procedure::ctype(void) const {
    return *m_ctype;
}

std::shared_ptr<type_t> procedure::p_type(void) const {
    return m_type;
}

std::shared_ptr<ctype::type_t> procedure::p_ctype(void) const {
    return m_ctype;
}

const std::string& procedure::place(void) const {
    return m_place;
}

conditional::conditional(std::shared_ptr<expression> cond,
                         std::shared_ptr<suite> then,
                         std::shared_ptr<suite> orelse)
    : statement(*this), m_cond(cond),
      m_then(then), m_orelse(orelse) {}

const expression& conditional::cond(void) const {
        return *m_cond;
    }
const suite& conditional::then(void) const {
    return *m_then;
}
const suite& conditional::orelse(void) const {
        return *m_orelse;
}

suite::suite(std::vector<std::shared_ptr<statement> > &&stmts)
    : node(*this),
      m_stmts(std::move(stmts)) {}
suite::const_iterator suite::begin() const {
    return boost::make_indirect_iterator(m_stmts.cbegin());
}

suite::const_iterator suite::end() const {
    return boost::make_indirect_iterator(m_stmts.cend());
}

int suite::size() const {
    return m_stmts.size();
}

}

<|endoftext|>


<commit_before>#include <ncurses.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include "key_aliases.hh"

std::string prompt_for_test(const std::string& message, unsigned int y) {
    std::string text;
    int b_y,b_x,
        x = 0,
        xtrack = 0;
    getyx(stdscr,b_y,b_x);

    move(y,x);
    printw("%s",message.c_str());
    x += message.length();
    move(y,x);

    while(true) {
        std::string str;
        char c;
        while(true) {
            switch(getch()) {
            case ERR:
                std::cout << "ERROR character: " << ERR;
                endwin();
                exit(2);
                break;
            case _escape:
                // timeout(0);//if waiting char then get
                // char ch = getch();
                // if(ch == -1) {
                move(b_y,b_x);
                return "";
                // }
                // timeout(-1);
                break;
            default:
                move(y, ++xtrack);
                addch(c);
                str += c;
                break;
            }
        }
    }

    return text;
}

std::string prompt_for_test(const std::string& message) {
    int y,x;
    getmaxyx(stdscr,y,x);
    return prompt_for_test(message,y-1);
}
<commit_msg>Fixed prompt functions<commit_after>#include <iostream>
#include <ncurses.h>
#include <stdlib.h>
#include <string>

#include "key_aliases.hh"

std::string prompt(const std::string& message, unsigned int y) {
    std::string text;
    int b_y,b_x,
        x = 0,
        xtrack = 0;
    getyx(stdscr,b_y,b_x);

    move(y,x);
    printw("%s",message.c_str());
    x += message.length();
    move(y,x);

    while(true) {
        char c = getch();
        switch(c) {
        case ERR:
            std::cout << "ERROR character: " << ERR;
            endwin();
            exit(2);
            break;
        case _escape:
            move(b_y,b_x);
            return "";
        case '\n':
            move(b_y,b_x);
            return text;
        default:
            move(y, ++xtrack);
            addch(c);
            text += c;
            break;
        }
    }

    return text;
}

std::string prompt(const std::string& message) {
    int y,x;
    getmaxyx(stdscr,y,x);
    return prompt(message,y-1);
}
<|endoftext|>


<commit_before>#include "tcpserver.h"
#include "timer.h"
#include "llist.h"
#include "log.h"
#include "socketops.h"
#include <time.h>
#include <assert.h>
#include <signal.h>

#define EVENT_TOTAL_COUNT	100000
#define MAX_DESCRIPTORS     100000

bool tcpserver::run_ = true;

tcpserver::tcpserver()
{
    countfd_ = 0;
    fdindex_ = 0;
    handles_ = NULL;
}

tcpserver::~tcpserver()
{
    socketops::myclose(listenfd_);
    socketops::myclose(epollfd_);
    free(epollevarr_);
    free(handles_);
}

void tcpserver::sighandler(int signum)
{
    if(signum == SIGTERM || signum == SIGUSR1 || signum == SIGKILL)
    {
        log_error("recv signal: %d, process done...", signum);
        tcpserver::run_ = false;
    }
}

bool tcpserver::initsock(int listen_port)
{
	listenfd_ = socket(AF_INET, SOCK_STREAM, 0);
	if (listenfd_ == -1)
		return false;

    socketops::set_reuse(listenfd_);
	socketops::set_nonblock(listenfd_);

    int ret = socketops::mylisten(listenfd_, listen_port);
    if(ret < 0)
        return false;

	if(!init_event())
        return false;

	log_debug("server start running, listen:%d", listen_port);
	return true;
}

bool tcpserver::run()
{
	int loop_times = 0;
	const int timer_check_point = 10;

	while(run_)
	{
		int res = epoll_wait(epollfd_, epollevarr_, EVENT_TOTAL_COUNT, 100);
		if (res < 0) {
			if (EINTR == errno)
				continue;
			log_debug("epoll_wait return false, errno:%d, errstr:%s", errno, strerror(errno));
			break;
		}
		else if (0 == res) { //timeout
			loop_times = 0;
			run_timer();
		}
		else {
			if (++loop_times >= timer_check_point) {
				loop_times = 0;
				run_timer();
			}
		}

		for(int i=0; i<res; i++)
		{
			if(epollevarr_[i].data.fd == listenfd_)
			{
				handle_accept();
				continue;
			}
			int fd = (uint32_t)epollevarr_[i].data.u64; // mask out the lower 32 bits
			uint32 index = (uint32_t)(epollevarr_[i].data.u64 >> 32);
			tcphandler* s = handles_[fd];
			if( s == 0 || s->get_fd_index() != index )
			{
				continue;       // epoll returned invalid fd
			}
			if(epollevarr_[i].events & ( EPOLLHUP | EPOLLERR ))
			{
				handle_close(s);
				continue;
			}
			else if(epollevarr_[i].events & EPOLLIN)
			{
				if( s->handle_read() == -1 )
				{
					handle_close(s);
					continue;
				}
				if( s->writable() )
					want_to_write(s);
			}
			else if( epollevarr_[i].events & EPOLLOUT )
			{
				if( s->handle_output() == -1 )
				{
					handle_close(s);
					continue;
				}
				if( !s->writable() )
					want_to_read(s);
			}
		}
	}
	return true;
}

bool tcpserver::init_event()
{
    handles_ =  (tcphandler**)malloc(MAX_DESCRIPTORS * sizeof(void*));
    memset(handles_, 0, MAX_DESCRIPTORS * sizeof(void*));

	struct rlimit rl;
	int nfiles = MAX_DESCRIPTORS;
	if (getrlimit(RLIMIT_NOFILE, &rl) == 0 &&
		rl.rlim_cur != RLIM_INFINITY) {
			nfiles = rl.rlim_cur - 1;
	}
    if( nfiles > MAX_DESCRIPTORS )
        nfiles = MAX_DESCRIPTORS;

	log_debug("epoll create files:%d", nfiles);
	if (-1 == (epollfd_ = epoll_create(nfiles)))
		return false;

    // listen fd use ET mode
	struct epoll_event ev;
	ev.data.fd = listenfd_;
	ev.events = EPOLLIN | EPOLLET;
	epoll_ctl(epollfd_, EPOLL_CTL_ADD, listenfd_, &ev);

	epollevarr_ = (struct epoll_event*)malloc(EVENT_TOTAL_COUNT * sizeof(struct epoll_event));

    signal(SIGTERM, tcpserver::sighandler);
    signal(SIGUSR1, tcpserver::sighandler);
	signal(SIGKILL, tcpserver::sighandler);

	return true;
}

int tcpserver::handle_accept()
{
	SOCKET conn_fd;
    do
    {
        if((conn_fd = socketops::myaccept(listenfd_)) == -1)
        {
            break;
        }
        socketops::set_socketbuf(conn_fd,16*1024);
        if(socketops::set_nonblock(conn_fd) < 0)
        {
            log_error("SetNonblock faild \n");
            socketops::myclose(conn_fd);
            assert(false);
            continue;
        }
        if(socketops::set_keepalive(conn_fd) < 0)
        {
            log_error("set_keepalive faild \n");
            socketops::myclose(conn_fd);
            assert(false);
            continue;
        }

        tcphandler* sh = allocatehandler(conn_fd);
        if(sh == NULL)
        {
            log_error("sh is null \n");
            socketops::myclose(conn_fd);
            assert(false);
            continue;
        }
        addsocket(sh);
        sh->handle_connected();
    } while(conn_fd > 0);

	return 0;
}

void tcpserver::handle_close(tcphandler* pHandler)
{
    assert(pHandler != NULL);
    pHandler->handle_close();

    delsocket(pHandler);

    if(pHandler->getneeddel())
    {
        delete pHandler;
        pHandler = NULL;
    }
}

tcphandler* tcpserver::allocatehandler(SOCKET sock_fd)
{
	tcphandler* sh = createhandler();
	if(sh != NULL)
	{
        sh->setneeddel(true);
		sh->setfd(sock_fd);
		sh->server(this);
	}
	return sh;
}
bool tcpserver::disconnect(tcphandler * pSocketHandler)
{
    log_debug("disconnect \n");
    handle_close(pSocketHandler);
 	return true;
}
bool tcpserver::reg(tcphandler *pHandler)
{
    if(pHandler == NULL)
        return false;

    addsocket(pHandler);

    pHandler->server(this);
    pHandler->handle_connected();

	return true;
}

void tcpserver::addsocket(tcphandler * s)
{
    countfd_++;
    fdindex_++;

    s->set_fd_index(fdindex_);

    //log_debug("Add one fd:%d ,Cur handles_%d \n",s->getfd(),countfd_);

    assert( s->getfd() < MAX_DESCRIPTORS );
    assert(handles_[s->getfd()] == 0);
    handles_[s->getfd()] = s;

#ifdef WIN32
    FD_SET(s->getfd(), &m_rset);
    maxfd_ = (s->getfd() > maxfd_) ? s->getfd() : maxfd_;
#else
    struct epoll_event ev;
    memset(&ev, 0, sizeof(epoll_event));

    /* store the generation counter in the upper 32 bits, the fd in the lower 32 bits */
    ev.data.u64 = (uint64_t)(uint32)(s->getfd()) | ((uint64_t)(uint32)(s->get_fd_index()) << 32);

    ev.events = EPOLLIN;
    epoll_ctl(epollfd_, EPOLL_CTL_ADD, s->getfd(), &ev);
#endif
}

void tcpserver::delsocket(tcphandler * s)
{
    countfd_--;
    //log_debug("delete one fd: %d ,cur handles_: %d \n",s->getfd(),countfd_);

    assert(handles_[s->getfd()] == s);
    handles_[s->getfd()] = 0;

#ifdef WIN32
    FD_CLR(s->getfd(), &m_rset);
    FD_CLR(s->getfd(), &m_wset);
#else
    struct epoll_event ev;
    memset(&ev, 0, sizeof(epoll_event));
    ev.data.u64 = (uint64_t)(uint32)(s->getfd()) | ((uint64_t)(uint32)(s->get_fd_index()) << 32);

    ev.events =  EPOLLOUT | EPOLLIN;

    epoll_ctl(epollfd_, EPOLL_CTL_DEL, s->getfd(), &ev);
#endif
    socketops::myclose(s->getfd());
}

void tcpserver::want_to_write(tcphandler * s)
{
#ifndef WIN32
    struct epoll_event ev;
    memset(&ev, 0, sizeof(epoll_event));
    ev.data.u64 = (uint64_t)(uint32)(s->getfd()) | ((uint64_t)(uint32)(s->get_fd_index()) << 32);

    ev.events = EPOLLOUT ;
    epoll_ctl(epollfd_, EPOLL_CTL_MOD, s->getfd(), &ev);
#endif
}
void tcpserver::want_to_read(tcphandler * s)
{
#ifndef WIN32
    struct epoll_event ev;
    memset(&ev, 0, sizeof(epoll_event));
    ev.data.u64 = (uint64_t)(uint32)(s->getfd()) | ((uint64_t)(uint32)(s->get_fd_index()) << 32);

    ev.events = EPOLLIN ;
    epoll_ctl(epollfd_, EPOLL_CTL_MOD, s->getfd(), &ev);
#endif
}
<commit_msg>rename<commit_after>#include "tcpserver.h"
#include "timer.h"
#include "llist.h"
#include "log.h"
#include "socketops.h"
#include <time.h>
#include <assert.h>
#include <signal.h>

#define EVENT_TOTAL_COUNT	100000
#define MAX_DESCRIPTORS     100000

bool tcpserver::run_ = true;

tcpserver::tcpserver()
{
    countfd_ = 0;
    fdindex_ = 0;
    handles_ = NULL;
}

tcpserver::~tcpserver()
{
    socketops::myclose(listenfd_);
    socketops::myclose(epollfd_);
    free(epollevarr_);
    free(handles_);
}

void tcpserver::sighandler(int signum)
{
    if(signum == SIGTERM || signum == SIGUSR1 || signum == SIGKILL)
    {
        log_error("recv signal: %d, process done...", signum);
        tcpserver::run_ = false;
    }
}

bool tcpserver::initsock(int listen_port)
{
	listenfd_ = socket(AF_INET, SOCK_STREAM, 0);
	if (listenfd_ == -1)
		return false;

    socketops::set_reuse(listenfd_);
	socketops::set_nonblock(listenfd_);

    int ret = socketops::mylisten(listenfd_, listen_port);
    if(ret < 0)
        return false;

	if(!init_event())
        return false;

	log_debug("server start running, listen:%d", listen_port);
	return true;
}

bool tcpserver::run()
{
	int loop_times = 0;
	const int timer_check_point = 10;

	while(run_)
	{
		int res = epoll_wait(epollfd_, epollevarr_, EVENT_TOTAL_COUNT, 100);
		if (res < 0) {
			if (EINTR == errno)
				continue;
			log_debug("epoll_wait return false, errno:%d, errstr:%s", errno, strerror(errno));
			break;
		}
		else if (0 == res) { //timeout
			loop_times = 0;
			run_timer();
		}
		else {
			if (++loop_times >= timer_check_point) {
				loop_times = 0;
				run_timer();
			}
		}

		for(int i=0; i<res; i++)
		{
			if(epollevarr_[i].data.fd == listenfd_)
			{
				handle_accept();
				continue;
			}
			int fd = (uint32_t)epollevarr_[i].data.u64; // mask out the lower 32 bits
			uint32 index = (uint32_t)(epollevarr_[i].data.u64 >> 32);
			tcphandler* s = handles_[fd];
			if( s == 0 || s->get_fd_index() != index )
			{
				continue;       // epoll returned invalid fd
			}
			if(epollevarr_[i].events & ( EPOLLHUP | EPOLLERR ))
			{
				handle_close(s);
				continue;
			}
			else if(epollevarr_[i].events & EPOLLIN)
			{
				if( s->handle_read() == -1 )
				{
					handle_close(s);
					continue;
				}
				if( s->writable() )
					want_to_write(s);
			}
			else if( epollevarr_[i].events & EPOLLOUT )
			{
				if( s->handle_output() == -1 )
				{
					handle_close(s);
					continue;
				}
				if( !s->writable() )
					want_to_read(s);
			}
		}
	}
	return true;
}

bool tcpserver::init_event()
{
    handles_ =  (tcphandler**)malloc(MAX_DESCRIPTORS * sizeof(void*));
    memset(handles_, 0, MAX_DESCRIPTORS * sizeof(void*));

	struct rlimit rl;
	int nfiles = MAX_DESCRIPTORS;
	if (getrlimit(RLIMIT_NOFILE, &rl) == 0 &&
		rl.rlim_cur != RLIM_INFINITY) {
			nfiles = rl.rlim_cur - 1;
	}
    if( nfiles > MAX_DESCRIPTORS )
        nfiles = MAX_DESCRIPTORS;

	log_debug("epoll create files:%d", nfiles);
	if (-1 == (epollfd_ = epoll_create(nfiles)))
		return false;

    // listen fd use ET mode
	struct epoll_event ev;
	ev.data.fd = listenfd_;
	ev.events = EPOLLIN | EPOLLET;
	epoll_ctl(epollfd_, EPOLL_CTL_ADD, listenfd_, &ev);

	epollevarr_ = (struct epoll_event*)malloc(EVENT_TOTAL_COUNT * sizeof(struct epoll_event));

    signal(SIGTERM, tcpserver::sighandler);
    signal(SIGUSR1, tcpserver::sighandler);
	signal(SIGKILL, tcpserver::sighandler);

	return true;
}

int tcpserver::handle_accept()
{
	SOCKET conn_fd;
    do
    {
        if((conn_fd = socketops::myaccept(listenfd_)) == -1)
        {
            break;
        }
        socketops::set_socketbuf(conn_fd,16*1024);
        if(socketops::set_nonblock(conn_fd) < 0)
        {
            log_error("set nonblock failure");
            socketops::myclose(conn_fd);
            assert(false);
            continue;
        }
        if(socketops::set_keepalive(conn_fd) < 0)
        {
            log_error("set keepalive failure");
            socketops::myclose(conn_fd);
            assert(false);
            continue;
        }
        tcphandler* sh = allocatehandler(conn_fd);
        if(sh == NULL)
        {
            log_error("allocate tcphandler failure");
            socketops::myclose(conn_fd);
            assert(false);
            continue;
        }
        addsocket(sh);
        sh->handle_connected();
    } while(conn_fd > 0);

	return 0;
}

void tcpserver::handle_close(tcphandler* pHandler)
{
    assert(pHandler != NULL);
    pHandler->handle_close();

    delsocket(pHandler);

    if(pHandler->getneeddel())
    {
        delete pHandler;
        pHandler = NULL;
    }
}

tcphandler* tcpserver::allocatehandler(SOCKET sock_fd)
{
	tcphandler* sh = createhandler();
	if(sh != NULL)
	{
        sh->setneeddel(true);
		sh->setfd(sock_fd);
		sh->server(this);
	}
	return sh;
}
bool tcpserver::disconnect(tcphandler * pSocketHandler)
{
    log_debug("disconnect");
    handle_close(pSocketHandler);
 	return true;
}
bool tcpserver::reg(tcphandler *pHandler)
{
    if(pHandler == NULL)
        return false;

    addsocket(pHandler);

    pHandler->server(this);
    pHandler->handle_connected();

	return true;
}

void tcpserver::addsocket(tcphandler * s)
{
    countfd_++;
    fdindex_++;

    s->set_fd_index(fdindex_);

    //log_debug("Add one fd:%d ,Cur handles_%d \n",s->getfd(),countfd_);

    assert( s->getfd() < MAX_DESCRIPTORS );
    assert(handles_[s->getfd()] == 0);
    handles_[s->getfd()] = s;

    struct epoll_event ev;
    memset(&ev, 0, sizeof(epoll_event));

    /* store the generation counter in the upper 32 bits, the fd in the lower 32 bits */
    ev.data.u64 = (uint64_t)(uint32)(s->getfd()) | ((uint64_t)(uint32)(s->get_fd_index()) << 32);

    ev.events = EPOLLIN;
    epoll_ctl(epollfd_, EPOLL_CTL_ADD, s->getfd(), &ev);
}

void tcpserver::delsocket(tcphandler * s)
{
    countfd_--;
    //log_debug("delete one fd: %d ,cur handles_: %d \n",s->getfd(),countfd_);

    assert(handles_[s->getfd()] == s);
    handles_[s->getfd()] = 0;

#ifdef WIN32
    FD_CLR(s->getfd(), &m_rset);
    FD_CLR(s->getfd(), &m_wset);
#else
    struct epoll_event ev;
    memset(&ev, 0, sizeof(epoll_event));
    ev.data.u64 = (uint64_t)(uint32)(s->getfd()) | ((uint64_t)(uint32)(s->get_fd_index()) << 32);

    ev.events =  EPOLLOUT | EPOLLIN;

    epoll_ctl(epollfd_, EPOLL_CTL_DEL, s->getfd(), &ev);
#endif
    socketops::myclose(s->getfd());
}

void tcpserver::want_to_write(tcphandler * s)
{
#ifndef WIN32
    struct epoll_event ev;
    memset(&ev, 0, sizeof(epoll_event));
    ev.data.u64 = (uint64_t)(uint32)(s->getfd()) | ((uint64_t)(uint32)(s->get_fd_index()) << 32);

    ev.events = EPOLLOUT ;
    epoll_ctl(epollfd_, EPOLL_CTL_MOD, s->getfd(), &ev);
#endif
}
void tcpserver::want_to_read(tcphandler * s)
{
#ifndef WIN32
    struct epoll_event ev;
    memset(&ev, 0, sizeof(epoll_event));
    ev.data.u64 = (uint64_t)(uint32)(s->getfd()) | ((uint64_t)(uint32)(s->get_fd_index()) << 32);

    ev.events = EPOLLIN ;
    epoll_ctl(epollfd_, EPOLL_CTL_MOD, s->getfd(), &ev);
#endif
}
<|endoftext|>


<commit_before>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/CopasiTime.cpp,v $
   $Revision: 1.9 $
   $Name:  $
   $Author: shoops $
   $Date: 2005/01/28 16:13:09 $
   End CVS Header */

#include <sstream>
#include <time.h>

#include "copasi.h"
#include "CopasiTime.h"
#include "utility.h"

CCopasiTimeVariable::CCopasiTimeVariable():
    mTime(LLONG_CONST(0))
{}

CCopasiTimeVariable::CCopasiTimeVariable(const CCopasiTimeVariable & src):
    mTime(src.mTime)
{}

CCopasiTimeVariable::CCopasiTimeVariable(const C_INT64 & value):
    mTime(value)
{}

CCopasiTimeVariable::~CCopasiTimeVariable() {}

CCopasiTimeVariable CCopasiTimeVariable::operator + (const CCopasiTimeVariable & value)
{return mTime + value.mTime;}

CCopasiTimeVariable CCopasiTimeVariable::operator - (const CCopasiTimeVariable & value)
{return mTime - value.mTime;}

CCopasiTimeVariable & CCopasiTimeVariable::operator = (const CCopasiTimeVariable & rhs)
{
  mTime = rhs.mTime;
  return *this;
}

CCopasiTimeVariable & CCopasiTimeVariable::operator = (const C_INT64 & value)
{
  mTime = value;
  return *this;
}

bool CCopasiTimeVariable::operator < (const CCopasiTimeVariable & value)
{return (mTime < value.mTime);}

std::string CCopasiTimeVariable::isoFormat() const
  {
    std::stringstream Iso;
    bool first = true;

    if (mTime < LLONG_CONST(0))
      {
        CCopasiTimeVariable Tmp(-mTime);
        Iso << "-";
        Iso << Tmp.isoFormat();

        return Iso.str();
      }

    if (mTime >= LLONG_CONST(86400000000))
      {
        Iso << LL2String(getDays()) << ":";
        first = false;
      }

    if (mTime >= LLONG_CONST(3600000000))
      Iso << LL2String(getHours(true), first ? 0 : 2) << ":";
    if (mTime >= LLONG_CONST(60000000))
      Iso << LL2String(getMinutes(true), first ? 0 : 2) << ":";
    if (mTime >= LLONG_CONST(1000000))
      Iso << LL2String(getSeconds(true), first ? 0 : 2) << ".";
    else
      Iso << "0.";

    Iso << LL2String(getMilliSeconds(true), 3) << LL2String(getMicroSeconds(true), 3);

    return Iso.str();
  }

C_INT64 CCopasiTimeVariable::getMicroSeconds(const bool & bounded) const
  {
    if (bounded) return mTime % LLONG_CONST(1000);
    else return mTime;
  }

C_INT64 CCopasiTimeVariable::getMilliSeconds(const bool & bounded) const
  {
    C_INT64 MilliSeconds = mTime / LLONG_CONST(1000);

    if (bounded) return MilliSeconds % LLONG_CONST(1000);
    else return MilliSeconds;
  }

C_INT64 CCopasiTimeVariable::getSeconds(const bool & bounded) const
  {
    C_INT64 Seconds = mTime / LLONG_CONST(1000000);

    if (bounded) return Seconds % LLONG_CONST(60);
    else return Seconds;
  }

C_INT64 CCopasiTimeVariable::getMinutes(const bool & bounded) const
  {
    C_INT64 Minutes = mTime / LLONG_CONST(60000000);

    if (bounded) return Minutes % LLONG_CONST(60);
    else return Minutes;
  }

C_INT64 CCopasiTimeVariable::getHours(const bool & bounded) const
  {
    C_INT64 Hours = mTime / LLONG_CONST(3600000000);

    if (bounded) return Hours % LLONG_CONST(24);
    else return Hours;
  }

C_INT64 CCopasiTimeVariable::getDays() const
  {
    C_INT64 Days = mTime / LLONG_CONST(86400000000);

    return Days;
  }

#ifndef WIN32

#include <sys/time.h>

//static
CCopasiTimeVariable CCopasiTimeVariable::getCurrentWallTime()
{
  timeval ttt;
  gettimeofday(&ttt, 0);
  C_INT64 time;
  time = ((C_INT64) ttt.tv_sec) * LLONG_CONST(1000000) + (C_INT64) ttt.tv_usec;
  return time;
}
#else

#include <windows.h>
#include <winbase.h>

//static
CCopasiTimeVariable CCopasiTimeVariable::getCurrentWallTime()
{
  LARGE_INTEGER SystemTime;
  GetSystemTimeAsFileTime((FILETIME *) &SystemTime);

  return SystemTime.QuadPart / LLONG_CONST(10);
}
#endif

CCopasiTimeVariable CCopasiTimeVariable::getCPUTime()
{
#ifdef WIN32
  LARGE_INTEGER CreationTime;
  LARGE_INTEGER ExitTime;
  LARGE_INTEGER KernelTime;
  LARGE_INTEGER UserTime;

  GetProcessTimes(GetCurrentProcess(),
                  (FILETIME *) &CreationTime,
                  (FILETIME *) &ExitTime,
                  (FILETIME *) &KernelTime,
                  (FILETIME *) &UserTime);

  return UserTime.QuadPart / LLONG_CONST(10);

#else
  // :TODO: replace with a function with higher resolution
  return (C_INT64) clock() * LLONG_CONST(1000000) / (C_INT64) CLOCKS_PER_SEC;
}
#endif
}

std::string CCopasiTimeVariable::LL2String(const C_INT64 & value,
    const C_INT32 & digits)
{
  std::string format;

  if (digits > 0)
    format = "%0" + StringPrint("d", digits);
  else
    format = "%";

#ifdef WIN32
  format += "I64d";
#else
  format += "lld";
#endif

  return StringPrint(format.c_str(), value);
}
<commit_msg>Enhance getCPUTime for Unix environments.<commit_after>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/CopasiTime.cpp,v $
   $Revision: 1.10 $
   $Name:  $
   $Author: shoops $
   $Date: 2005/01/28 17:14:53 $
   End CVS Header */

#include <time.h>

#ifdef WIN32
# include <windows.h>
# include <winbase.h>
#else
# include <sys/time.h>
# include <sys/resource.h>
#endif // WIN32

#include <sstream>

#include "copasi.h"
#include "CopasiTime.h"
#include "utility.h"

CCopasiTimeVariable::CCopasiTimeVariable():
    mTime(LLONG_CONST(0))
{}

CCopasiTimeVariable::CCopasiTimeVariable(const CCopasiTimeVariable & src):
    mTime(src.mTime)
{}

CCopasiTimeVariable::CCopasiTimeVariable(const C_INT64 & value):
    mTime(value)
{}

CCopasiTimeVariable::~CCopasiTimeVariable() {}

CCopasiTimeVariable CCopasiTimeVariable::operator + (const CCopasiTimeVariable & value)
{return mTime + value.mTime;}

CCopasiTimeVariable CCopasiTimeVariable::operator - (const CCopasiTimeVariable & value)
{return mTime - value.mTime;}

CCopasiTimeVariable & CCopasiTimeVariable::operator = (const CCopasiTimeVariable & rhs)
{
  mTime = rhs.mTime;
  return *this;
}

CCopasiTimeVariable & CCopasiTimeVariable::operator = (const C_INT64 & value)
{
  mTime = value;
  return *this;
}

bool CCopasiTimeVariable::operator < (const CCopasiTimeVariable & value)
{return (mTime < value.mTime);}

std::string CCopasiTimeVariable::isoFormat() const
  {
    std::stringstream Iso;
    bool first = true;

    if (mTime < LLONG_CONST(0))
      {
        CCopasiTimeVariable Tmp(-mTime);
        Iso << "-";
        Iso << Tmp.isoFormat();

        return Iso.str();
      }

    if (mTime >= LLONG_CONST(86400000000))
      {
        Iso << LL2String(getDays()) << ":";
        first = false;
      }

    if (mTime >= LLONG_CONST(3600000000))
      Iso << LL2String(getHours(true), first ? 0 : 2) << ":";
    if (mTime >= LLONG_CONST(60000000))
      Iso << LL2String(getMinutes(true), first ? 0 : 2) << ":";
    if (mTime >= LLONG_CONST(1000000))
      Iso << LL2String(getSeconds(true), first ? 0 : 2) << ".";
    else
      Iso << "0.";

    Iso << LL2String(getMilliSeconds(true), 3) << LL2String(getMicroSeconds(true), 3);

    return Iso.str();
  }

C_INT64 CCopasiTimeVariable::getMicroSeconds(const bool & bounded) const
  {
    if (bounded) return mTime % LLONG_CONST(1000);
    else return mTime;
  }

C_INT64 CCopasiTimeVariable::getMilliSeconds(const bool & bounded) const
  {
    C_INT64 MilliSeconds = mTime / LLONG_CONST(1000);

    if (bounded) return MilliSeconds % LLONG_CONST(1000);
    else return MilliSeconds;
  }

C_INT64 CCopasiTimeVariable::getSeconds(const bool & bounded) const
  {
    C_INT64 Seconds = mTime / LLONG_CONST(1000000);

    if (bounded) return Seconds % LLONG_CONST(60);
    else return Seconds;
  }

C_INT64 CCopasiTimeVariable::getMinutes(const bool & bounded) const
  {
    C_INT64 Minutes = mTime / LLONG_CONST(60000000);

    if (bounded) return Minutes % LLONG_CONST(60);
    else return Minutes;
  }

C_INT64 CCopasiTimeVariable::getHours(const bool & bounded) const
  {
    C_INT64 Hours = mTime / LLONG_CONST(3600000000);

    if (bounded) return Hours % LLONG_CONST(24);
    else return Hours;
  }

C_INT64 CCopasiTimeVariable::getDays() const
  {
    C_INT64 Days = mTime / LLONG_CONST(86400000000);

    return Days;
  }

#ifndef WIN32

//static
CCopasiTimeVariable CCopasiTimeVariable::getCurrentWallTime()
{
  timeval ttt;
  gettimeofday(&ttt, 0);
  C_INT64 time;
  time = ((C_INT64) ttt.tv_sec) * LLONG_CONST(1000000) + (C_INT64) ttt.tv_usec;
  return time;
}
#else

//static
CCopasiTimeVariable CCopasiTimeVariable::getCurrentWallTime()
{
  LARGE_INTEGER SystemTime;
  GetSystemTimeAsFileTime((FILETIME *) &SystemTime);

  return SystemTime.QuadPart / LLONG_CONST(10);
}
#endif

CCopasiTimeVariable CCopasiTimeVariable::getCPUTime()
{
#ifdef WIN32
  LARGE_INTEGER CreationTime;
  LARGE_INTEGER ExitTime;
  LARGE_INTEGER KernelTime;
  LARGE_INTEGER UserTime;

  GetProcessTimes(GetCurrentProcess(),
                  (FILETIME *) &CreationTime,
                  (FILETIME *) &ExitTime,
                  (FILETIME *) &KernelTime,
                  (FILETIME *) &UserTime);

  return UserTime.QuadPart / LLONG_CONST(10);

#else
  struct rusage ResourceUsage;

  getrusage(RUSAGE_SELF, &ResourceUsage);

  return ((C_INT64) ResourceUsage.ru_utime.tv_sec) * LLONG_CONST(1000000)
  + (C_INT64) ResourceUsage.ru_utime.tv_usec;
#endif // WIN32
}

std::string CCopasiTimeVariable::LL2String(const C_INT64 & value,
    const C_INT32 & digits)
{
  std::string format;

  if (digits > 0)
    format = "%0" + StringPrint("d", digits);
  else
    format = "%";

#ifdef WIN32
  format += "I64d";
#else
  format += "lld";
#endif

  return StringPrint(format.c_str(), value);
}
<|endoftext|>


<commit_before>#include "riptide_controllers/alignment_controller.h"

#undef debug
#undef report
#undef progress
#define MAX_TASK_ID 1

int main(int argc, char **argv) {
  ros::init(argc, argv, "alignment_controller");
  AlignmentController ac;
  ros::spin();
}

// Function: UpdateError()
// Computes and publishes new commands based on incoming alignment data and
// target data. There is some clever stuff in here to deal with the two alignment
// planes we deal in.
void AlignmentController::UpdateError() {
  sample_duration = ros::Time::now() - sample_start;
  dt = sample_duration.toSec();

  error.y = (target.y - task.y);
  error_dot.y = (error.y - last_error.y) / dt;
  last_error.y = error.y;
  sway_cmd.data = y_pid.computeCommand(error.y, error_dot.y, sample_duration);

  // If we are aligning in the YZ plane (forward cam), then X acceleration is
  // dependent on bounding box width (approximation for distance from task), while
  // Z acceleration is determined by offset in the Z axis.
  // If we are aligning in the YX plane (downward cam), then Z acceleration is
  // dependent on boudning box width, while X acceleration is determined by offset
  // in the X axis.
  if (alignment_plane == riptide_msgs::AlignmentCommand::YZ) {
    error.z = (target.z - task.z);
    error.x = (target_bbox_width - task_bbox_width);
  } else if (alignment_plane == riptide_msgs::AlignmentCommand::YX) {
    error.z = (target_bbox_width - task_bbox_width);
    error.x = (target.x - task.x);
  }

  error_dot.x = (error.x - last_error.x) / dt;
  last_error.x = error.x;
  surge_cmd.data = x_pid.computeCommand(error.x, error_dot.x, sample_duration);

  error_dot.z = (error.z - last_error.z) / dt;
  last_error.z = error.z;
  heave_cmd.data = z_pid.computeCommand(error.z, error_dot.z, sample_duration);

  x_pub.publish(surge_cmd);
  y_pub.publish(sway_cmd);
  z_pub.publish(heave_cmd);

  sample_start = ros::Time::now();
}

// Constructor: AlignmentController()
AlignmentController::AlignmentController() {
    ros::NodeHandle surge("surge_controller");
    ros::NodeHandle sway("sway_controller");
    ros::NodeHandle heave("heave_controller");

    // Default to gate alignment
    alignment_sub = nh.subscribe<riptide_msgs::TaskAlignment>("task/gate/alignment", 1, &AlignmentController::AlignmentCB, this);
    command_sub = nh.subscribe<riptide_msgs::AlignmentCommand>("command/alignment", 1, &AlignmentController::CommandCB, this);

    x_pid.init(surge, false);
    y_pid.init(sway, false);
    z_pid.init(heave, false);

    x_pub = nh.advertise<std_msgs::Float32>("command/accel/linear/x", 1);
    y_pub = nh.advertise<std_msgs::Float32>("command/accel/linear/y", 1);
    z_pub = nh.advertise<std_msgs::Float32>("command/accel/linear/z", 1);

    sample_start = ros::Time::now();
}

// Function: UpdateTaskID
// Parameters: id - ID of the new task to subscribe to
//
void AlignmentController::UpdateTaskID(int id) {
  // Validate id
  if (id >= 0 && id < MAX_TASK_ID) {
    alignment_sub.shutdown(); // Unsubscribe from old task topic
    alignment_sub = nh.subscribe<riptide_msgs::TaskAlignment>(topics[current_task_id], 1, &AlignmentController::AlignmentCB, this);
    current_task_id = id;
  }
}

// Function: AlignmentCB
// Parameters: TaskAlignment msg
// Subscribe to state/vision/<task>/object_data to get relative position of task.
void AlignmentController::AlignmentCB(const riptide_msgs::TaskAlignment::ConstPtr &msg) {
  if (pid_initialized) {
    task.x = msg->relative_pos.x;
    task.y = msg->relative_pos.y;
    task.z = msg->relative_pos.z;

    // Boudning box width is always captured by the Y coordinate of the bounding box vertices.
    // This is because we only care about the YZ (forward cam) and YX (downward cam)
    // planes
    task_bbox_width = abs(msg->bbox.top_left.y - msg->bbox.bottom_right.y);

    AlignmentController::UpdateError();
  }
}

// Function: CommandCB
// Parameters: AlignmentCommand msg
// Subscribe to /command/alignment to get target alignment relative to task
void AlignmentController::CommandCB(const riptide_msgs::AlignmentCommand::ConstPtr &cmd) {
  alignment_plane = cmd->alignment_plane;

  target.x = cmd->target_pos.x;
  target.y = cmd->target_pos.y;
  target.z = cmd->target_pos.z;

  target_bbox_width = cmd->bbox_width;

  if (cmd->task_id != current_task_id) {
    AlignmentController::UpdateTaskID(cmd->task_id);
  }

  AlignmentController::UpdateError();

  if (!pid_initialized)
    pid_initialized = true;
}
<commit_msg>Added todo notes in alignment_controller<commit_after>#include "riptide_controllers/alignment_controller.h"

#undef debug
#undef report
#undef progress
#define MAX_TASK_ID 1

int main(int argc, char **argv) {
  ros::init(argc, argv, "alignment_controller");
  AlignmentController ac;
  ros::spin();
}

// Function: UpdateError()
// Computes and publishes new commands based on incoming alignment data and
// target data. There is some clever stuff in here to deal with the two alignment
// planes we deal in.
void AlignmentController::UpdateError() {
  sample_duration = ros::Time::now() - sample_start;
  dt = sample_duration.toSec();

  error.y = (target.y - task.y);
  error_dot.y = (error.y - last_error.y) / dt;
  last_error.y = error.y;
  sway_cmd.data = y_pid.computeCommand(error.y, error_dot.y, sample_duration);

  // If we are aligning in the YZ plane (forward cam), then X acceleration is
  // dependent on bounding box width (approximation for distance from task), while
  // Z acceleration is determined by offset in the Z axis.
  // If we are aligning in the YX plane (downward cam), then Z acceleration is
  // dependent on boudning box width, while X acceleration is determined by offset
  // in the X axis.
  if (alignment_plane == riptide_msgs::AlignmentCommand::YZ) {
    error.z = (target.z - task.z);
    error.x = (target_bbox_width - task_bbox_width);
  } else if (alignment_plane == riptide_msgs::AlignmentCommand::YX) {
    error.z = (target_bbox_width - task_bbox_width);
    error.x = (target.x - task.x);
  }

  error_dot.x = (error.x - last_error.x) / dt;
  last_error.x = error.x;
  surge_cmd.data = x_pid.computeCommand(error.x, error_dot.x, sample_duration);

  error_dot.z = (error.z - last_error.z) / dt;
  last_error.z = error.z;
  heave_cmd.data = z_pid.computeCommand(error.z, error_dot.z, sample_duration);

  x_pub.publish(surge_cmd);
  y_pub.publish(sway_cmd);
  z_pub.publish(heave_cmd);

  sample_start = ros::Time::now();
}

// Constructor: AlignmentController()
AlignmentController::AlignmentController() {
    ros::NodeHandle surge("surge_controller");
    ros::NodeHandle sway("sway_controller");
    ros::NodeHandle heave("heave_controller");

    // Default to gate alignment
    alignment_sub = nh.subscribe<riptide_msgs::TaskAlignment>("task/gate/alignment", 1, &AlignmentController::AlignmentCB, this);
    command_sub = nh.subscribe<riptide_msgs::AlignmentCommand>("command/alignment", 1, &AlignmentController::CommandCB, this);

    x_pid.init(surge, false);
    y_pid.init(sway, false);
    z_pid.init(heave, false);

    x_pub = nh.advertise<std_msgs::Float32>("command/accel/linear/x", 1);
    y_pub = nh.advertise<std_msgs::Float32>("command/accel/linear/y", 1);
    z_pub = nh.advertise<std_msgs::Float32>("command/accel/linear/z", 1);

    sample_start = ros::Time::now();
}

// Function: UpdateTaskID
// Parameters: id - ID of the new task to subscribe to
//
void AlignmentController::UpdateTaskID(int id) {
  // Validate id
  if (id >= 0 && id < MAX_TASK_ID) {
    alignment_sub.shutdown(); // Unsubscribe from old task topic
    current_task_id = id;
    alignment_sub = nh.subscribe<riptide_msgs::TaskAlignment>(topics[current_task_id], 1, &AlignmentController::AlignmentCB, this);

    // Notes:
    // 1. Reset previous controllers
    // 2. Add controller status messages
  }
}

// Function: AlignmentCB
// Parameters: TaskAlignment msg
// Subscribe to state/vision/<task>/object_data to get relative position of task.
void AlignmentController::AlignmentCB(const riptide_msgs::TaskAlignment::ConstPtr &msg) {
  if (pid_initialized) {
    task.x = msg->relative_pos.x;
    task.y = msg->relative_pos.y;
    task.z = msg->relative_pos.z;

    // Boudning box width is always captured by the Y coordinate of the bounding box vertices.
    // This is because we only care about the YZ (forward cam) and YX (downward cam)
    // planes
    task_bbox_width = abs(msg->bbox.top_left.y - msg->bbox.bottom_right.y);

    AlignmentController::UpdateError();
  }
}

// Function: CommandCB
// Parameters: AlignmentCommand msg
// Subscribe to /command/alignment to get target alignment relative to task
void AlignmentController::CommandCB(const riptide_msgs::AlignmentCommand::ConstPtr &cmd) {
  alignment_plane = cmd->alignment_plane;

  target.x = cmd->target_pos.x;
  target.y = cmd->target_pos.y;
  target.z = cmd->target_pos.z;

  target_bbox_width = cmd->bbox_width;

  if (cmd->task_id != current_task_id) {
    AlignmentController::UpdateTaskID(cmd->task_id);
  }

  AlignmentController::UpdateError();

  if (!pid_initialized)
    pid_initialized = true;
}
<|endoftext|>


<commit_before>#include "../tlang.h"
#include <taichi/util.h>
#include <taichi/visual/gui.h>
#include <taichi/system/profiler.h>
#include <taichi/visualization/particle_visualization.h>

TC_NAMESPACE_BEGIN

using namespace Tlang;

auto cnn = [](std::vector<std::string> cli_param) {
  CoreState::set_trigger_gdb_when_crash(true);
  auto param = parse_param(cli_param);
  auto path = param.get("grid_path", "");
  auto use_dense = param.get("use_dense", false);
  TC_P(path);
  TC_P(use_dense);

  auto f = fopen(path.c_str(), "rb");
  TC_ASSERT_INFO(f, "grid not found");
  int magic_number = -1;
  if (fread(&magic_number, sizeof(int), 1, f)) {
  }
  int n_dim = -1;
  if (fread(&n_dim, sizeof(int), 1, f)) {
  }
  int size = 1;
  for (int i = 0; i < n_dim; i++) {
    int d = -1;
    if (fread(&d, sizeof(int), 1, f)) {
    }
    size *= d;
  }
  float *data = new float[size];
  if (fread(data, sizeof(float), size, f)) {
  }
  fclose(f);

  Program prog(Arch::gpu);
  prog.config.lower_access = false;

  // constexpr int dim = 3;
  constexpr int n = 256;

  constexpr int num_ch1 = 16, num_ch2 = 16;

  int block_size = 4;

  Global(layer1, f32);
  Global(layer2, f32);
  Global(weights, f32);

  layout([&]() {
    auto ijkl = Indices(0, 1, 2, 3);
    if (use_dense) {
      root.dense(ijkl, {n, n, n, num_ch1}).place(layer1);
      root.dense(ijkl, {n, n, n, num_ch2}).place(layer2);
    } else {
      root.dense(ijkl, {n / block_size, n / block_size, n / block_size, 1})
          .bitmasked()
          .dense(ijkl, {block_size, block_size, block_size, num_ch1})
          .place(layer1);
      root.dense(ijkl, {n / block_size, n / block_size, n / block_size, 1})
          .bitmasked()
          .dense(ijkl, {block_size, block_size, block_size, num_ch2})
          .place(layer2);
    }
    root.dense(ijkl, {4, 4, 4, num_ch1 * num_ch2}).place(weights);
  });

  for (int c_in = 0; c_in < num_ch1; c_in++) {
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        for (int k = 0; k < n; k++) {
          float v = data[((c_in * n + k) * n + j) * n + i];
          if (v != 0) {
            layer1.val<float32>(i, j, k, c_in) = v;
          }
        }
      }
    }
  }
  delete[] data;

  Kernel(forward).def([&] {
    // Cache(0, layer1);
    BlockDim(128);
    For(layer2, [&](Expr i, Expr j, Expr k, Expr c_out) {
      auto sum = Var(0.0f);
      for (int c_in = 0; c_in < num_ch1; c_in++) {
        for (int dx = -1; dx < 2; dx++) {
          for (int dy = -1; dy < 2; dy++) {
            for (int dz = -1; dz < 2; dz++) {
              auto weight = weights[Expr(dx + 1), Expr(dy + 1), Expr(dz + 1),
                                    c_in * num_ch2 + c_out];
              auto c_in2 = AssumeInRange(c_in, c_out, 0, 1);
              sum += weight * layer1[i + dx, j + dy, k + dz, c_in2];
              // layer2[i, j, k, c_out] += weight * layer1[i + dx, j + dy, k +
              // dz, c_in];
            }
          }
        }
      }
      layer2[i, j, k, c_out] = sum;
    });
  });

  // expand blocks
  kernel([&] {
    kernel_name("dilate");
    For(layer1, [&](Expr i, Expr j, Expr k) {
      for (int x = -1; x < 2; x++) {
        for (int y = -1; y < 2; y++) {
          for (int z = -1; z < 2; z++) {
            layer2[i + x * block_size, j + y * block_size,
                   k + z * block_size] += 0.0f;  // simply activate the block
          }
        }
      }
    });
  })();

  for (int c_out = 0; c_out < num_ch2; c_out++) {
    for (int c_in = 0; c_in < num_ch1; c_in++) {
      float inc = 0.1f;
      for (int dx = -1; dx < 2; dx++) {
        for (int dy = -1; dy < 2; dy++) {
          for (int dz = -1; dz < 2; dz++) {
            if (dx == 0 && dy == 0 && dz == 0) {
              weights.val<float32>(dx + 1, dy + 1, dz + 1,
                                   c_in * num_ch2 + c_out) = 1.f / 16.f;
            } else {
              weights.val<float32>(dx + 1, dy + 1, dz + 1,
                                   c_in * num_ch2 + c_out) = 0.f;
            }
            inc += 0.1f;
          }
        }
      }
    }
  }

  // prog.config.print_ir = true;

  for (int i = 0; i < 20; i++) {
    forward();
  }
  prog.profiler_print();

  // Write the first layer of output
  data = new float[n * n * n];
  int non_zero = 0;
  int zero = 0;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      for (int k = 0; k < n; k++) {
        data[((0 * n + k) * n + j) * n + i] = layer2.val<float32>(i, j, k, 0);
        if (layer2.val<float32>(i, j, k, 0) != 0) {
          non_zero++;
        } else {
          zero++;
        }
      }
    }
  }
  std::cout << "Non zero:" << non_zero << ", zero:" << zero << std::endl;
  std::cerr << "Sparsity:" << (double)non_zero / (double)(non_zero + zero)
            << std::endl;
  auto f_out = fopen("our_output.bin", "wb");
  fwrite(data, sizeof(float), n * n * n, f_out);
  fclose(f_out);

#if 0
  int gui_res = 512;
  GUI gui("Sparse CNN", Vector2i(gui_res + 200, gui_res), false);
  int layer = 1;
  int k = 0;
  int channel = 0;
  gui.slider("z", k, 0, n - 1)
      .slider("Layer", layer, 1, 2)
      .slider("Channel", channel, 0, num_ch1);

  int scale = gui_res / n;
  auto &canvas = gui.get_canvas();
  for (int frame = 1;; frame++) {
    for (int i = 0; i < gui_res - scale; i++) {
      for (int j = 0; j < gui_res - scale; j++) {
        real dx;
        if (layer == 1) {
          dx = layer1.val<float32>(i / scale, j / scale, k, channel);
        } else {
          dx = layer2.val<float32>(i / scale, j / scale, k, channel);
        }
        canvas.img[i][j] = Vector4(0.5f) + Vector4(dx) * 0.5f;
      }
    }
    gui.update();
  }
#endif
};
TC_REGISTER_TASK(cnn);

TC_NAMESPACE_END
<commit_msg>optimize dilate<commit_after>#include "../tlang.h"
#include <taichi/util.h>
#include <taichi/visual/gui.h>
#include <taichi/system/profiler.h>
#include <taichi/visualization/particle_visualization.h>

TC_NAMESPACE_BEGIN

using namespace Tlang;

auto cnn = [](std::vector<std::string> cli_param) {
  CoreState::set_trigger_gdb_when_crash(true);
  auto param = parse_param(cli_param);
  auto path = param.get("grid_path", "");
  auto use_dense = param.get("use_dense", false);
  TC_P(path);
  TC_P(use_dense);

  auto f = fopen(path.c_str(), "rb");
  TC_ASSERT_INFO(f, "grid not found");
  int magic_number = -1;
  if (fread(&magic_number, sizeof(int), 1, f)) {
  }
  int n_dim = -1;
  if (fread(&n_dim, sizeof(int), 1, f)) {
  }
  int size = 1;
  for (int i = 0; i < n_dim; i++) {
    int d = -1;
    if (fread(&d, sizeof(int), 1, f)) {
    }
    size *= d;
  }
  float *data = new float[size];
  if (fread(data, sizeof(float), size, f)) {
  }
  fclose(f);

  Program prog(Arch::gpu);
  prog.config.lower_access = true;

  // constexpr int dim = 3;
  constexpr int n = 256;

  constexpr int num_ch1 = 16, num_ch2 = 16;

  int block_size = 4;

  Global(layer1, f32);
  Global(layer2, f32);
  Global(weights, f32);

  layout([&]() {
    auto ijkl = Indices(0, 1, 2, 3);
    if (use_dense) {
      root.dense(ijkl, {n, n, n, num_ch1}).place(layer1);
      root.dense(ijkl, {n, n, n, num_ch2}).place(layer2);
    } else {
      root.dense(ijkl, {n / block_size, n / block_size, n / block_size, 1})
          .bitmasked()
          .dense(ijkl, {block_size, block_size, block_size, num_ch1})
          .place(layer1);
      root.dense(ijkl, {n / block_size, n / block_size, n / block_size, 1})
          .bitmasked()
          .dense(ijkl, {block_size, block_size, block_size, num_ch2})
          .place(layer2);
    }
    root.dense(ijkl, {4, 4, 4, num_ch1 * num_ch2}).place(weights);
  });

  for (int c_in = 0; c_in < num_ch1; c_in++) {
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        for (int k = 0; k < n; k++) {
          float v = data[((c_in * n + k) * n + j) * n + i];
          if (v != 0) {
            layer1.val<float32>(i, j, k, c_in) = v;
          }
        }
      }
    }
  }
  delete[] data;

  Kernel(forward).def([&] {
    // Cache(0, layer1);
    BlockDim(256);
    For(layer2, [&](Expr i, Expr j, Expr k, Expr c_out) {
      auto sum = Var(0.0f);
      for (int c_in = 0; c_in < num_ch1; c_in++) {
        for (int dx = -1; dx < 2; dx++) {
          for (int dy = -1; dy < 2; dy++) {
            for (int dz = -1; dz < 2; dz++) {
              auto weight = weights[Expr(dx + 1), Expr(dy + 1), Expr(dz + 1),
                                    c_in * num_ch2 + c_out];
              auto c_in2 = AssumeInRange(c_in, c_out, 0, 1);
              sum += weight * layer1[i + dx, j + dy, k + dz, c_in2];
              // layer2[i, j, k, c_out] += weight * layer1[i + dx, j + dy, k +
              // dz, c_in];
            }
          }
        }
      }
      layer2[i, j, k, c_out] = sum;
    });
  });

  // expand blocks
  kernel([&] {
    kernel_name("dilate");
    For(layer1, [&](Expr i, Expr j, Expr k) {
      If(i % block_size == 0 && j % block_size == 0 && k % block_size == 0)
          .Then([&] {
            for (int x = -1; x < 2; x++) {
              for (int y = -1; y < 2; y++) {
                for (int z = -1; z < 2; z++) {
                  layer2[i + x * block_size, j + y * block_size,
                         k + z * block_size] =
                      0.0f;  // simply activate the block
                }
              }
            }
          });
    });
  })();

  for (int c_out = 0; c_out < num_ch2; c_out++) {
    for (int c_in = 0; c_in < num_ch1; c_in++) {
      float inc = 0.1f;
      for (int dx = -1; dx < 2; dx++) {
        for (int dy = -1; dy < 2; dy++) {
          for (int dz = -1; dz < 2; dz++) {
            if (dx == 0 && dy == 0 && dz == 0) {
              weights.val<float32>(dx + 1, dy + 1, dz + 1,
                                   c_in * num_ch2 + c_out) = 1.f / 16.f;
            } else {
              weights.val<float32>(dx + 1, dy + 1, dz + 1,
                                   c_in * num_ch2 + c_out) = 0.f;
            }
            inc += 0.1f;
          }
        }
      }
    }
  }

  // prog.config.print_ir = true;

  for (int i = 0; i < 20; i++) {
    forward();
  }
  prog.profiler_print();

  // Write the first layer of output
  data = new float[n * n * n];
  int non_zero = 0;
  int zero = 0;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      for (int k = 0; k < n; k++) {
        data[((0 * n + k) * n + j) * n + i] = layer2.val<float32>(i, j, k, 0);
        if (layer2.val<float32>(i, j, k, 0) != 0) {
          non_zero++;
        } else {
          zero++;
        }
      }
    }
  }
  std::cout << "Non zero:" << non_zero << ", zero:" << zero << std::endl;
  std::cerr << "Sparsity:" << (double)non_zero / (double)(non_zero + zero)
            << std::endl;
  auto f_out = fopen("our_output.bin", "wb");
  fwrite(data, sizeof(float), n * n * n, f_out);
  fclose(f_out);

#if 0
  int gui_res = 512;
  GUI gui("Sparse CNN", Vector2i(gui_res + 200, gui_res), false);
  int layer = 1;
  int k = 0;
  int channel = 0;
  gui.slider("z", k, 0, n - 1)
      .slider("Layer", layer, 1, 2)
      .slider("Channel", channel, 0, num_ch1);

  int scale = gui_res / n;
  auto &canvas = gui.get_canvas();
  for (int frame = 1;; frame++) {
    for (int i = 0; i < gui_res - scale; i++) {
      for (int j = 0; j < gui_res - scale; j++) {
        real dx;
        if (layer == 1) {
          dx = layer1.val<float32>(i / scale, j / scale, k, channel);
        } else {
          dx = layer2.val<float32>(i / scale, j / scale, k, channel);
        }
        canvas.img[i][j] = Vector4(0.5f) + Vector4(dx) * 0.5f;
      }
    }
    gui.update();
  }
#endif
};
TC_REGISTER_TASK(cnn);

TC_NAMESPACE_END
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: AccessiblePreviewHeaderCell.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-26 18:06:09 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SC_ACCESSIBLEPREVIEWHEADERCELL_HXX
#define _SC_ACCESSIBLEPREVIEWHEADERCELL_HXX

#ifndef _SC_ACCESSIBLECONTEXTBASE_HXX
#include "AccessibleContextBase.hxx"
#endif

#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEVALUE_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleValue.hpp>
#endif

#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

class ScPreviewShell;
class ScPreviewTableInfo;
class accessibility::AccessibleTextHelper;

typedef cppu::ImplHelper1< ::drafts::com::sun::star::accessibility::XAccessibleValue>
                    ScAccessiblePreviewHeaderCellImpl;

class ScAccessiblePreviewHeaderCell :
        public ScAccessibleContextBase,
        public ScAccessiblePreviewHeaderCellImpl
{
public:
    ScAccessiblePreviewHeaderCell( const ::com::sun::star::uno::Reference<
                                ::drafts::com::sun::star::accessibility::XAccessible>& rxParent,
                            ScPreviewShell* pViewShell,
                            const ScAddress& rCellPos, sal_Bool bIsColHdr, sal_Bool bIsRowHdr,
                            sal_Int32 nIndex );

protected:
    virtual ~ScAccessiblePreviewHeaderCell();

public:
     virtual void SAL_CALL disposing();

    //=====  SfxListener  =====================================================

    virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    ///=====  XInterface  =====================================================

    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
        ::com::sun::star::uno::Type const & rType )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL acquire() throw ();

    virtual void SAL_CALL release() throw ();

    //=====  XAccessibleValue  ================================================

    virtual ::com::sun::star::uno::Any SAL_CALL getCurrentValue() throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL setCurrentValue( const ::com::sun::star::uno::Any& aNumber )
                                throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getMaximumValue() throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getMinimumValue() throw (::com::sun::star::uno::RuntimeException);

    //=====  XAccessibleComponent  ============================================

    virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL
                            getAccessibleAt( const ::com::sun::star::awt::Point& aPoint )
                                throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL   grabFocus() throw (::com::sun::star::uno::RuntimeException);

    //=====  XAccessibleContext  ==============================================

    virtual sal_Int32 SAL_CALL getAccessibleChildCount() throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL
                            getAccessibleChild( sal_Int32 i )
                                throw (::com::sun::star::lang::IndexOutOfBoundsException,
                                    ::com::sun::star::uno::RuntimeException);
    virtual sal_Int32 SAL_CALL getAccessibleIndexInParent() throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL
                            getAccessibleStateSet() throw (::com::sun::star::uno::RuntimeException);

    //=====  XServiceInfo  ====================================================

    virtual ::rtl::OUString SAL_CALL getImplementationName()
                                throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
                                throw(::com::sun::star::uno::RuntimeException);

    ///=====  XTypeProvider  ===================================================

    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL
        getTypes()
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a implementation id.
    */
    virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL
        getImplementationId(void)
        throw (::com::sun::star::uno::RuntimeException);

protected:
    virtual ::rtl::OUString SAL_CALL createAccessibleDescription(void) throw(::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL createAccessibleName(void) throw (::com::sun::star::uno::RuntimeException);

    virtual Rectangle GetBoundingBoxOnScreen(void) const throw(::com::sun::star::uno::RuntimeException);
    virtual Rectangle GetBoundingBox(void) const throw (::com::sun::star::uno::RuntimeException);

private:
    ScPreviewShell*     mpViewShell;
    accessibility::AccessibleTextHelper* mpTextHelper;
    sal_Int32           mnIndex;
    ScAddress           maCellPos;
    sal_Bool            mbColumnHeader;
    sal_Bool            mbRowHeader;
    mutable ScPreviewTableInfo* mpTableInfo;

    sal_Bool IsDefunc(
        const com::sun::star::uno::Reference<
        ::drafts::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);

    void CreateTextHelper();
    void    FillTableInfo() const;
};

#endif
<commit_msg>INTEGRATION: CWS uaa02 (1.8.24); FILE MERGED 2003/04/22 08:15:01 mt 1.8.24.1: #108656# Moved Accessibility from drafts to final<commit_after>/*************************************************************************
 *
 *  $RCSfile: AccessiblePreviewHeaderCell.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-24 17:15:30 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SC_ACCESSIBLEPREVIEWHEADERCELL_HXX
#define _SC_ACCESSIBLEPREVIEWHEADERCELL_HXX

#ifndef _SC_ACCESSIBLECONTEXTBASE_HXX
#include "AccessibleContextBase.hxx"
#endif

#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEVALUE_HPP_
#include <com/sun/star/accessibility/XAccessibleValue.hpp>
#endif

#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

class ScPreviewShell;
class ScPreviewTableInfo;
class accessibility::AccessibleTextHelper;

typedef cppu::ImplHelper1< ::com::sun::star::accessibility::XAccessibleValue>
                    ScAccessiblePreviewHeaderCellImpl;

class ScAccessiblePreviewHeaderCell :
        public ScAccessibleContextBase,
        public ScAccessiblePreviewHeaderCellImpl
{
public:
    ScAccessiblePreviewHeaderCell( const ::com::sun::star::uno::Reference<
                                ::com::sun::star::accessibility::XAccessible>& rxParent,
                            ScPreviewShell* pViewShell,
                            const ScAddress& rCellPos, sal_Bool bIsColHdr, sal_Bool bIsRowHdr,
                            sal_Int32 nIndex );

protected:
    virtual ~ScAccessiblePreviewHeaderCell();

public:
     virtual void SAL_CALL disposing();

    //=====  SfxListener  =====================================================

    virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    ///=====  XInterface  =====================================================

    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
        ::com::sun::star::uno::Type const & rType )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL acquire() throw ();

    virtual void SAL_CALL release() throw ();

    //=====  XAccessibleValue  ================================================

    virtual ::com::sun::star::uno::Any SAL_CALL getCurrentValue() throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL setCurrentValue( const ::com::sun::star::uno::Any& aNumber )
                                throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getMaximumValue() throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getMinimumValue() throw (::com::sun::star::uno::RuntimeException);

    //=====  XAccessibleComponent  ============================================

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL
                            getAccessibleAtPoint( const ::com::sun::star::awt::Point& aPoint )
                                throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL   grabFocus() throw (::com::sun::star::uno::RuntimeException);

    //=====  XAccessibleContext  ==============================================

    virtual sal_Int32 SAL_CALL getAccessibleChildCount() throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL
                            getAccessibleChild( sal_Int32 i )
                                throw (::com::sun::star::lang::IndexOutOfBoundsException,
                                    ::com::sun::star::uno::RuntimeException);
    virtual sal_Int32 SAL_CALL getAccessibleIndexInParent() throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL
                            getAccessibleStateSet() throw (::com::sun::star::uno::RuntimeException);

    //=====  XServiceInfo  ====================================================

    virtual ::rtl::OUString SAL_CALL getImplementationName()
                                throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
                                throw(::com::sun::star::uno::RuntimeException);

    ///=====  XTypeProvider  ===================================================

    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL
        getTypes()
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a implementation id.
    */
    virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL
        getImplementationId(void)
        throw (::com::sun::star::uno::RuntimeException);

protected:
    virtual ::rtl::OUString SAL_CALL createAccessibleDescription(void) throw(::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL createAccessibleName(void) throw (::com::sun::star::uno::RuntimeException);

    virtual Rectangle GetBoundingBoxOnScreen(void) const throw(::com::sun::star::uno::RuntimeException);
    virtual Rectangle GetBoundingBox(void) const throw (::com::sun::star::uno::RuntimeException);

private:
    ScPreviewShell*     mpViewShell;
    accessibility::AccessibleTextHelper* mpTextHelper;
    sal_Int32           mnIndex;
    ScAddress           maCellPos;
    sal_Bool            mbColumnHeader;
    sal_Bool            mbRowHeader;
    mutable ScPreviewTableInfo* mpTableInfo;

    sal_Bool IsDefunc(
        const com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);

    void CreateTextHelper();
    void    FillTableInfo() const;
};

#endif
<|endoftext|>


<commit_before>/*
 *  This file is part of SKATRAK Playground.
 *
 *  SKATRAK Playground 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, see <http://www.gnu.org/licenses/> or
 *  write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
 *  Floor, Boston, MA 02110-1301 USA
 *
 *  Sergio M. Afonso Fumero <theSkatrak@gmail.com>
 */

#include <SKATRAK_PLAYGROUND.hpp>
#include <shared_attributes.hpp>
#include <snake/snakePiece.hpp>
#include <snake/snake.hpp>
#include <snake/snakeMap.hpp>

returnVal gameSnake(void*){
	// Inicializacin de la semilla
	srand(SDL_GetTicks());

	// Fondo de la pantalla
	SDL_Surface* screen = sistema->scr();
	image_t background("fondo_inicio_prueba.png");
	image_t foodImg("snake/serpiente_comida_prueba.png");

	// La serpiente
	snake_t snake;
	snake.setPos(10, 10, MOVE_RIGHT);
	snake.setImg("snake/serpiente_pruebav2.png", 32);
	int headX, headY, foodX = -1, foodY = -1;

	// Colocamos la primera comida
	foodX = rand() % (int)(sistema->width()/32);
	foodY = rand() % (int)(sistema->height()/32);

	// Game loop
	SDL_Event event;
	timekeeper_t timer;
	while(true){
		timer.refresh();
		while(SDL_PollEvent(&event)){
			switch(event.type){
			case SDL_KEYDOWN:
				switch(event.key.keysym.sym){
				case SDLK_UP:
					snake.turn(MOVE_UP);
					break;
				case SDLK_DOWN:
					snake.turn(MOVE_DOWN);
					break;
				case SDLK_LEFT:
					snake.turn(MOVE_LEFT);
					break;
				case SDLK_RIGHT:
					snake.turn(MOVE_RIGHT);
					break;
				case SDLK_ESCAPE:
					return ACTUAL_MENU;
				default: break;
				}
				break;
			case SDL_QUIT:
				return EXIT;
			default: break;
			}
		}
		// Lgica del juego
		if(timer.renderedFrames() == 2){
			timer.resetFrames();
			snake.step();
			if(snake.headPos(&headX, &headY) >= 0){
				if(headX >= (sistema->width()/32))
					snake.setHeadPos(0, headY);
				else if(headX < 0)
					snake.setHeadPos((sistema->width()/32)-1, headY);
				if(headY >= (sistema->height()/32))
					snake.setHeadPos(headX, 0);
				else if(headY < 0)
					snake.setHeadPos(headX, (sistema->height()/32)-1);
			}
			if(headX == foodX && headY == foodY){
				snake.addPiece(3);
				do {
					foodX = rand() % (int)(sistema->width()/32);
					foodY = rand() % (int)(sistema->height()/32);
				} while(foodX == headX && foodY == headY);
			}
			if(snake.checkCollision()){
				printf("Te mordiste la cola.\n");
				return ACTUAL_MENU;
			}
		}

		// Imprimir por pantalla
		background.blit(0, 0, screen);
		foodImg.blit(foodX*32, foodY*32, screen);
		snake.blit(0, 0, screen);
		sistema->update();
		timer.waitFramerate(30);
	}
}
<commit_msg>Snake de prueba utilizando lo desarrollado en los últimos días<commit_after>/*
 *  This file is part of SKATRAK Playground.
 *
 *  SKATRAK Playground 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, see <http://www.gnu.org/licenses/> or
 *  write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
 *  Floor, Boston, MA 02110-1301 USA
 *
 *  Sergio M. Afonso Fumero <theSkatrak@gmail.com>
 */

#include <SKATRAK_PLAYGROUND.hpp>
#include <shared_attributes.hpp>
#include <snake/snakePiece.hpp>
#include <snake/snake.hpp>
#include <snake/snakeMap.hpp>

returnVal gameSnake(void*){
	// Inicializacin de la semilla
	srand(SDL_GetTicks());

	// Fondo de la pantalla
	SDL_Surface* screen = sistema->scr();
	image_t background("fondo_inicio_prueba.png");

	// La serpiente
	snakeMap_t snakemap(10, 10, "snake/serpiente_mapa_fondo_prueba.png");
	snakemap.loadMapScheme("mapasnake_prueba.txt");
	snakemap.setSnakeImg("snake/serpiente_pruebav2.png", 32);
	snakemap.setFoodImg("snake/serpiente_comida_prueba.png");
	// Nmeros pequeos para probar su correcto funcionamiento
	snakemap.setFoodLimit(25);
	snakemap.setTimeLimit(150);

	// Game loop
	int puntuacion = 0;
	SDL_Event event;
	timekeeper_t timer;
	while(true){
		timer.refresh();
		while(SDL_PollEvent(&event)){
			switch(event.type){
			case SDL_KEYDOWN:
				switch(event.key.keysym.sym){
				case SDLK_UP:
					snakemap.turnSnake(MOVE_UP);
					break;
				case SDLK_DOWN:
					snakemap.turnSnake(MOVE_DOWN);
					break;
				case SDLK_LEFT:
					snakemap.turnSnake(MOVE_LEFT);
					break;
				case SDLK_RIGHT:
					snakemap.turnSnake(MOVE_RIGHT);
					break;
				case SDLK_ESCAPE:
					return ACTUAL_MENU;
				default: break;
				}
				break;
			case SDL_QUIT:
				return EXIT;
			default: break;
			}
		}
		// Lgica del juego
		if(timer.renderedFrames() == 5){
			timer.resetFrames();
			switch(snakemap.update()){
			case HIT_NONE:
				break;
			case HIT_BONUS:
				puntuacion += 5;	// Deliberadamente sin 'break' para que se sume ms a la puntuacin
			case HIT_NORMAL:
				puntuacion += 5;
				break;
			case HIT_DEATH:
				printf("Has muerto. Puntuacin: %d\n", puntuacion);
				return ACTUAL_MENU;
			case HIT_WARP:	// Aqu se podra cargar otro mapa, etc...
				printf("Has ganado. Puntuacin: %d\n", puntuacion);
				return MAIN;
			}
		}

		// Imprimir por pantalla
		background.blit(0, 0, screen);
		snakemap.blit(screen);
		sistema->update();
		timer.waitFramerate(30);
	}
}
<|endoftext|>


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

 Program: FEMUS
 Module: Writer
 Authors: Eugenio Aulisa, Simone Bnà, Giorgio Bornia

 Copyright (c) FEMTTU
 All rights reserved.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notice for more information.

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

#ifndef __femus_solution_Writer_hpp__
#define __femus_solution_Writer_hpp__

//----------------------------------------------------------------------------
// includes :
//----------------------------------------------------------------------------
#include <vector>
#include <string>
#include <memory>
#include "ParallelObject.hpp"
#include "WriterEnum.hpp"

namespace femus {

  //------------------------------------------------------------------------------
  // Forward declarations
  //------------------------------------------------------------------------------
  class MultiLevelMesh;
  class MultiLevelSolution;
  class SparseMatrix;
  class Vector;

  class Writer : public ParallelObject {

  public:

    /** Constructor. */
    Writer(MultiLevelSolution * ml_sol);

    /** Constructor. */
    Writer(MultiLevelMesh * ml_mesh);

    /** Destructor */
    virtual ~Writer();

    /** write output function */
    virtual void Write(const std::string output_path, const char order[], const std::vector < std::string > & vars = std::vector < std::string > (), const unsigned time_step = 0)  = 0;
    /** set moving mesh */
    void SetMovingMesh(std::vector<std::string>& movvars_in);

    /** runtime selection of writer for MLsol */
    static std::auto_ptr<Writer> build(const WriterEnum format, MultiLevelSolution * ml_sol);

    /** runtime selection of writer for MLmesh */
    static std::auto_ptr<Writer> build(const WriterEnum format, MultiLevelMesh * ml_mesh);

    virtual void SetDebugOutput( bool value ){
      std::cout<<"Warning this writer type does not have debug printing"<<std::endl;
    };

    void SetGraphVariable(const std::string &GraphVaraible);
    void UnsetGraphVariable(){ _graph = false;};

    void SetSurfaceVariables( std::vector < std::string > &surfaceVariable );
    void UnsetSurfaceVariables(){ _surface = false;};

  protected:

    /** a flag to move the output mesh */
    int _moving_mesh;

    /** the displacement variables for mesh moving */
    std::vector<std::string> _moving_vars;

    bool _graph;
    std::string _graphVariable;

    bool _surface;
    std::vector < std::string > _surfaceVariables;

    /** the multilevelsolution pointer */
    MultiLevelSolution* _ml_sol;

    /** the multilevel mesh */
    MultiLevelMesh* _ml_mesh;

    int _gridn;

    /** map from femus connectivity to vtk-connectivity for paraview visualization */
    static const unsigned FemusToVTKorToXDMFConn[27];

  private:

  };

} //end namespace femus

#endif
<commit_msg>fixed issues<commit_after>/*=========================================================================

 Program: FEMUS
 Module: Writer
 Authors: Eugenio Aulisa, Simone Bnà, Giorgio Bornia

 Copyright (c) FEMTTU
 All rights reserved.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notice for more information.

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

#ifndef __femus_solution_Writer_hpp__
#define __femus_solution_Writer_hpp__

//----------------------------------------------------------------------------
// includes :
//----------------------------------------------------------------------------
#include <vector>
#include <string>
#include <memory>
#include <iostream>
#include "ParallelObject.hpp"
#include "WriterEnum.hpp"

namespace femus {

  //------------------------------------------------------------------------------
  // Forward declarations
  //------------------------------------------------------------------------------
  class MultiLevelMesh;
  class MultiLevelSolution;
  class SparseMatrix;
  class Vector;

  class Writer : public ParallelObject {

  public:

    /** Constructor. */
    Writer(MultiLevelSolution * ml_sol);

    /** Constructor. */
    Writer(MultiLevelMesh * ml_mesh);

    /** Destructor */
    virtual ~Writer();

    /** write output function */
    virtual void Write(const std::string output_path, const char order[], const std::vector < std::string > & vars = std::vector < std::string > (), const unsigned time_step = 0)  = 0;
    /** set moving mesh */
    void SetMovingMesh(std::vector<std::string>& movvars_in);

    /** runtime selection of writer for MLsol */
    static std::auto_ptr<Writer> build(const WriterEnum format, MultiLevelSolution * ml_sol);

    /** runtime selection of writer for MLmesh */
    static std::auto_ptr<Writer> build(const WriterEnum format, MultiLevelMesh * ml_mesh);

    virtual void SetDebugOutput( bool value ){
      std::cout<<"Warning this writer type does not have debug printing"<<std::endl;
    };

    void SetGraphVariable(const std::string &GraphVaraible);
    void UnsetGraphVariable(){ _graph = false;};

    void SetSurfaceVariables( std::vector < std::string > &surfaceVariable );
    void UnsetSurfaceVariables(){ _surface = false;};

  protected:

    /** a flag to move the output mesh */
    int _moving_mesh;

    /** the displacement variables for mesh moving */
    std::vector<std::string> _moving_vars;

    bool _graph;
    std::string _graphVariable;

    bool _surface;
    std::vector < std::string > _surfaceVariables;

    /** the multilevelsolution pointer */
    MultiLevelSolution* _ml_sol;

    /** the multilevel mesh */
    MultiLevelMesh* _ml_mesh;

    int _gridn;

    /** map from femus connectivity to vtk-connectivity for paraview visualization */
    static const unsigned FemusToVTKorToXDMFConn[27];

  private:

  };

} //end namespace femus

#endif
<|endoftext|>