<commit_before>// Copyright (c) 2013-2014 Quanta Research Cambridge, Inc.

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

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

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

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/un.h>
#include <pthread.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <poll.h>

#include "portal.h"
#include "sock_utils.h"

#define MAX_FD_ARRAY 10

static struct {
    struct memrequest req;
    int sockfd;
    int valid;
    int inflight;
} head;
static struct memresponse respitem;
static int trace_port;// = 1;
static int fd_array[MAX_FD_ARRAY];
static int fd_array_index = 0;

static void *pthread_worker(void *p)
{
    int listening_socket = init_listening(SOCKET_NAME, NULL);
    if (trace_port)
        fprintf(stderr, "%s[%d]: waiting for a connection...\n",__FUNCTION__, listening_socket);
    while (1) {
        int sockfd = accept(listening_socket, NULL, NULL);
        if (sockfd == -1) {
            fprintf(stderr, "%s[%d]: accept error %s\n",__FUNCTION__, listening_socket, strerror(errno));
	    return 0;
        }
        if (trace_port)
            printf("[%s:%d] sockfd %d\n", __FUNCTION__, __LINE__, sockfd);
        fd_array[fd_array_index++] = sockfd;
    }
    return 0;
}

extern "C" void initPortal(void)
{
    pthread_t threaddata;
    pthread_create(&threaddata, NULL, &pthread_worker, NULL);
}

extern "C" void interruptLevel(uint32_t ivalue)
{
    static struct memresponse respitem;
    int i;
    if (ivalue != respitem.data) {
        respitem.portal = MAGIC_PORTAL_FOR_SENDING_INTERRUPT;
        respitem.data = ivalue;
        if (trace_port)
            printf("%s: %d\n", __FUNCTION__, ivalue);
        for (i = 0; i < fd_array_index; i++)
           portalSendFd(fd_array[i], &respitem, sizeof(respitem), -1);
    }
}

#if 0
static unsigned long long int rdtsc(void)
{
   unsigned long long int x;
   unsigned a, d;

   __asm__ volatile("rdtsc" : "=a" (a), "=d" (d));

   return ((unsigned long long)a) | (((unsigned long long)d) << 32);;
}
#endif
extern "C" bool checkForRequest(uint32_t rr)
{
#if 0
static int counter;
static int timeoutcount;
static int last_short;
static long long last_val;
long long this_val = rdtsc();
last_val = (this_val - last_val)/1000;
counter++;
if (last_val <= 3)
   last_short++;
if (last_short == 2) {
timeoutcount++;
    last_short = 0;
    struct timeval timeout;
    timeout.tv_sec = 0;
    timeout.tv_usec = 10000;
    select(0, NULL, NULL, NULL, &timeout);
}
last_val = this_val;
#endif
    if (!head.valid){
	int rv = -1, i, recvfd;
        for (i = 0; i < fd_array_index; i++) {
            head.sockfd = fd_array[i];
            rv = portalRecvFd(head.sockfd, &head.req, sizeof(head.req), &recvfd);
	    if(rv > 0){
	        assert(rv == sizeof(memrequest));
	        respitem.portal = head.req.portal;
	        head.valid = 1;
	        head.inflight = 1;
                if (recvfd != -1)
                    head.req.data_or_tag = recvfd;
	        if(trace_port)
	            fprintf(stderr, "processr p=%d w=%d, a=%8lx, dt=%8x:",
		        head.req.portal, head.req.write_flag, (long)head.req.addr, head.req.data_or_tag);
                break;
	    }
        }
    }
    return head.valid && head.inflight == 1 && head.req.write_flag == (int)rr;
}

extern "C" unsigned long long getRequest32(uint32_t rr)
{
    if(trace_port)
        fprintf(stderr, " get%c", rr ? '\n' : ':');
    if (rr)
        head.valid = 0;
    head.inflight = 0;
    return (((unsigned long long)head.req.data_or_tag) << 32) | ((long)head.req.addr);
}

extern "C" void readResponse32(unsigned int data, unsigned int tag)
{
    if(trace_port)
        fprintf(stderr, " read = %x\n", data);
    head.valid = 0;
    respitem.data = data;
    respitem.tag = tag;
    portalSendFd(head.sockfd, &respitem, sizeof(respitem), -1);
}

#define NUM_LINKS 16

struct linkInfo {
    char name[128];
    int listening;
    int socket[1];
    int fd[1];
    uint64_t rxdata[1];
    uint64_t txdata[1];
    pthread_mutex_t mutex;
    int up;
} linkInfo[NUM_LINKS];

struct linkInfo *getLinkInfo(int linknumber, int listening)
{
    char name[128];
    snprintf(name, sizeof(name), "sim.link.%d", linknumber);
    for (int i = 0; i < NUM_LINKS; i++) {
	struct linkInfo *li = &linkInfo[i];
	if (li->name[0] == 0) {
	    strncpy(li->name, name, sizeof(li->name));;
	    li->listening = listening;
	    return li;
	} else if ((strcmp(li->name, name) == 0)
		   && li->listening == listening) {
	    return li;
	}
    }
    return 0;
}

static void *bsimLinkWorker(void *p)
{
    struct linkInfo *li = (struct linkInfo *)p;
    char iname[128];
    int i;
    const char *socketdir = ".";
    if (getenv("SIM_LINK_DIR"))
	socketdir = getenv("SIM_LINK_DIR");

    for (i = 0; i < 1; i++) {
	snprintf(iname, sizeof(iname), "%s/%s", socketdir, li->name);
	if (li->listening) {
	    li->socket[i] = init_listening(iname, NULL);
	    li->fd[i] = accept(li->socket[i], NULL, NULL);
	    if (li->fd[i] == -1) {
		fprintf(stderr, "%s:%d[%d]: accept error %s\n",__FUNCTION__, __LINE__, li->socket[i], strerror(errno));
		return 0;
	    }
	    fprintf(stderr, "%s:%d[%d]: accept ok fd=%d\n",__FUNCTION__, __LINE__, li->socket[i], li->fd[i]);
	} else {
	    li->socket[i] = 0;
	    li->fd[i] = init_connecting(iname, NULL);
	    fprintf(stderr, "%s:%d[%d]: connect ok fd=%d\n",__FUNCTION__, __LINE__, li->socket[i], li->fd[i]);
	}
	fcntl(li->fd[i], F_SETFL, O_NONBLOCK);
    }
    li->up = 1;
    return 0;
}

extern "C" void bsimLinkOpen(int linknumber, int listening)
{
    //fprintf(stderr, "%s:%d pid=%d linknumber=%d listening=%d\n", __func__, __LINE__, getpid(), linknumber, listening);
    struct linkInfo *li = getLinkInfo(linknumber, listening);
    if (li) {
	li->listening = listening;
	pthread_mutex_init(&li->mutex, NULL);
	pthread_t threaddata;
	pthread_create(&threaddata, NULL, &bsimLinkWorker, li);
    }
}
extern "C" int bsimLinkUp(int linknumber, int listening)
{
  struct linkInfo *li = getLinkInfo(linknumber, listening);
  if (li)
      return li->up;
  else
      return 0;
}

extern "C" int bsimLinkCanReceive(int linknumber, int listening)
{
    struct linkInfo *li = getLinkInfo(linknumber, listening);
    struct pollfd pollfd[1];
    int i = 0;
    if (!li->fd[i])
	return 0;
    pollfd[0].fd = li->fd[i];
    pollfd[0].events = POLLIN|POLLRDHUP;
    int status = poll(pollfd, 1, 0);
    if (status && pollfd[0].revents & POLLRDHUP) {
	//fprintf(stderr, "%s:%d revents=%d, closing link %s\n", __FUNCTION__, __LINE__, pollfd[0].revents, li->name);
	//close(li->fd[0]);
	//li->fd[0] = 0;
	return 0;
    }
    return status;
}
extern "C" int bsimLinkCanTransmit(int linknumber, int listening)
{
    struct linkInfo *li = getLinkInfo(linknumber, listening);
    struct pollfd pollfd[1];
    int i = 0;
    if (!li->fd[i])
	return 0;
    pollfd[0].fd = li->fd[i];
    pollfd[0].events = POLLOUT|POLLHUP;
    int status = poll(pollfd, 1, 0);
    if (status && pollfd[0].revents&POLLHUP) {
	//fprintf(stderr, "%s:%d revents=%d, closing link %s\n", __FUNCTION__, __LINE__, pollfd[0].revents, li->name);
	//close(li->fd[i]);
	//li->fd[i] = 0;
	return 0;
    }
    return status;
}
extern "C" uint32_t bsimLinkReceive32(int linknumber, int listening)
{
    struct linkInfo *li = getLinkInfo(linknumber, listening);
    uint32_t *prxdata = (uint32_t *)&li->rxdata;
    int i = 0;
    memset(li->rxdata, 0xbc, sizeof(uint32_t));
    int numBytes = read(li->fd[i], li->rxdata, sizeof(uint32_t));
    if (0 && numBytes > 0)
	fprintf(stderr, "%s:%d linknumber=%d listening=%d numBytes=%d\n", __func__, __LINE__, linknumber, listening, numBytes);
    if (numBytes <= 0)
      fprintf(stderr, "%s:%d linknumber=%d listening=%d numBytes=%d errno=%d\n", __func__, __LINE__, linknumber, listening, numBytes, errno);
    return *prxdata;
}
extern "C" int bsimLinkTransmit32(int linknumber, int listening, uint32_t val)
{
    struct linkInfo *li = getLinkInfo(linknumber, listening);
    //fprintf(stderr, "%s:%d linknumber=%d listening=%d val=%d\n", __func__, __LINE__, linknumber, listening, val);
    int i = 0;
    int numBytes = write(li->fd[i], &val, sizeof(uint32_t));
    //fprintf(stderr, "%s:%d linknumber=%d val=%d numBytes=%d\n", __func__, __LINE__, linknumber, val, numBytes);
    return 0;
}
extern "C" uint64_t bsimLinkReceive64(int linknumber, int listening)
{
    struct linkInfo *li = getLinkInfo(linknumber, listening);
    int i = 0;
    memset(li->rxdata, 0xbc, sizeof(uint64_t));
    int numBytes = read(li->fd[i], li->rxdata, sizeof(uint64_t));
    if (0 && numBytes > 0)
	fprintf(stderr, "%s:%d linknumber=%d listening=%d numBytes=%d\n", __func__, __LINE__, linknumber, listening, numBytes);
    if (numBytes <= 0)
      fprintf(stderr, "%s:%d linknumber=%d listening=%d numBytes=%d errno=%d\n", __func__, __LINE__, linknumber, listening, numBytes, errno);
    return *(uint64_t*)&li->rxdata;
}
extern "C" int bsimLinkTransmit64(int linknumber, int listening, uint64_t val)
{
    struct linkInfo *li = getLinkInfo(linknumber, listening);
    //fprintf(stderr, "%s:%d linknumber=%d listening=%d val=%d\n", __func__, __LINE__, linknumber, listening, val);
    int i = 0;
    int numBytes = write(li->fd[i], &val, sizeof(uint64_t));
    //fprintf(stderr, "%s:%d linknumber=%d val=%lld numBytes=%d\n", __func__, __LINE__, linknumber, val, numBytes);
    return 0;
}

<commit_msg>silence "accept ok" and "connect ok"<commit_after>// Copyright (c) 2013-2014 Quanta Research Cambridge, Inc.

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

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

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

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/un.h>
#include <pthread.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <poll.h>

#include "portal.h"
#include "sock_utils.h"

#define MAX_FD_ARRAY 10

static struct {
    struct memrequest req;
    int sockfd;
    int valid;
    int inflight;
} head;
static struct memresponse respitem;
static int trace_port;// = 1;
static int fd_array[MAX_FD_ARRAY];
static int fd_array_index = 0;

static void *pthread_worker(void *p)
{
    int listening_socket = init_listening(SOCKET_NAME, NULL);
    if (trace_port)
        fprintf(stderr, "%s[%d]: waiting for a connection...\n",__FUNCTION__, listening_socket);
    while (1) {
        int sockfd = accept(listening_socket, NULL, NULL);
        if (sockfd == -1) {
            fprintf(stderr, "%s[%d]: accept error %s\n",__FUNCTION__, listening_socket, strerror(errno));
	    return 0;
        }
        if (trace_port)
            printf("[%s:%d] sockfd %d\n", __FUNCTION__, __LINE__, sockfd);
        fd_array[fd_array_index++] = sockfd;
    }
    return 0;
}

extern "C" void initPortal(void)
{
    pthread_t threaddata;
    pthread_create(&threaddata, NULL, &pthread_worker, NULL);
}

extern "C" void interruptLevel(uint32_t ivalue)
{
    static struct memresponse respitem;
    int i;
    if (ivalue != respitem.data) {
        respitem.portal = MAGIC_PORTAL_FOR_SENDING_INTERRUPT;
        respitem.data = ivalue;
        if (trace_port)
            printf("%s: %d\n", __FUNCTION__, ivalue);
        for (i = 0; i < fd_array_index; i++)
           portalSendFd(fd_array[i], &respitem, sizeof(respitem), -1);
    }
}

#if 0
static unsigned long long int rdtsc(void)
{
   unsigned long long int x;
   unsigned a, d;

   __asm__ volatile("rdtsc" : "=a" (a), "=d" (d));

   return ((unsigned long long)a) | (((unsigned long long)d) << 32);;
}
#endif
extern "C" bool checkForRequest(uint32_t rr)
{
#if 0
static int counter;
static int timeoutcount;
static int last_short;
static long long last_val;
long long this_val = rdtsc();
last_val = (this_val - last_val)/1000;
counter++;
if (last_val <= 3)
   last_short++;
if (last_short == 2) {
timeoutcount++;
    last_short = 0;
    struct timeval timeout;
    timeout.tv_sec = 0;
    timeout.tv_usec = 10000;
    select(0, NULL, NULL, NULL, &timeout);
}
last_val = this_val;
#endif
    if (!head.valid){
	int rv = -1, i, recvfd;
        for (i = 0; i < fd_array_index; i++) {
            head.sockfd = fd_array[i];
            rv = portalRecvFd(head.sockfd, &head.req, sizeof(head.req), &recvfd);
	    if(rv > 0){
	        assert(rv == sizeof(memrequest));
	        respitem.portal = head.req.portal;
	        head.valid = 1;
	        head.inflight = 1;
                if (recvfd != -1)
                    head.req.data_or_tag = recvfd;
	        if(trace_port)
	            fprintf(stderr, "processr p=%d w=%d, a=%8lx, dt=%8x:",
		        head.req.portal, head.req.write_flag, (long)head.req.addr, head.req.data_or_tag);
                break;
	    }
        }
    }
    return head.valid && head.inflight == 1 && head.req.write_flag == (int)rr;
}

extern "C" unsigned long long getRequest32(uint32_t rr)
{
    if(trace_port)
        fprintf(stderr, " get%c", rr ? '\n' : ':');
    if (rr)
        head.valid = 0;
    head.inflight = 0;
    return (((unsigned long long)head.req.data_or_tag) << 32) | ((long)head.req.addr);
}

extern "C" void readResponse32(unsigned int data, unsigned int tag)
{
    if(trace_port)
        fprintf(stderr, " read = %x\n", data);
    head.valid = 0;
    respitem.data = data;
    respitem.tag = tag;
    portalSendFd(head.sockfd, &respitem, sizeof(respitem), -1);
}

#define NUM_LINKS 16

struct linkInfo {
    char name[128];
    int listening;
    int socket[1];
    int fd[1];
    uint64_t rxdata[1];
    uint64_t txdata[1];
    pthread_mutex_t mutex;
    int up;
} linkInfo[NUM_LINKS];

struct linkInfo *getLinkInfo(int linknumber, int listening)
{
    char name[128];
    snprintf(name, sizeof(name), "sim.link.%d", linknumber);
    for (int i = 0; i < NUM_LINKS; i++) {
	struct linkInfo *li = &linkInfo[i];
	if (li->name[0] == 0) {
	    strncpy(li->name, name, sizeof(li->name));;
	    li->listening = listening;
	    return li;
	} else if ((strcmp(li->name, name) == 0)
		   && li->listening == listening) {
	    return li;
	}
    }
    return 0;
}

static void *bsimLinkWorker(void *p)
{
    struct linkInfo *li = (struct linkInfo *)p;
    char iname[128];
    int i;
    const char *socketdir = ".";
    if (getenv("SIM_LINK_DIR"))
	socketdir = getenv("SIM_LINK_DIR");

    for (i = 0; i < 1; i++) {
	snprintf(iname, sizeof(iname), "%s/%s", socketdir, li->name);
	if (li->listening) {
	    li->socket[i] = init_listening(iname, NULL);
	    li->fd[i] = accept(li->socket[i], NULL, NULL);
	    if (li->fd[i] == -1) {
		fprintf(stderr, "%s:%d[%d]: accept error %s\n",__FUNCTION__, __LINE__, li->socket[i], strerror(errno));
		return 0;
	    }
	    //fprintf(stderr, "%s:%d[%d]: accept ok fd=%d\n",__FUNCTION__, __LINE__, li->socket[i], li->fd[i]);
	} else {
	    li->socket[i] = 0;
	    li->fd[i] = init_connecting(iname, NULL);
	    //fprintf(stderr, "%s:%d[%d]: connect ok fd=%d\n",__FUNCTION__, __LINE__, li->socket[i], li->fd[i]);
	}
	fcntl(li->fd[i], F_SETFL, O_NONBLOCK);
    }
    li->up = 1;
    return 0;
}

extern "C" void bsimLinkOpen(int linknumber, int listening)
{
    //fprintf(stderr, "%s:%d pid=%d linknumber=%d listening=%d\n", __func__, __LINE__, getpid(), linknumber, listening);
    struct linkInfo *li = getLinkInfo(linknumber, listening);
    if (li) {
	li->listening = listening;
	pthread_mutex_init(&li->mutex, NULL);
	pthread_t threaddata;
	pthread_create(&threaddata, NULL, &bsimLinkWorker, li);
    }
}
extern "C" int bsimLinkUp(int linknumber, int listening)
{
  struct linkInfo *li = getLinkInfo(linknumber, listening);
  if (li)
      return li->up;
  else
      return 0;
}

extern "C" int bsimLinkCanReceive(int linknumber, int listening)
{
    struct linkInfo *li = getLinkInfo(linknumber, listening);
    struct pollfd pollfd[1];
    int i = 0;
    if (!li->fd[i])
	return 0;
    pollfd[0].fd = li->fd[i];
    pollfd[0].events = POLLIN|POLLRDHUP;
    int status = poll(pollfd, 1, 0);
    if (status && pollfd[0].revents & POLLRDHUP) {
	//fprintf(stderr, "%s:%d revents=%d, closing link %s\n", __FUNCTION__, __LINE__, pollfd[0].revents, li->name);
	//close(li->fd[0]);
	//li->fd[0] = 0;
	return 0;
    }
    return status;
}
extern "C" int bsimLinkCanTransmit(int linknumber, int listening)
{
    struct linkInfo *li = getLinkInfo(linknumber, listening);
    struct pollfd pollfd[1];
    int i = 0;
    if (!li->fd[i])
	return 0;
    pollfd[0].fd = li->fd[i];
    pollfd[0].events = POLLOUT|POLLHUP;
    int status = poll(pollfd, 1, 0);
    if (status && pollfd[0].revents&POLLHUP) {
	//fprintf(stderr, "%s:%d revents=%d, closing link %s\n", __FUNCTION__, __LINE__, pollfd[0].revents, li->name);
	//close(li->fd[i]);
	//li->fd[i] = 0;
	return 0;
    }
    return status;
}
extern "C" uint32_t bsimLinkReceive32(int linknumber, int listening)
{
    struct linkInfo *li = getLinkInfo(linknumber, listening);
    uint32_t *prxdata = (uint32_t *)&li->rxdata;
    int i = 0;
    memset(li->rxdata, 0xbc, sizeof(uint32_t));
    int numBytes = read(li->fd[i], li->rxdata, sizeof(uint32_t));
    if (0 && numBytes > 0)
	fprintf(stderr, "%s:%d linknumber=%d listening=%d numBytes=%d\n", __func__, __LINE__, linknumber, listening, numBytes);
    if (numBytes <= 0)
      fprintf(stderr, "%s:%d linknumber=%d listening=%d numBytes=%d errno=%d\n", __func__, __LINE__, linknumber, listening, numBytes, errno);
    return *prxdata;
}
extern "C" int bsimLinkTransmit32(int linknumber, int listening, uint32_t val)
{
    struct linkInfo *li = getLinkInfo(linknumber, listening);
    //fprintf(stderr, "%s:%d linknumber=%d listening=%d val=%d\n", __func__, __LINE__, linknumber, listening, val);
    int i = 0;
    int numBytes = write(li->fd[i], &val, sizeof(uint32_t));
    //fprintf(stderr, "%s:%d linknumber=%d val=%d numBytes=%d\n", __func__, __LINE__, linknumber, val, numBytes);
    return 0;
}
extern "C" uint64_t bsimLinkReceive64(int linknumber, int listening)
{
    struct linkInfo *li = getLinkInfo(linknumber, listening);
    int i = 0;
    memset(li->rxdata, 0xbc, sizeof(uint64_t));
    int numBytes = read(li->fd[i], li->rxdata, sizeof(uint64_t));
    if (0 && numBytes > 0)
	fprintf(stderr, "%s:%d linknumber=%d listening=%d numBytes=%d\n", __func__, __LINE__, linknumber, listening, numBytes);
    if (numBytes <= 0)
      fprintf(stderr, "%s:%d linknumber=%d listening=%d numBytes=%d errno=%d\n", __func__, __LINE__, linknumber, listening, numBytes, errno);
    return *(uint64_t*)&li->rxdata;
}
extern "C" int bsimLinkTransmit64(int linknumber, int listening, uint64_t val)
{
    struct linkInfo *li = getLinkInfo(linknumber, listening);
    //fprintf(stderr, "%s:%d linknumber=%d listening=%d val=%d\n", __func__, __LINE__, linknumber, listening, val);
    int i = 0;
    int numBytes = write(li->fd[i], &val, sizeof(uint64_t));
    //fprintf(stderr, "%s:%d linknumber=%d val=%lld numBytes=%d\n", __func__, __LINE__, linknumber, val, numBytes);
    return 0;
}

<|endoftext|>


<commit_before>/*
 *  ofxWebSimpleGuiToo.cpp
 *  ofxWebSimpleGuiTooExample
 *
 *  Created by Marek Bereza on 27/03/2010.
 *  Copyright 2010 Marek Bereza. All rights reserved.
 *
 */
#include "ofxWebSimpleGuiToo.h"

ofxWebSimpleGuiToo webGui;

ofxWebSimpleGuiToo::ofxWebSimpleGuiToo() {
}
void ofxWebSimpleGuiToo::startServer(int port) {
	server.start("ofxWebSimpleGuiToo", port);
	server.addHandler(this, "/control");
}

void ofxWebSimpleGuiToo::stopServer(){
	server.stop();
}

void ofxWebSimpleGuiToo::replaceAll(string &str, const string &find_what, const string &replace_with) {
	string::size_type pos=0;
	while((pos=str.find(find_what, pos))!=string::npos)
	{
		str.erase(pos, find_what.length());
		str.insert(pos, replace_with);
		pos+=replace_with.length();
	}
}

void ofxWebSimpleGuiToo::httpGet(string url) {

	string key = getRequestParameter("key");
	replaceAll(key, "%20", " ");
	if(key=="") {
		string guiDesc = "[";
		for(int i = 0; i < pages.size(); i++) {
			guiDesc += describePage(pages[i]);
			if(i+1<pages.size()) {
				guiDesc += ",";
			}
		}
		guiDesc += "]";
		httpResponse(guiDesc);
	} else {

		string value = getRequestParameter("value");
		printf("value received: %s = %s\n", key.c_str(), value.c_str());
		ofxSimpleGuiControl *ctrl = &control(key);
		if(ctrl!=NULL) {
			if(ctrl->controlType=="Toggle") {
				ofxSimpleGuiToggle *t = (ofxSimpleGuiToggle*)ctrl;
				*(t->value) = (value=="true");
			} else if(ctrl->controlType=="SliderInt") {
				ofxSimpleGuiSliderInt *t = (ofxSimpleGuiSliderInt*)ctrl;
				*(t->value) = atoi(value.c_str());
			} else if(ctrl->controlType=="SliderFloat") {
				ofxSimpleGuiSliderFloat *t = (ofxSimpleGuiSliderFloat*)ctrl;
				*(t->value) = atof(value.c_str());
			} else if(ctrl->controlType=="Button") {
				ofxSimpleGuiToggle *t = (ofxSimpleGuiToggle*)ctrl;
//				t->onPress(0, 0, 0);
//				t->onRelease(0, 0, 0);
				*(t->value) = true;
// 				printf("Hello here!!\n");
			//} else if(ctrl->controlType=="ColorPicker") {
			//	ofxSimpleGuiColorPicker *t = (ofxSimpleGuiColorPicker*) ctrl;
			//	vector<string> ss = ofSplitString(value, ",");
			//	for(int i = 0; i < 4; i++)
			//		t->values[i] = atof(ss[i].c_str());
			}  else if(ctrl->controlType=="HexColorPicker") {
//					ofxSimpleGuiHexColorPicker *t = (ofxSimpleGuiHexColorPicker*) ctrl;
//					vector<string> ss = ofSplitString(value, ",");
//					for(int i = 0; i < 3; i++)
//						t->setValue(atof(ss[i].c_str()), i);

			} else if(ctrl->controlType=="Slider2D") {
				ofxSimpleGuiSlider2d *t = (ofxSimpleGuiSlider2d*) ctrl;
				vector<string> ss = ofSplitString(value, ",");

				t->value->x = atof(ss[0].c_str());
				t->value->y = atof(ss[1].c_str());

			/*} else if(ctrl->controlType=="Slider3D") {
				ofxSimpleGuiSlider3d *t = (ofxSimpleGuiSlider3d*) ctrl;
				vector<string> ss = ofSplitString(value, ",");

				t->value->x = atof(ss[0].c_str());
				t->value->y = atof(ss[1].c_str());
				t->value->z = atof(ss[2].c_str());
			*/
			}

		}
		httpResponse("thanks");
	}
}

string ofxWebSimpleGuiToo::describePage(ofxSimpleGuiPage *page) {
	string desc = "{\"name\": \""+page->name+"\", \"controls\":[";
	for(int i = 0; i < page->getControls().size(); i++) {
		desc += describeControl(page->getControls()[i]);
		if(i+1<page->getControls().size()) {
			desc += ",";
		}
	}
	desc += "]}";
	return desc;
}
string ofxWebSimpleGuiToo::describeControl(ofxSimpleGuiControl *ctrl) {
	string desc = "{\"name\":\""+ctrl->name + "\",";
	desc += "\"type\": \""+ctrl->controlType+"\"";

	if(ctrl->controlType=="Toggle") {
		ofxSimpleGuiToggle *t = (ofxSimpleGuiToggle*)ctrl;
		if(*t->value) desc += ", \"value\":\"true\"";
		else desc += ", \"value\":\"false\"";
	} else if(ctrl->controlType=="SliderInt") {
		ofxSimpleGuiSliderInt *t = (ofxSimpleGuiSliderInt*)ctrl;
		desc += ", \"value\":\""+ofToString(*(t->value))+"\"";
		desc += ", \"min\":\""+ofToString(t->min)+"\"";
		desc += ", \"max\":\""+ofToString(t->max)+"\"";

	} else if(ctrl->controlType=="SliderFloat") {
		ofxSimpleGuiSliderFloat *t = (ofxSimpleGuiSliderFloat*)ctrl;
		desc += ", \"value\":\""+ofToString(*(t->value))+"\"";
		desc += ", \"min\":\""+ofToString(t->min)+"\"";
		desc += ", \"max\":\""+ofToString(t->max)+"\"";

	} else if(ctrl->controlType=="Slider2D") {
		ofxSimpleGuiSlider2d *t = (ofxSimpleGuiSlider2d*)ctrl;

		desc += ", \"value\":\""+ofToString(t->value->x)+","+ofToString(t->value->y)+"\"";
		desc += ", \"minX\":\""+ofToString(t->min.x)+"\"";
		desc += ", \"maxX\":\""+ofToString(t->max.x)+"\"";
		desc += ", \"minY\":\""+ofToString(t->min.y)+"\"";
		desc += ", \"maxY\":\""+ofToString(t->max.y)+"\"";
	/*} else if(ctrl->controlType=="Slider3D") {
		ofxSimpleGuiSlider3d *t = (ofxSimpleGuiSlider3d*)ctrl;

		desc += ", \"value\":\""+ofToString(t->value->x)+","+ofToString(t->value->y)+","+ofToString(t->value->z)+"\"";
		desc += ", \"minX\":\""+ofToString(t->min.x)+"\"";
		desc += ", \"maxX\":\""+ofToString(t->max.x)+"\"";
		desc += ", \"minY\":\""+ofToString(t->min.y)+"\"";
		desc += ", \"maxY\":\""+ofToString(t->max.y)+"\"";
		desc += ", \"minZ\":\""+ofToString(t->min.z)+"\"";
		desc += ", \"maxZ\":\""+ofToString(t->max.z)+"\"";*/
	//} else if(ctrl->controlType=="ColorPicker") {
	//	ofxSimpleGuiColorPicker *t = (ofxSimpleGuiColorPicker*)ctrl;

	//	desc += ", \"value\":\""
	//	+ofToString(t->values[0])+","+ofToString(t->values[1])+","+ofToString(t->values[2])+","+ofToString(t->values[3])+"\"";
	} else if(ctrl->controlType=="HexColorPicker") {
		ofxSimpleGuiHexColorPicker *t = (ofxSimpleGuiHexColorPicker*)ctrl;
//
//

			desc += ", \"value\":\""
			+ofToString(t->getValue(0))+","+ofToString(t->getValue(1))+","+ofToString(t->getValue(2))+"\"";

	}
	desc += "}";
	return desc;
}

<commit_msg>Better fix<commit_after>/*
 *  ofxWebSimpleGuiToo.cpp
 *  ofxWebSimpleGuiTooExample
 *
 *  Created by Marek Bereza on 27/03/2010.
 *  Copyright 2010 Marek Bereza. All rights reserved.
 *
 */
#include "ofxWebSimpleGuiToo.h"

ofxWebSimpleGuiToo webGui;

ofxWebSimpleGuiToo::ofxWebSimpleGuiToo() {
}
void ofxWebSimpleGuiToo::startServer(int port) {
	server.start("ofxWebSimpleGuiToo", port);
	server.addHandler(this, "/control");
}

void ofxWebSimpleGuiToo::stopServer(){
	server.stop();
}

void ofxWebSimpleGuiToo::replaceAll(string &str, const string &find_what, const string &replace_with) {
	string::size_type pos=0;
	while((pos=str.find(find_what, pos))!=string::npos)
	{
		str.erase(pos, find_what.length());
		str.insert(pos, replace_with);
		pos+=replace_with.length();
	}
}

void ofxWebSimpleGuiToo::httpGet(string url) {

	string key = getRequestParameter("key");
	replaceAll(key, "%20", " ");
	if(key=="") {
		string guiDesc = "[";
		for(int i = 0; i < pages.size(); i++) {
			guiDesc += describePage(pages[i]);
			if(i+1<pages.size()) {
				guiDesc += ",";
			}
		}
		guiDesc += "]";
		httpResponse(guiDesc);
	} else {

		string value = getRequestParameter("value");
		printf("value received: %s = %s\n", key.c_str(), value.c_str());
		ofxSimpleGuiControl *ctrl = &control(key);
		if(ctrl!=NULL) {
			if(ctrl->controlType=="Toggle") {
				ofxSimpleGuiToggle *t = (ofxSimpleGuiToggle*)ctrl;
				*(t->value) = (value=="true");
			} else if(ctrl->controlType=="SliderInt") {
				ofxSimpleGuiSliderInt *t = (ofxSimpleGuiSliderInt*)ctrl;
				*(t->value) = atoi(value.c_str());
			} else if(ctrl->controlType=="SliderFloat") {
				ofxSimpleGuiSliderFloat *t = (ofxSimpleGuiSliderFloat*)ctrl;
				*(t->value) = atof(value.c_str());
			} else if(ctrl->controlType=="Button") {
				ofxSimpleGuiToggle *t = (ofxSimpleGuiToggle*)ctrl;
//				t->onPress(0, 0, 0);
//				t->onRelease(0, 0, 0);
				*(t->value) = true;
// 				printf("Hello here!!\n");
			//} else if(ctrl->controlType=="ColorPicker") {
			//	ofxSimpleGuiColorPicker *t = (ofxSimpleGuiColorPicker*) ctrl;
			//	vector<string> ss = ofSplitString(value, ",");
			//	for(int i = 0; i < 4; i++)
			//		t->values[i] = atof(ss[i].c_str());
			}  else if(ctrl->controlType=="HexColorPicker") {
					ofxSimpleGuiHexColorPicker *t = (ofxSimpleGuiHexColorPicker*) ctrl;
					vector<string> ss = ofSplitString(value, ",");
					for(int i = 0; i < 3; i++)
						t->setValue(atof(ss[i].c_str()), i);

			} else if(ctrl->controlType=="Slider2D") {
				ofxSimpleGuiSlider2d *t = (ofxSimpleGuiSlider2d*) ctrl;
				vector<string> ss = ofSplitString(value, ",");

				t->value->x = atof(ss[0].c_str());
				t->value->y = atof(ss[1].c_str());

			/*} else if(ctrl->controlType=="Slider3D") {
				ofxSimpleGuiSlider3d *t = (ofxSimpleGuiSlider3d*) ctrl;
				vector<string> ss = ofSplitString(value, ",");

				t->value->x = atof(ss[0].c_str());
				t->value->y = atof(ss[1].c_str());
				t->value->z = atof(ss[2].c_str());
			*/
			}

		}
		httpResponse("thanks");
	}
}

string ofxWebSimpleGuiToo::describePage(ofxSimpleGuiPage *page) {
	string desc = "{\"name\": \""+page->name+"\", \"controls\":[";
	for(int i = 0; i < page->getControls().size(); i++) {
		desc += describeControl(page->getControls()[i]);
		if(i+1<page->getControls().size()) {
			desc += ",";
		}
	}
	desc += "]}";
	return desc;
}
string ofxWebSimpleGuiToo::describeControl(ofxSimpleGuiControl *ctrl) {
	string desc = "{\"name\":\""+ctrl->name + "\",";
	desc += "\"type\": \""+ctrl->controlType+"\"";

	if(ctrl->controlType=="Toggle") {
		ofxSimpleGuiToggle *t = (ofxSimpleGuiToggle*)ctrl;
		if(*t->value) desc += ", \"value\":\"true\"";
		else desc += ", \"value\":\"false\"";
	} else if(ctrl->controlType=="SliderInt") {
		ofxSimpleGuiSliderInt *t = (ofxSimpleGuiSliderInt*)ctrl;
		desc += ", \"value\":\""+ofToString(*(t->value))+"\"";
		desc += ", \"min\":\""+ofToString(t->min)+"\"";
		desc += ", \"max\":\""+ofToString(t->max)+"\"";

	} else if(ctrl->controlType=="SliderFloat") {
		ofxSimpleGuiSliderFloat *t = (ofxSimpleGuiSliderFloat*)ctrl;
		desc += ", \"value\":\""+ofToString(*(t->value))+"\"";
		desc += ", \"min\":\""+ofToString(t->min)+"\"";
		desc += ", \"max\":\""+ofToString(t->max)+"\"";

	} else if(ctrl->controlType=="Slider2D") {
		ofxSimpleGuiSlider2d *t = (ofxSimpleGuiSlider2d*)ctrl;

		desc += ", \"value\":\""+ofToString(t->value->x)+","+ofToString(t->value->y)+"\"";
		desc += ", \"minX\":\""+ofToString(t->min.x)+"\"";
		desc += ", \"maxX\":\""+ofToString(t->max.x)+"\"";
		desc += ", \"minY\":\""+ofToString(t->min.y)+"\"";
		desc += ", \"maxY\":\""+ofToString(t->max.y)+"\"";
	/*} else if(ctrl->controlType=="Slider3D") {
		ofxSimpleGuiSlider3d *t = (ofxSimpleGuiSlider3d*)ctrl;

		desc += ", \"value\":\""+ofToString(t->value->x)+","+ofToString(t->value->y)+","+ofToString(t->value->z)+"\"";
		desc += ", \"minX\":\""+ofToString(t->min.x)+"\"";
		desc += ", \"maxX\":\""+ofToString(t->max.x)+"\"";
		desc += ", \"minY\":\""+ofToString(t->min.y)+"\"";
		desc += ", \"maxY\":\""+ofToString(t->max.y)+"\"";
		desc += ", \"minZ\":\""+ofToString(t->min.z)+"\"";
		desc += ", \"maxZ\":\""+ofToString(t->max.z)+"\"";*/
	//} else if(ctrl->controlType=="ColorPicker") {
	//	ofxSimpleGuiColorPicker *t = (ofxSimpleGuiColorPicker*)ctrl;

	//	desc += ", \"value\":\""
	//	+ofToString(t->values[0])+","+ofToString(t->values[1])+","+ofToString(t->values[2])+","+ofToString(t->values[3])+"\"";
	} else if(ctrl->controlType=="HexColorPicker") {
		ofxSimpleGuiHexColorPicker *t = (ofxSimpleGuiHexColorPicker*)ctrl;
//
//

			desc += ", \"value\":\""
			+ofToString(t->getValue(0))+","+ofToString(t->getValue(1))+","+ofToString(t->getValue(2))+"\"";

	}
	desc += "}";
	return desc;
}

<|endoftext|>


<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>

#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <Shifts.hpp>
#include <Dedispersion.hpp>
#include <utils.hpp>
#include <Timer.hpp>
#include <Stats.hpp>

typedef float dataType;
std::string typeName("float");

void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, const unsigned int shifts_size, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size);

int main(int argc, char * argv[]) {
  bool localMem = false;
  bool reInit = false;
	unsigned int nrIterations = 0;
	unsigned int clPlatformID = 0;
	unsigned int clDeviceID = 0;
	unsigned int minThreads = 0;
  unsigned int maxThreads = 0;
	unsigned int maxRows = 0;
	unsigned int maxColumns = 0;
  unsigned int threadUnit = 0;
  unsigned int threadIncrement = 0;
  unsigned int maxItems = 0;
  unsigned int maxUnroll = 0;
  unsigned int maxLoopBodySize = 0;
  AstroData::Observation observation;
  cl::Event event;

	try {
    isa::utils::ArgumentList args(argc, argv);

		nrIterations = args.getSwitchArgument< unsigned int >("-iterations");
		clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
		clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
    localMem = args.getSwitch("-local");
		observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
    threadUnit = args.getSwitchArgument< unsigned int >("-thread_unit");
		minThreads = args.getSwitchArgument< unsigned int >("-min_threads");
		maxThreads = args.getSwitchArgument< unsigned int >("-max_threads");
		maxRows = args.getSwitchArgument< unsigned int >("-max_rows");
		maxColumns = args.getSwitchArgument< unsigned int >("-max_columns");
    threadIncrement = args.getSwitchArgument< unsigned int >("-thread_increment");
		maxItems = args.getSwitchArgument< unsigned int >("-max_items");
    maxUnroll = args.getSwitchArgument< unsigned int >("-max_unroll");
    maxLoopBodySize = args.getSwitchArgument< unsigned int >("-max_loopsize");
    observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth"));
		observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples"));
    observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), args.getSwitchArgument< float >("-dm_first"), args.getSwitchArgument< float >("-dm_step"));
	} catch ( isa::utils::EmptyCommandLine & err ) {
		std::cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... [-local] -padding ... -thread_unit ... -min_threads ... -max_threads ... -max_items ... -max_unroll ... -max_loopsize ... -max_columns ... -max_rows ... -thread_increment ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << std::endl;
		return 1;
	} catch ( std::exception & err ) {
		std::cerr << err.what() << std::endl;
		return 1;
	}

  // Allocate host memory
  std::vector< float > * shifts = PulsarSearch::getShifts(observation);
  observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()))));

	// Initialize OpenCL
	cl::Context clContext;
	std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();
	std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();
	std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >();
  isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);

	// Allocate device memory
  cl::Buffer shifts_d;
  cl::Buffer dispersedData_d;
  cl::Buffer dedispersedData_d;

  initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, shifts->size(), &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());

	// Find the parameters
	std::vector< unsigned int > samplesPerBlock;
	for ( unsigned int samples = minThreads; samples <= maxColumns; samples += threadIncrement ) {
		if ( (observation.getNrSamplesPerPaddedSecond() % samples) == 0 ) {
			samplesPerBlock.push_back(samples);
		}
	}
	std::vector< unsigned int > DMsPerBlock;
	for ( unsigned int DMs = 1; DMs <= maxRows; DMs++ ) {
		if ( (observation.getNrDMs() % DMs) == 0 ) {
			DMsPerBlock.push_back(DMs);
		}
	}

	std::cout << std::fixed << std::endl;
	std::cout << "# nrDMs nrChannels nrSamples local samplesPerBlock DMsPerBlock samplesPerThread DMsPerThread unroll GFLOP/s GB/s time stdDeviation COV" << std::endl << std::endl;

	for ( std::vector< unsigned int >::iterator samples = samplesPerBlock.begin(); samples != samplesPerBlock.end(); ++samples ) {
		for ( std::vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); ++DMs ) {
			if ( ((*samples) * (*DMs)) > maxThreads ) {
				break;
			} else if ( ((*samples) * (*DMs)) % threadUnit != 0 ) {
        continue;
      }

			for ( unsigned int samplesPerThread = 1; samplesPerThread <= maxItems; samplesPerThread++ ) {
				if ( (observation.getNrSamplesPerPaddedSecond() % ((*samples) * samplesPerThread)) != 0 ) {
					continue;
				}

				for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItems; DMsPerThread++ ) {
					if ( (observation.getNrDMs() % ((*DMs) * DMsPerThread)) != 0 ) {
						continue;
					} else if ( (samplesPerThread * DMsPerThread) + DMsPerThread > maxItems ) {
						break;
					}

          for ( unsigned int unroll = 1; unroll <= maxUnroll; unroll++ ) {
            if ( (observation.getNrChannels() - 1) % unroll != 0 ) {
              continue;
            } else if ( (samplesPerThread * DMsPerThread * unroll) > maxLoopBodySize ) {
              break;
            }
            // Generate kernel
            double gflops = isa::utils::giga(static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrChannels() * observation.getNrSamplesPerSecond());
            double gbs = isa::utils::giga(((static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrSamplesPerSecond() * (observation.getNrChannels() + 1)) * sizeof(dataType)) + ((observation.getNrDMs() * observation.getNrChannels()) * sizeof(unsigned int)));
            isa::utils::Timer timer;
            cl::Kernel * kernel;
            std::string * code = PulsarSearch::getDedispersionOpenCL(localMem, *samples, *DMs, samplesPerThread, DMsPerThread, unroll, typeName, observation, *shifts);

            if ( reInit ) {
              delete clQueues;
              clQueues = new std::vector< std::vector < cl::CommandQueue > >();
              isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);
              initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, shifts->size(), &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
              reInit = false;
            }
            try {
              kernel = isa::OpenCL::compile("dedispersion", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID));
            } catch ( isa::OpenCL::OpenCLError & err ) {
              std::cerr << err.what() << std::endl;
              reInit = true;
              break;
            }
            delete code;

            cl::NDRange global(observation.getNrSamplesPerPaddedSecond() / samplesPerThread, observation.getNrDMs() / DMsPerThread);
            cl::NDRange local(*samples, *DMs);

            kernel->setArg(0, dispersedData_d);
            kernel->setArg(1, dedispersedData_d);
            kernel->setArg(2, shifts_d);

            try {
              // Warm-up run
              clQueues->at(clDeviceID)[0].finish();
              clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
              event.wait();
              // Tuning runs
              for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {
                timer.start();
                clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
                event.wait();
                timer.stop();
              }
            } catch ( cl::Error & err ) {
              std::cerr << "OpenCL error kernel execution (";
              std::cerr << *samples << ", " << *DMs << ", " << samplesPerThread << ", " << DMsPerThread << "): ";
              std::cerr << isa::utils::toString(err.err()) << "." << std::endl;
              delete kernel;
              reInit = true;
              break;
            }
            delete kernel;

            std::cout << observation.getNrDMs() << " " << observation.getNrChannels() << " " << observation.getNrSamplesPerSecond() << " " << localMem << " " << *samples << " " << *DMs << " " << samplesPerThread << " " << DMsPerThread << " " << unroll << " ";
            std::cout << std::setprecision(3);
            std::cout << gflops / timer.getAverageTime() << " ";
            std::cout << gbs / timer.getAverageTime() << " ";
            std::cout << std::setprecision(6);
            std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " ";
            std::cout << timer.getCoefficientOfVariation() <<  std::endl;
          }
				}
			}
		}
	}

	std::cout << std::endl;

	return 0;
}

void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, const unsigned int shifts_size, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size) {
  try {
    *shifts_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, shifts_size * sizeof(float), 0, 0);
    *dispersedData_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, dispersedData_size * sizeof(dataType), 0, 0);
    *dedispersedData_d = cl::Buffer(clContext, CL_MEM_READ_WRITE, dedispersedData_size * sizeof(dataType), 0, 0);
    clQueue->enqueueWriteBuffer(*shifts_d, CL_FALSE, 0, shifts_size * sizeof(float), reinterpret_cast< void * >(shifts->data()));
  } catch ( cl::Error & err ) {
    std::cerr << "OpenCL error: " << isa::utils::toString(err.err()) << "." << std::endl;
  }
}

<commit_msg>Format fix.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>

#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <Shifts.hpp>
#include <Dedispersion.hpp>
#include <utils.hpp>
#include <Timer.hpp>
#include <Stats.hpp>

typedef float dataType;
std::string typeName("float");

void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, const unsigned int shifts_size, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size);

int main(int argc, char * argv[]) {
  bool localMem = false;
  bool reInit = false;
	unsigned int nrIterations = 0;
	unsigned int clPlatformID = 0;
	unsigned int clDeviceID = 0;
	unsigned int minThreads = 0;
  unsigned int maxThreads = 0;
	unsigned int maxRows = 0;
	unsigned int maxColumns = 0;
  unsigned int threadUnit = 0;
  unsigned int threadIncrement = 0;
  unsigned int maxItems = 0;
  unsigned int maxUnroll = 0;
  unsigned int maxLoopBodySize = 0;
  AstroData::Observation observation;
  cl::Event event;

	try {
    isa::utils::ArgumentList args(argc, argv);

		nrIterations = args.getSwitchArgument< unsigned int >("-iterations");
		clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
		clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
    localMem = args.getSwitch("-local");
		observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
    threadUnit = args.getSwitchArgument< unsigned int >("-thread_unit");
		minThreads = args.getSwitchArgument< unsigned int >("-min_threads");
		maxThreads = args.getSwitchArgument< unsigned int >("-max_threads");
		maxRows = args.getSwitchArgument< unsigned int >("-max_rows");
		maxColumns = args.getSwitchArgument< unsigned int >("-max_columns");
    threadIncrement = args.getSwitchArgument< unsigned int >("-thread_increment");
		maxItems = args.getSwitchArgument< unsigned int >("-max_items");
    maxUnroll = args.getSwitchArgument< unsigned int >("-max_unroll");
    maxLoopBodySize = args.getSwitchArgument< unsigned int >("-max_loopsize");
    observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth"));
		observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples"));
    observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), args.getSwitchArgument< float >("-dm_first"), args.getSwitchArgument< float >("-dm_step"));
	} catch ( isa::utils::EmptyCommandLine & err ) {
		std::cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... [-local] -padding ... -thread_unit ... -min_threads ... -max_threads ... -max_items ... -max_unroll ... -max_loopsize ... -max_columns ... -max_rows ... -thread_increment ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ..." << std::endl;
		return 1;
	} catch ( std::exception & err ) {
		std::cerr << err.what() << std::endl;
		return 1;
	}

  // Allocate host memory
  std::vector< float > * shifts = PulsarSearch::getShifts(observation);
  observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()))));

	// Initialize OpenCL
	cl::Context clContext;
	std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();
	std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();
	std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >();
  isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);

	// Allocate device memory
  cl::Buffer shifts_d;
  cl::Buffer dispersedData_d;
  cl::Buffer dedispersedData_d;

  initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, shifts->size(), &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());

	// Find the parameters
	std::vector< unsigned int > samplesPerBlock;
	for ( unsigned int samples = minThreads; samples <= maxColumns; samples += threadIncrement ) {
		if ( (observation.getNrSamplesPerPaddedSecond() % samples) == 0 ) {
			samplesPerBlock.push_back(samples);
		}
	}
	std::vector< unsigned int > DMsPerBlock;
	for ( unsigned int DMs = 1; DMs <= maxRows; DMs++ ) {
		if ( (observation.getNrDMs() % DMs) == 0 ) {
			DMsPerBlock.push_back(DMs);
		}
	}

	std::cout << std::fixed << std::endl;
	std::cout << "# nrDMs nrChannels nrSamples local samplesPerBlock DMsPerBlock samplesPerThread DMsPerThread unroll GFLOP/s GB/s time stdDeviation COV" << std::endl << std::endl;

	for ( std::vector< unsigned int >::iterator samples = samplesPerBlock.begin(); samples != samplesPerBlock.end(); ++samples ) {
		for ( std::vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); ++DMs ) {
			if ( ((*samples) * (*DMs)) > maxThreads ) {
				break;
			} else if ( ((*samples) * (*DMs)) % threadUnit != 0 ) {
        continue;
      }

			for ( unsigned int samplesPerThread = 1; samplesPerThread <= maxItems; samplesPerThread++ ) {
				if ( (observation.getNrSamplesPerPaddedSecond() % ((*samples) * samplesPerThread)) != 0 ) {
					continue;
				}

				for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItems; DMsPerThread++ ) {
					if ( (observation.getNrDMs() % ((*DMs) * DMsPerThread)) != 0 ) {
						continue;
					} else if ( (samplesPerThread * DMsPerThread) + DMsPerThread > maxItems ) {
						break;
					}

          for ( unsigned int unroll = 1; unroll <= maxUnroll; unroll++ ) {
            if ( (observation.getNrChannels() - 1) % unroll != 0 ) {
              continue;
            } else if ( (samplesPerThread * DMsPerThread * unroll) > maxLoopBodySize ) {
              break;
            }
            // Generate kernel
            double gflops = isa::utils::giga(static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrChannels() * observation.getNrSamplesPerSecond());
            double gbs = isa::utils::giga(((static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrSamplesPerSecond() * (observation.getNrChannels() + 1)) * sizeof(dataType)) + ((observation.getNrDMs() * observation.getNrChannels()) * sizeof(unsigned int)));
            isa::utils::Timer timer;
            cl::Kernel * kernel;
            std::string * code = PulsarSearch::getDedispersionOpenCL(localMem, *samples, *DMs, samplesPerThread, DMsPerThread, unroll, typeName, observation, *shifts);

            if ( reInit ) {
              delete clQueues;
              clQueues = new std::vector< std::vector < cl::CommandQueue > >();
              isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);
              initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, shifts->size(), &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());
              reInit = false;
            }
            try {
              kernel = isa::OpenCL::compile("dedispersion", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID));
            } catch ( isa::OpenCL::OpenCLError & err ) {
              std::cerr << err.what() << std::endl;
              reInit = true;
              break;
            }
            delete code;

            cl::NDRange global(observation.getNrSamplesPerPaddedSecond() / samplesPerThread, observation.getNrDMs() / DMsPerThread);
            cl::NDRange local(*samples, *DMs);

            kernel->setArg(0, dispersedData_d);
            kernel->setArg(1, dedispersedData_d);
            kernel->setArg(2, shifts_d);

            try {
              // Warm-up run
              clQueues->at(clDeviceID)[0].finish();
              clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
              event.wait();
              // Tuning runs
              for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {
                timer.start();
                clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
                event.wait();
                timer.stop();
              }
            } catch ( cl::Error & err ) {
              std::cerr << "OpenCL error kernel execution (";
              std::cerr << localMem << " " << *samples << ", " << *DMs << ", " << samplesPerThread << ", " << DMsPerThread << ", " << unroll << "): ";
              std::cerr << isa::utils::toString(err.err()) << "." << std::endl;
              delete kernel;
              reInit = true;
              break;
            }
            delete kernel;

            std::cout << observation.getNrDMs() << " " << observation.getNrChannels() << " " << observation.getNrSamplesPerSecond() << " " << localMem << " " << *samples << " " << *DMs << " " << samplesPerThread << " " << DMsPerThread << " " << unroll << " ";
            std::cout << std::setprecision(3);
            std::cout << gflops / timer.getAverageTime() << " ";
            std::cout << gbs / timer.getAverageTime() << " ";
            std::cout << std::setprecision(6);
            std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " ";
            std::cout << timer.getCoefficientOfVariation() <<  std::endl;
          }
				}
			}
		}
	}

	std::cout << std::endl;

	return 0;
}

void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, const unsigned int shifts_size, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size) {
  try {
    *shifts_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, shifts_size * sizeof(float), 0, 0);
    *dispersedData_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, dispersedData_size * sizeof(dataType), 0, 0);
    *dedispersedData_d = cl::Buffer(clContext, CL_MEM_READ_WRITE, dedispersedData_size * sizeof(dataType), 0, 0);
    clQueue->enqueueWriteBuffer(*shifts_d, CL_FALSE, 0, shifts_size * sizeof(float), reinterpret_cast< void * >(shifts->data()));
  } catch ( cl::Error & err ) {
    std::cerr << "OpenCL error: " << isa::utils::toString(err.err()) << "." << std::endl;
  }
}

<|endoftext|>


<commit_before>// Demonstrates usage of TEveJetCone class.
// Author: Jochen Thaeder

const char* esd_geom_file_name = "http://root.cern.ch/files/alice_ESDgeometry.root";

void jetcone()
{
   TEveManager::Create();

   using namespace TMath;

   TRandom r(0);

   // -- Set Constants
   Int_t nCones  = 10;
   Int_t nTracks = 200;

   Float_t coneRadius = 0.4;
   Float_t length = 300.;

   // -- Define palette
   gStyle->SetPalette(1, 0);
   TEveRGBAPalette* pal = new TEveRGBAPalette(0, 500);

   // -----------------------------------------------------------------------------------
   // -- Line sets
   // -----------------------------------------------------------------------------------

   // -- Define cone center
   TEveStraightLineSet* axis = new TEveStraightLineSet("Cone Axis");
   axis->SetLineColor(kGreen);
   axis->SetLineWidth(2);

   TEveStraightLineSet* tracksXYZ = new TEveStraightLineSet("StraightLinesXYZ");
   tracksXYZ->SetLineColor(kRed);
   tracksXYZ->SetLineWidth(2);

   TEveStraightLineSet* tracksEtaPhi = new TEveStraightLineSet("StraightLinesEtaPhi");
   tracksEtaPhi->SetLineColor(kYellow);
   tracksEtaPhi->SetLineWidth(2);

   TEveStraightLineSet* tracksSeedEtaPhi = new TEveStraightLineSet("StraightLinesEtaPhiSeed");
   tracksSeedEtaPhi->SetLineColor(kBlue);
   tracksSeedEtaPhi->SetLineWidth(2);

   // -----------------------------------------------------------------------------------
   // -- Draw track distribution in XYZ ( in TPC Volume ) ( +/-250, +/-250, +/-250 )
   // -----------------------------------------------------------------------------------

   for ( Int_t track=0; track < nTracks ; track++ ) {

      Float_t trackX = r.Uniform(-250.0, 250.0);
      Float_t trackY = r.Uniform(-250.0, 250.0);
      Float_t trackZ = r.Uniform(-250.0, 250.0);
      Float_t trackR = (Float_t) Sqrt ( trackX*trackX + trackY*trackY + trackZ*trackZ );

      /*
        Float_t trackEta =  0.5 * (Float_t) Log( (Double_t)(( trackR+trackZ )/( trackR-trackZ )) );
        Float_t trackPhi = (Float_t) ATan2( (Double_t) trackY, (Double_t) trackX );
        if ( trackPhi < 0. ) trackPhi += (Float_t) TwoPi();
      */

      TEveVector trackDir(trackX/trackR, trackY/trackR ,trackZ/trackR);
      TEveVector trackEnd = trackDir * length;
      tracksXYZ->AddLine(0., 0., 0., trackEnd.fX, trackEnd.fY, trackEnd.fZ );
   }

   // -----------------------------------------------------------------------------------
   // -- Draw track distribution in eta phi ( in TPC Volume ) ( +/-0.9, {0, 2Pi} )
   // -----------------------------------------------------------------------------------

   for ( Int_t track=0; track < nTracks ; track++ ) {

      Float_t trackEta = r.Uniform(-0.9, 0.9);
      Float_t trackPhi = r.Uniform(0.0, TwoPi());

      TEveVector trackDir( GetTEveVector(trackEta, trackPhi) );
      TEveVector trackEnd = trackDir * length;

      if ( trackEta > coneRadius || trackEta < -coneRadius )
         tracksEtaPhi->AddLine(0., 0., 0., trackEnd.fX, trackEnd.fY, trackEnd.fZ );
      else
         tracksSeedEtaPhi->AddLine(0., 0., 0., trackEnd.fX, trackEnd.fY, trackEnd.fZ );
   }

   // -----------------------------------------------------------------------------------
   // -- Draw cones
   // -----------------------------------------------------------------------------------

   for ( Int_t iter = 0; iter < nCones; ++iter ) {

      // -- Get Random ( eta ,phi )
      Float_t coneEta = r.Uniform(-0.9, 0.9);
      Float_t conePhi = r.Uniform(0.0, TwoPi() );

      // -- Primary vertx as origin
      TEveVector coneOrigin(0.0,0.0,0.0);

      // -- Get Cone Axis - axis line 10% longer than cone height
      TEveVector coneAxis ( GetTEveVector( coneEta, conePhi) );
      coneAxis *= length * 1.1;

      axis->AddLine( 0., 0., 0., coneAxis.fX, coneAxis.fY, coneAxis.fZ );

      // -- Draw jet cone
      TEveJetCone* jetCone = new TEveJetCone("JetCone");
      jetCone->SetCylinder( 250., 250. );
      if ( (jetCone->AddCone( coneEta, conePhi, coneRadius   ) ) != -1)
         gEve->AddElement( jetCone );
   }

   // -----------------------------------------------------------------------------------

   // -- Add cone axis
   gEve->AddElement(axis);

   // -- Add lines
   //  gEve->AddElement(tracksXYZ);
   gEve->AddElement(tracksSeedEtaPhi);
   gEve->AddElement(tracksEtaPhi);

   // -- Load TPC geometry
   geomGentleTPC();

   gEve->Redraw3D(kTRUE);

   return;
}

// ################################################################################
// ################################################################################

// ################################################################################
TEveVector GetTEveVector( Float_t& eta, Float_t& phi )
{
  TEveVector vec( (Float_t) Cos ( (Double_t) phi)/ CosH( (Double_t) eta ),
		  (Float_t) Sin ( (Double_t) phi)/ CosH( (Double_t) eta ),
		  (Float_t) TanH( (Double_t) eta ) );
  return vec;
}

// ################################################################################
void geomGentleTPC()
{
   // Simple geometry
   TFile* geom = TFile::Open(esd_geom_file_name, "CACHEREAD");
   if (!geom)
      return;

   TEveGeoShapeExtract* gse = (TEveGeoShapeExtract*) geom->Get("Gentle");
   TEveGeoShape* gsre = TEveGeoShape::ImportShapeExtract(gse, 0);
   geom->Close();
   delete geom;

   gEve->AddGlobalElement(gsre);

   TEveElement* elTRD = gsre->FindChild("TRD+TOF");
   elTRD->SetRnrState(kFALSE);

   TEveElement* elPHOS = gsre->FindChild("PHOS");
   elPHOS->SetRnrState(kFALSE);

   TEveElement* elHMPID = gsre->FindChild("HMPID");
   elHMPID->SetRnrState(kFALSE);
}
<commit_msg>Make jet-cones pickable in the 3d view.<commit_after>// Demonstrates usage of TEveJetCone class.
// Author: Jochen Thaeder

const char* esd_geom_file_name = "http://root.cern.ch/files/alice_ESDgeometry.root";

void jetcone()
{
   TEveManager::Create();

   using namespace TMath;

   TRandom r(0);

   // -- Set Constants
   Int_t nCones  = 10;
   Int_t nTracks = 200;

   Float_t coneRadius = 0.4;
   Float_t length = 300.;

   // -- Define palette
   gStyle->SetPalette(1, 0);
   TEveRGBAPalette* pal = new TEveRGBAPalette(0, 500);

   // -----------------------------------------------------------------------------------
   // -- Line sets
   // -----------------------------------------------------------------------------------

   // -- Define cone center
   TEveStraightLineSet* axis = new TEveStraightLineSet("Cone Axis");
   axis->SetLineColor(kGreen);
   axis->SetLineWidth(2);

   TEveStraightLineSet* tracksXYZ = new TEveStraightLineSet("StraightLinesXYZ");
   tracksXYZ->SetLineColor(kRed);
   tracksXYZ->SetLineWidth(2);

   TEveStraightLineSet* tracksEtaPhi = new TEveStraightLineSet("StraightLinesEtaPhi");
   tracksEtaPhi->SetLineColor(kYellow);
   tracksEtaPhi->SetLineWidth(2);

   TEveStraightLineSet* tracksSeedEtaPhi = new TEveStraightLineSet("StraightLinesEtaPhiSeed");
   tracksSeedEtaPhi->SetLineColor(kBlue);
   tracksSeedEtaPhi->SetLineWidth(2);

   // -----------------------------------------------------------------------------------
   // -- Draw track distribution in XYZ ( in TPC Volume ) ( +/-250, +/-250, +/-250 )
   // -----------------------------------------------------------------------------------

   for ( Int_t track=0; track < nTracks ; track++ ) {

      Float_t trackX = r.Uniform(-250.0, 250.0);
      Float_t trackY = r.Uniform(-250.0, 250.0);
      Float_t trackZ = r.Uniform(-250.0, 250.0);
      Float_t trackR = (Float_t) Sqrt ( trackX*trackX + trackY*trackY + trackZ*trackZ );

      /*
        Float_t trackEta =  0.5 * (Float_t) Log( (Double_t)(( trackR+trackZ )/( trackR-trackZ )) );
        Float_t trackPhi = (Float_t) ATan2( (Double_t) trackY, (Double_t) trackX );
        if ( trackPhi < 0. ) trackPhi += (Float_t) TwoPi();
      */

      TEveVector trackDir(trackX/trackR, trackY/trackR ,trackZ/trackR);
      TEveVector trackEnd = trackDir * length;
      tracksXYZ->AddLine(0., 0., 0., trackEnd.fX, trackEnd.fY, trackEnd.fZ );
   }

   // -----------------------------------------------------------------------------------
   // -- Draw track distribution in eta phi ( in TPC Volume ) ( +/-0.9, {0, 2Pi} )
   // -----------------------------------------------------------------------------------

   for ( Int_t track=0; track < nTracks ; track++ ) {

      Float_t trackEta = r.Uniform(-0.9, 0.9);
      Float_t trackPhi = r.Uniform(0.0, TwoPi());

      TEveVector trackDir( GetTEveVector(trackEta, trackPhi) );
      TEveVector trackEnd = trackDir * length;

      if ( trackEta > coneRadius || trackEta < -coneRadius )
         tracksEtaPhi->AddLine(0., 0., 0., trackEnd.fX, trackEnd.fY, trackEnd.fZ );
      else
         tracksSeedEtaPhi->AddLine(0., 0., 0., trackEnd.fX, trackEnd.fY, trackEnd.fZ );
   }

   // -----------------------------------------------------------------------------------
   // -- Draw cones
   // -----------------------------------------------------------------------------------

   for ( Int_t iter = 0; iter < nCones; ++iter ) {

      // -- Get Random ( eta ,phi )
      Float_t coneEta = r.Uniform(-0.9, 0.9);
      Float_t conePhi = r.Uniform(0.0, TwoPi() );

      // -- Primary vertx as origin
      TEveVector coneOrigin(0.0,0.0,0.0);

      // -- Get Cone Axis - axis line 10% longer than cone height
      TEveVector coneAxis ( GetTEveVector( coneEta, conePhi) );
      coneAxis *= length * 1.1;

      axis->AddLine( 0., 0., 0., coneAxis.fX, coneAxis.fY, coneAxis.fZ );

      // -- Draw jet cone
      TEveJetCone* jetCone = new TEveJetCone("JetCone");
      jetCone->SetPickable(kTRUE);
      jetCone->SetCylinder( 250., 250. );
      if ( (jetCone->AddCone( coneEta, conePhi, coneRadius   ) ) != -1)
         gEve->AddElement( jetCone );
   }

   // -----------------------------------------------------------------------------------

   // -- Add cone axis
   gEve->AddElement(axis);

   // -- Add lines
   //  gEve->AddElement(tracksXYZ);
   gEve->AddElement(tracksSeedEtaPhi);
   gEve->AddElement(tracksEtaPhi);

   // -- Load TPC geometry
   geomGentleTPC();

   gEve->Redraw3D(kTRUE);

   return;
}

// ################################################################################
// ################################################################################

// ################################################################################
TEveVector GetTEveVector( Float_t& eta, Float_t& phi )
{
  TEveVector vec( (Float_t) Cos ( (Double_t) phi)/ CosH( (Double_t) eta ),
		  (Float_t) Sin ( (Double_t) phi)/ CosH( (Double_t) eta ),
		  (Float_t) TanH( (Double_t) eta ) );
  return vec;
}

// ################################################################################
void geomGentleTPC()
{
   // Simple geometry
   TFile* geom = TFile::Open(esd_geom_file_name, "CACHEREAD");
   if (!geom)
      return;

   TEveGeoShapeExtract* gse = (TEveGeoShapeExtract*) geom->Get("Gentle");
   TEveGeoShape* gsre = TEveGeoShape::ImportShapeExtract(gse, 0);
   geom->Close();
   delete geom;

   gEve->AddGlobalElement(gsre);

   TEveElement* elTRD = gsre->FindChild("TRD+TOF");
   elTRD->SetRnrState(kFALSE);

   TEveElement* elPHOS = gsre->FindChild("PHOS");
   elPHOS->SetRnrState(kFALSE);

   TEveElement* elHMPID = gsre->FindChild("HMPID");
   elHMPID->SetRnrState(kFALSE);
}
<|endoftext|>


<commit_before>#include "Avion.h"
#include <string.h>

#define SEP ';'

void Avion::accionar() {
	this->estrategia.operar();
}

Avion::Avion(const Avion& avion): estrategia(avion.estrategia) {
}

Avion::Avion(const EstrategiaAvion& estrategia): estrategia(estrategia) {
}

Avion::Avion(const std::string& s){
	deserializar(s);
}

Avion::~Avion() {
}

bool Avion::operator<(const Avion& avion) const {
	return this->estrategia < avion.estrategia;
}

const char* Avion::serializar(){

	static char serial[32];
	std::stringstream ss;

	ss << "AVION" << SEP << determinarPrioridad();
	ss >> serial ;

	return serial;
}

void Avion::deserializar (const std::string& s){

}

int Avion::determinarPrioridad(){
	return this->estrategia.determinarPrioridad();
}
<commit_msg>Se agrega la deserialización del avión, segun la prioridad<commit_after>#include "Avion.h"
#include <string.h>
#include <iostream>

#define SEP ';'

void Avion::accionar() {
	this->estrategia.operar();
}

Avion::Avion(const Avion& avion): estrategia(avion.estrategia) {
}

Avion::Avion(const EstrategiaAvion& estrategia): estrategia(estrategia) {
}

Avion::Avion(const std::string& s){
	deserializar(s);
}

Avion::~Avion() {
}

bool Avion::operator<(const Avion& avion) const {
	return this->estrategia < avion.estrategia;
}

const char* Avion::serializar(){

	static char serial[32];
	std::stringstream ss;

	ss << "AVION" << SEP << determinarPrioridad();
	ss >> serial ;

	return serial;
}

void Avion::deserializar (const std::string& s){
	Utilitario utilitario;
	int codEstrategia = utilitario.convertirAEntero( utilitario.separar(s, SEP, 1) );
	if (codEstrategia == 0)
		this->estrategia = EstrategiaAvion (TIERRA);
	else if (codEstrategia == 1)
		this->estrategia = EstrategiaAvion (AIRE);

}

int Avion::determinarPrioridad(){
	return this->estrategia.determinarPrioridad();
}
<|endoftext|>


<commit_before><commit_msg>`class Shader`: Palautettu `private:` & `friend`-määritykset ennalleen.<commit_after><|endoftext|>


<commit_before>#include <cassert>
#include <cstdio>
#include <cstdlib>

#include <memory>

#include "constants.h"
#include "game_renderer.h"
#include "spritemgr.h"

// From game
#include "game.h"
#include "player_input.h"
#include "player.h"

// From sdl_wrapper
#include "sdl_wrapper.h"
#include "event.h"
#include "graphics.h"

// From utils
#include "geometry.h"
#include "logger.h"

PlayerInput input_to_player_input(const Input& input)
{
  PlayerInput pi;
  pi.left = input.left.pressed;
  pi.right = input.right.pressed;
  pi.jump = input.z.pressed;
  pi.shoot = input.x.pressed;
  return pi;
}

void render_statusbar(Surface* surface, unsigned score, unsigned num_ammo, unsigned num_lives)
{
  constexpr auto statusbar_height = WINDOW_SIZE.y() / 12 / 2;
  constexpr auto statusbar_rect = geometry::Rectangle(0, WINDOW_SIZE.y() - statusbar_height,
                                                      WINDOW_SIZE.x(), statusbar_height);

  char statusbar_text[64];
  snprintf(statusbar_text, 64, "Score: %8u Ammo: %2u Life: %u", score, num_ammo, num_lives);

  surface->fill_rect(statusbar_rect, { 0u, 0u, 0u });
  surface->render_text(statusbar_rect.position + geometry::Position(32, 0),
                       statusbar_text,
                       16,
                       { 255u, 255u, 255u });
}

int main()
{
  LOG_INFO("Starting!");

  // Init SDL wrapper
  auto sdl = SDLWrapper::create();
  if (!sdl)
  {
    LOG_CRITICAL("Could not create SDLWrapper");
    return 1;
  }
  if (!sdl->init())
  {
    LOG_CRITICAL("Could not initialize SDLWrapper");
    return 1;
  }
  LOG_INFO("SDLWrapper initialized");

  // Create Window
  auto window = Window::create("OpenCrystalCaves", WINDOW_SIZE);
  if (!window)
  {
    LOG_CRITICAL("Could not create Window");
    return 1;
  }
  auto window_surface = window->get_surface();
  LOG_INFO("Window created");

  // Create game surface
  std::unique_ptr<Surface> game_surface = window->create_surface(CAMERA_SIZE);
  if (!game_surface)
  {
    LOG_CRITICAL("Could not create game surface");
    return 1;
  }
  LOG_INFO("Game surface created");

  // Create event handler
  auto event = Event::create();
  if (!event)
  {
    LOG_CRITICAL("Could not create event handler");
    return 1;
  }

  // Load tileset
  SpriteManager sprite_manager;
  if (!sprite_manager.load_tileset("media/sprites.bmp"))
  {
    LOG_CRITICAL("Could not load tileset");
    return 1;
  }
  LOG_INFO("Tileset loaded");

  // Create Game
  std::unique_ptr<Game> game = Game::create();
  if (!game)
  {
    LOG_CRITICAL("Could not create Game");
    return 1;
  }
  if (!game->init())
  {
    LOG_CRITICAL("Could not initialize Game");
    return 1;
  }
  LOG_INFO("Game initialized");

  // Create GameRenderer
  GameRenderer game_renderer(game.get(), &sprite_manager, game_surface.get());

  // Game loop
  {
    // Game variables
    bool paused = false;
    unsigned game_tick = 0u;
    Input input;

    // Debug information
    bool debug = false;

    // Game loop logic
    auto sdl_tick = sdl->get_tick();
    const auto ms_per_update = 57;  // 17.5~ ticks per second
    auto tick_last_update = sdl_tick;
    auto lag = 0u;

    // FPS logic
    auto fps_num_renders = 0u;
    auto fps_last_calc = sdl_tick;
    auto fps_start_time = sdl_tick;
    auto fps = 0u;

    while (true)
    {
      /////////////////////////////////////////////////////////////////////////
      ///
      ///  Logic
      ///
      /////////////////////////////////////////////////////////////////////////
      sdl_tick = sdl->get_tick();
      auto elapsed_ticks = sdl_tick - tick_last_update;
      tick_last_update = sdl_tick;
      lag += elapsed_ticks;
      while (lag >= ms_per_update)
      {
        // Read input
        event->poll_event(&input);

        // Handle input
        if (input.quit)
        {
          return 0;  // Quit ASAP
        }
        if (input.num_1.pressed && !input.num_1.repeated)
        {
          debug = !debug;
        }
        if (input.enter.pressed && !input.enter.repeated)
        {
          paused = !paused;
        }

        if (!paused || (paused && input.space.pressed && !input.space.repeated))
        {
          // Call game loop
          game->update(game_tick, input_to_player_input(input));
          game_tick += 1;
        }

        lag -= ms_per_update;
      }

      /////////////////////////////////////////////////////////////////////////
      ///
      ///  Render
      ///
      /////////////////////////////////////////////////////////////////////////

      // Clear window surface
      window_surface->fill_rect(geometry::Rectangle(0, 0, WINDOW_SIZE), { 33u, 33u, 33u });

      // Render game
      game_renderer.render_game(game_tick);

      // Render game surface to window surface, centered and scaled
      window_surface->blit_surface(game_surface.get(),
                                   geometry::Rectangle(0, 0, CAMERA_SIZE),
                                   geometry::Rectangle((WINDOW_SIZE - CAMERA_SIZE_SCALED) / 2, CAMERA_SIZE_SCALED),
                                   BlitType::SCALE);

      // Render statusbar
      render_statusbar(window_surface.get(), game->get_score(), game->get_num_ammo(), game->get_num_lives());

      // Render FPS
      auto fps_str = "fps: " + std::to_string(fps);
      window_surface->render_text(geometry::Position(5, 5), fps_str, 12, { 255u, 255u, 255u });

      // Debug
      if (debug)
      {
        // Put a black box where we're going to the draw the debug text
        window_surface->fill_rect({ 0, 24, 200, 165 }, { 0u, 0u, 0u });

        const auto& game_camera = game_renderer.get_game_camera();

        // Debug text
        const auto camera_position_str = "camera position: (" + std::to_string(game_camera.position.x()) + ", " + std::to_string(game_camera.position.y()) + ")";
        const auto player_position_str = "player position: (" + std::to_string(game->get_player().position.x()) + ", " + std::to_string(game->get_player().position.y()) + ")";
        const auto player_velocity_str = "player velocity: (" + std::to_string(game->get_player().velocity.x()) + ", " + std::to_string(game->get_player().velocity.y()) + ")";
        const auto player_walking_str  = std::string("player walking: ") + (game->get_player().walking ? "true" : "false");
        const auto player_jumping_str  = std::string("player jumping: ") + (game->get_player().jumping ? "true" : "false");
        const auto player_falling_str  = std::string("player falling: ") + (game->get_player().falling ? "true" : "false");
        const auto player_shooting_str = std::string("player shooting: ") + (game->get_player().shooting ? "true" : "false");
        const auto collide_str         = std::string("player collide: ")  + (game->get_player().collide_x ? "x " : "_ ") + (game->get_player().collide_y ? "y" : "_");

        window_surface->render_text(geometry::Position(5,  25), camera_position_str, 12, { 255u, 0u, 0u });
        window_surface->render_text(geometry::Position(5,  45), player_position_str, 12, { 255u, 0u, 0u });
        window_surface->render_text(geometry::Position(5,  65), player_velocity_str, 12, { 255u, 0u, 0u });
        window_surface->render_text(geometry::Position(5,  85), player_walking_str , 12, { 255u, 0u, 0u });
        window_surface->render_text(geometry::Position(5, 105), player_jumping_str , 12, { 255u, 0u, 0u });
        window_surface->render_text(geometry::Position(5, 125), player_falling_str , 12, { 255u, 0u, 0u });
        window_surface->render_text(geometry::Position(5, 145), player_shooting_str, 12, { 255u, 0u, 0u });
        window_surface->render_text(geometry::Position(5, 165), collide_str        , 12, { 255u, 0u, 0u });

      }

      // Update screen
      window->refresh();

      // Calculate FPS each second
      fps_num_renders++;
      if (sdl_tick >= (fps_last_calc + 1000))
      {
        const auto total_time = sdl_tick - fps_start_time;
        fps = fps_num_renders / (total_time / 1000);
        fps_last_calc = sdl_tick;

        // Reset
        fps_num_renders = 0;
        fps_start_time = sdl_tick;
      }
    }
  }

  return 0;
}
<commit_msg>Use larger statusbar text font<commit_after>#include <cassert>
#include <cstdio>
#include <cstdlib>

#include <memory>

#include "constants.h"
#include "game_renderer.h"
#include "spritemgr.h"

// From game
#include "game.h"
#include "player_input.h"
#include "player.h"

// From sdl_wrapper
#include "sdl_wrapper.h"
#include "event.h"
#include "graphics.h"

// From utils
#include "geometry.h"
#include "logger.h"

PlayerInput input_to_player_input(const Input& input)
{
  PlayerInput pi;
  pi.left = input.left.pressed;
  pi.right = input.right.pressed;
  pi.jump = input.z.pressed;
  pi.shoot = input.x.pressed;
  return pi;
}

void render_statusbar(Surface* surface, unsigned score, unsigned num_ammo, unsigned num_lives)
{
  constexpr auto statusbar_height = WINDOW_SIZE.y() / 12 / 2;
  constexpr auto statusbar_rect = geometry::Rectangle(0, WINDOW_SIZE.y() - statusbar_height,
                                                      WINDOW_SIZE.x(), statusbar_height);

  char statusbar_text[64];
  snprintf(statusbar_text, 64, "Score: %8u Ammo: %2u Life: %u", score, num_ammo, num_lives);

  surface->fill_rect(statusbar_rect, { 0u, 0u, 0u });
  surface->render_text(statusbar_rect.position + geometry::Position(32, 0),
                       statusbar_text,
                       24,
                       { 255u, 255u, 255u });
}

int main()
{
  LOG_INFO("Starting!");

  // Init SDL wrapper
  auto sdl = SDLWrapper::create();
  if (!sdl)
  {
    LOG_CRITICAL("Could not create SDLWrapper");
    return 1;
  }
  if (!sdl->init())
  {
    LOG_CRITICAL("Could not initialize SDLWrapper");
    return 1;
  }
  LOG_INFO("SDLWrapper initialized");

  // Create Window
  auto window = Window::create("OpenCrystalCaves", WINDOW_SIZE);
  if (!window)
  {
    LOG_CRITICAL("Could not create Window");
    return 1;
  }
  auto window_surface = window->get_surface();
  LOG_INFO("Window created");

  // Create game surface
  std::unique_ptr<Surface> game_surface = window->create_surface(CAMERA_SIZE);
  if (!game_surface)
  {
    LOG_CRITICAL("Could not create game surface");
    return 1;
  }
  LOG_INFO("Game surface created");

  // Create event handler
  auto event = Event::create();
  if (!event)
  {
    LOG_CRITICAL("Could not create event handler");
    return 1;
  }

  // Load tileset
  SpriteManager sprite_manager;
  if (!sprite_manager.load_tileset("media/sprites.bmp"))
  {
    LOG_CRITICAL("Could not load tileset");
    return 1;
  }
  LOG_INFO("Tileset loaded");

  // Create Game
  std::unique_ptr<Game> game = Game::create();
  if (!game)
  {
    LOG_CRITICAL("Could not create Game");
    return 1;
  }
  if (!game->init())
  {
    LOG_CRITICAL("Could not initialize Game");
    return 1;
  }
  LOG_INFO("Game initialized");

  // Create GameRenderer
  GameRenderer game_renderer(game.get(), &sprite_manager, game_surface.get());

  // Game loop
  {
    // Game variables
    bool paused = false;
    unsigned game_tick = 0u;
    Input input;

    // Debug information
    bool debug = false;

    // Game loop logic
    auto sdl_tick = sdl->get_tick();
    const auto ms_per_update = 57;  // 17.5~ ticks per second
    auto tick_last_update = sdl_tick;
    auto lag = 0u;

    // FPS logic
    auto fps_num_renders = 0u;
    auto fps_last_calc = sdl_tick;
    auto fps_start_time = sdl_tick;
    auto fps = 0u;

    while (true)
    {
      /////////////////////////////////////////////////////////////////////////
      ///
      ///  Logic
      ///
      /////////////////////////////////////////////////////////////////////////
      sdl_tick = sdl->get_tick();
      auto elapsed_ticks = sdl_tick - tick_last_update;
      tick_last_update = sdl_tick;
      lag += elapsed_ticks;
      while (lag >= ms_per_update)
      {
        // Read input
        event->poll_event(&input);

        // Handle input
        if (input.quit)
        {
          return 0;  // Quit ASAP
        }
        if (input.num_1.pressed && !input.num_1.repeated)
        {
          debug = !debug;
        }
        if (input.enter.pressed && !input.enter.repeated)
        {
          paused = !paused;
        }

        if (!paused || (paused && input.space.pressed && !input.space.repeated))
        {
          // Call game loop
          game->update(game_tick, input_to_player_input(input));
          game_tick += 1;
        }

        lag -= ms_per_update;
      }

      /////////////////////////////////////////////////////////////////////////
      ///
      ///  Render
      ///
      /////////////////////////////////////////////////////////////////////////

      // Clear window surface
      window_surface->fill_rect(geometry::Rectangle(0, 0, WINDOW_SIZE), { 33u, 33u, 33u });

      // Render game
      game_renderer.render_game(game_tick);

      // Render game surface to window surface, centered and scaled
      window_surface->blit_surface(game_surface.get(),
                                   geometry::Rectangle(0, 0, CAMERA_SIZE),
                                   geometry::Rectangle((WINDOW_SIZE - CAMERA_SIZE_SCALED) / 2, CAMERA_SIZE_SCALED),
                                   BlitType::SCALE);

      // Render statusbar
      render_statusbar(window_surface.get(), game->get_score(), game->get_num_ammo(), game->get_num_lives());

      // Render FPS
      auto fps_str = "fps: " + std::to_string(fps);
      window_surface->render_text(geometry::Position(5, 5), fps_str, 12, { 255u, 255u, 255u });

      // Debug
      if (debug)
      {
        // Put a black box where we're going to the draw the debug text
        window_surface->fill_rect({ 0, 24, 200, 165 }, { 0u, 0u, 0u });

        const auto& game_camera = game_renderer.get_game_camera();

        // Debug text
        const auto camera_position_str = "camera position: (" + std::to_string(game_camera.position.x()) + ", " + std::to_string(game_camera.position.y()) + ")";
        const auto player_position_str = "player position: (" + std::to_string(game->get_player().position.x()) + ", " + std::to_string(game->get_player().position.y()) + ")";
        const auto player_velocity_str = "player velocity: (" + std::to_string(game->get_player().velocity.x()) + ", " + std::to_string(game->get_player().velocity.y()) + ")";
        const auto player_walking_str  = std::string("player walking: ") + (game->get_player().walking ? "true" : "false");
        const auto player_jumping_str  = std::string("player jumping: ") + (game->get_player().jumping ? "true" : "false");
        const auto player_falling_str  = std::string("player falling: ") + (game->get_player().falling ? "true" : "false");
        const auto player_shooting_str = std::string("player shooting: ") + (game->get_player().shooting ? "true" : "false");
        const auto collide_str         = std::string("player collide: ")  + (game->get_player().collide_x ? "x " : "_ ") + (game->get_player().collide_y ? "y" : "_");

        window_surface->render_text(geometry::Position(5,  25), camera_position_str, 12, { 255u, 0u, 0u });
        window_surface->render_text(geometry::Position(5,  45), player_position_str, 12, { 255u, 0u, 0u });
        window_surface->render_text(geometry::Position(5,  65), player_velocity_str, 12, { 255u, 0u, 0u });
        window_surface->render_text(geometry::Position(5,  85), player_walking_str , 12, { 255u, 0u, 0u });
        window_surface->render_text(geometry::Position(5, 105), player_jumping_str , 12, { 255u, 0u, 0u });
        window_surface->render_text(geometry::Position(5, 125), player_falling_str , 12, { 255u, 0u, 0u });
        window_surface->render_text(geometry::Position(5, 145), player_shooting_str, 12, { 255u, 0u, 0u });
        window_surface->render_text(geometry::Position(5, 165), collide_str        , 12, { 255u, 0u, 0u });

      }

      // Update screen
      window->refresh();

      // Calculate FPS each second
      fps_num_renders++;
      if (sdl_tick >= (fps_last_calc + 1000))
      {
        const auto total_time = sdl_tick - fps_start_time;
        fps = fps_num_renders / (total_time / 1000);
        fps_last_calc = sdl_tick;

        // Reset
        fps_num_renders = 0;
        fps_start_time = sdl_tick;
      }
    }
  }

  return 0;
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-2003, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
/* $Id$ */

// Storing digits in a binary file
// according to the DDL mapping
// To be used in Alice Data Challenges
// This class is used by AliVZERODDL.C macro
// Author: B. Cheynis

#include <Riostream.h>
#include <TObjArray.h>
#include "AliRawDataHeader.h"
#include "AliVZEROBuffer.h"

//#include "TFile.h"
//#include "TTree.h"

ClassImp(AliVZEROBuffer)
//_____________________________________________________________________________
AliVZEROBuffer::AliVZEROBuffer(const char* fileName){
  // Constructor
#ifndef __DECCXX
  f.open(fileName,ios::binary|ios::out);
#else
  f.open(fileName,ios::out);
#endif
  // fout=new TFile(fileName,"recreate");
  // tree=new TTree("tree","Values");
  AliRawDataHeader header;
  f.write((char*)(&header), sizeof(header));
  fNumberOfDigits=0;
  fVerbose=0;
  remove("VZEROdigits.txt");
}

//_____________________________________________________________________________
AliVZEROBuffer::~AliVZEROBuffer(){
  // Destructor, it closes the IO stream
  AliRawDataHeader header;
  header.fSize = f.tellp();
  header.SetAttribute(0);  // valid data
  f.seekp(0);
  f.write((char*)(&header), sizeof(header));
  f.close();
  //delete tree;
  //delete fout;
}

//_____________________________________________________________________________
AliVZEROBuffer::AliVZEROBuffer(const AliVZEROBuffer &source):TObject(source){
  // Copy Constructor
  this->fVerbose=source.fVerbose;
  return;
}

//_____________________________________________________________________________
AliVZEROBuffer& AliVZEROBuffer::operator=(const AliVZEROBuffer &source){
  //Assigment operator
  this->fVerbose=source.fVerbose;
  return *this;
}

//_____________________________________________________________________________
void AliVZEROBuffer::WriteBinary(Int_t cell,Int_t ADC, Int_t Time){
  // It writes VZERO digits as a raw data file.
  // Being called by AliVZERODDL.C

  struct DataFile{
    Int_t cell;
    Int_t ADC;
    Int_t Time;
  };

  DataFile  data;
  data.cell = cell;
  data.ADC  = ADC;
  data.Time = Time;

  ofstream ftxt;
  ftxt.open("VZEROdigits.txt",ios::app);

  fNumberOfDigits++;
  f.write((char*)(&data),sizeof(data));

}

<commit_msg>Removing the access to unused txt file<commit_after>/**************************************************************************
 * Copyright(c) 1998-2003, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
/* $Id$ */

// Storing digits in a binary file
// according to the DDL mapping
// To be used in Alice Data Challenges
// This class is used by AliVZERODDL.C macro
// Author: B. Cheynis

#include <Riostream.h>
#include <TObjArray.h>
#include "AliRawDataHeader.h"
#include "AliVZEROBuffer.h"

//#include "TFile.h"
//#include "TTree.h"

ClassImp(AliVZEROBuffer)
//_____________________________________________________________________________
AliVZEROBuffer::AliVZEROBuffer(const char* fileName){
  // Constructor
#ifndef __DECCXX
  f.open(fileName,ios::binary|ios::out);
#else
  f.open(fileName,ios::out);
#endif
  // fout=new TFile(fileName,"recreate");
  // tree=new TTree("tree","Values");
  AliRawDataHeader header;
  f.write((char*)(&header), sizeof(header));
  fNumberOfDigits=0;
  fVerbose=0;
}

//_____________________________________________________________________________
AliVZEROBuffer::~AliVZEROBuffer(){
  // Destructor, it closes the IO stream
  AliRawDataHeader header;
  header.fSize = f.tellp();
  header.SetAttribute(0);  // valid data
  f.seekp(0);
  f.write((char*)(&header), sizeof(header));
  f.close();
  //delete tree;
  //delete fout;
}

//_____________________________________________________________________________
AliVZEROBuffer::AliVZEROBuffer(const AliVZEROBuffer &source):TObject(source){
  // Copy Constructor
  this->fVerbose=source.fVerbose;
  return;
}

//_____________________________________________________________________________
AliVZEROBuffer& AliVZEROBuffer::operator=(const AliVZEROBuffer &source){
  //Assigment operator
  this->fVerbose=source.fVerbose;
  return *this;
}

//_____________________________________________________________________________
void AliVZEROBuffer::WriteBinary(Int_t cell,Int_t ADC, Int_t Time){
  // It writes VZERO digits as a raw data file.
  // Being called by AliVZERODDL.C

  struct DataFile{
    Int_t cell;
    Int_t ADC;
    Int_t Time;
  };

  DataFile  data;
  data.cell = cell;
  data.ADC  = ADC;
  data.Time = Time;

  fNumberOfDigits++;
  f.write((char*)(&data),sizeof(data));

}

<|endoftext|>