<commit_before>/*
 *  Copyright (C) 2004 Steve Harris, Uwe Koloska
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as
 *  published by the Free Software Foundation; either version 2.1 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  $Id$
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>

#include "lo/lo.h"
using namespace std;

int done = 0;

struct member {
    int pid;
    string hostname;
    lo_timetag timetag;
};

vector<member> members;

int memberCompare(member a, member b);

void error(int num, const char *m, const char *path);

int ping_handler(const char *path, const char *types, lo_arg ** argv,
                int argc, void *data, void *user_data);

int quit_handler(const char *path, const char *types, lo_arg ** argv,
                 int argc, void *data, void *user_data);

int main()
{
    /* make address for multicast ip
     * pick a port number for you by passing NULL as the last argument */

    lo_address t = lo_address_new("224.0.0.1", "7770");
    // lo_server multi = lo_server_new_multicast("drone", "7771", error);
    /* start a new server on port 7770 */
    lo_server_thread st = lo_server_thread_new_multicast("224.0.0.1", "7770", error);

    /* add method that will match the path /foo/bar, with two numbers, coerced
     * to float and int */
    lo_server_thread_add_method(st, "/ping", "is", ping_handler, NULL);

    /* add method that will match the path /quit with no args */
    lo_server_thread_add_method(st, "/quit", "", quit_handler, NULL);

    lo_server_thread_start(st);

    while (!done) {
#ifdef WIN32
        Sleep(1);
#else
        usleep(1500000);
#endif
        char hostname[128] = "";

        gethostname(hostname, sizeof(hostname));

        int pid = getpid();
        // cerr << "pid: " << pid << " || hostname : " << hostname << endl;
        lo_send(t, "/ping", "is", pid, hostname);
    }

    lo_server_thread_free(st);

    return 0;
}

int memberCompare(member a, member b)
{
    int name = strcmp(a.hostname.c_str(), b.hostname.c_str());
    if(name != 0)
    {
        if (name == -1)
        {
            return 0
        }
        return 1
    }
    bool test =  a.pid < b.pid;
    return a.pid < b.pid;
};

void error(int num, const char *msg, const char *path)
{
    printf("liblo server error %d in path %s: %s\n", num, path, msg);
    fflush(stdout);
}

/* catch any incoming messages and display them. returning 1 means that the
 * message has not been fully handled and the server should try other methods */
int ping_handler(const char *path, const char *types, lo_arg ** argv,
                int argc, void *data, void *user_data)
{
    member messageSender;
    messageSender.pid = argv[0]->i;
    char *address = (char *)argv[1];
    messageSender.hostname = address;

    lo_timetag_now(&messageSender.timetag);
    if(!std::binary_search(members.begin(), members.end(), messageSender, memberCompare))
    {
        members.push_back(messageSender);
        cerr << "NEW NODE ~ PID: " << messageSender.pid << " || path : " <<  messageSender.hostname << " || timestamp : " << messageSender.timetag.sec << endl;
    }

    fflush(stdout);

    return 0;
}

int quit_handler(const char *path, const char *types, lo_arg ** argv,
                 int argc, void *data, void *user_data)
{
    done = 1;
    printf("quiting\n\n");
    fflush(stdout);

    return 0;
}

/* vi:set ts=8 sts=4 sw=4: */
<commit_msg>Forgot ;<commit_after>/*
 *  Copyright (C) 2004 Steve Harris, Uwe Koloska
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as
 *  published by the Free Software Foundation; either version 2.1 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  $Id$
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>

#include "lo/lo.h"
using namespace std;

int done = 0;

struct member {
    int pid;
    string hostname;
    lo_timetag timetag;
};

vector<member> members;

int memberCompare(member a, member b);

void error(int num, const char *m, const char *path);

int ping_handler(const char *path, const char *types, lo_arg ** argv,
                int argc, void *data, void *user_data);

int quit_handler(const char *path, const char *types, lo_arg ** argv,
                 int argc, void *data, void *user_data);

int main()
{
    /* make address for multicast ip
     * pick a port number for you by passing NULL as the last argument */

    lo_address t = lo_address_new("224.0.0.1", "7770");
    // lo_server multi = lo_server_new_multicast("drone", "7771", error);
    /* start a new server on port 7770 */
    lo_server_thread st = lo_server_thread_new_multicast("224.0.0.1", "7770", error);

    /* add method that will match the path /foo/bar, with two numbers, coerced
     * to float and int */
    lo_server_thread_add_method(st, "/ping", "is", ping_handler, NULL);

    /* add method that will match the path /quit with no args */
    lo_server_thread_add_method(st, "/quit", "", quit_handler, NULL);

    lo_server_thread_start(st);

    while (!done) {
#ifdef WIN32
        Sleep(1);
#else
        usleep(1500000);
#endif
        char hostname[128] = "";

        gethostname(hostname, sizeof(hostname));

        int pid = getpid();
        // cerr << "pid: " << pid << " || hostname : " << hostname << endl;
        lo_send(t, "/ping", "is", pid, hostname);
    }

    lo_server_thread_free(st);

    return 0;
}

int memberCompare(member a, member b)
{
    int name = strcmp(a.hostname.c_str(), b.hostname.c_str());
    if(name != 0)
    {
        if (name == -1)
        {
            return 0;
        }
        return 1;
    }
    bool test =  a.pid < b.pid;
    return a.pid < b.pid;
};

void error(int num, const char *msg, const char *path)
{
    printf("liblo server error %d in path %s: %s\n", num, path, msg);
    fflush(stdout);
}

/* catch any incoming messages and display them. returning 1 means that the
 * message has not been fully handled and the server should try other methods */
int ping_handler(const char *path, const char *types, lo_arg ** argv,
                int argc, void *data, void *user_data)
{
    member messageSender;
    messageSender.pid = argv[0]->i;
    char *address = (char *)argv[1];
    messageSender.hostname = address;

    lo_timetag_now(&messageSender.timetag);
    if(!std::binary_search(members.begin(), members.end(), messageSender, memberCompare))
    {
        members.push_back(messageSender);
        cerr << "NEW NODE ~ PID: " << messageSender.pid << " || path : " <<  messageSender.hostname << " || timestamp : " << messageSender.timetag.sec << endl;
    }

    fflush(stdout);

    return 0;
}

int quit_handler(const char *path, const char *types, lo_arg ** argv,
                 int argc, void *data, void *user_data)
{
    done = 1;
    printf("quiting\n\n");
    fflush(stdout);

    return 0;
}

/* vi:set ts=8 sts=4 sw=4: */
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Compositor.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "waylandwindowmanagerintegration.h"

#include "waylandobject.h"
#include "wayland_wrapper/wldisplay.h"
#include "wayland_wrapper/wlcompositor.h"

#include "wayland-server.h"
#include "wayland-windowmanager-server-protocol.h"

#include <QtCore/QDebug>

// the protocol files are generated with wayland-scanner, in the following manner:
// wayland-scanner client-header < windowmanager.xml > wayland-windowmanager-client-protocol.h
// wayland-scanner server-header < windowmanager.xml > wayland-windowmanager-server-protocol.h
// wayland-scanner code < windowmanager.xml > wayland-windowmanager-protocol.c
//
// wayland-scanner can be found from wayland sources.

class WindowManagerObject : public Wayland::Object<struct wl_object>
{
public:

    void mapClientToProcess(wl_client *client, uint32_t processId)
    {
        WindowManagerServerIntegration::instance()->mapClientToProcess(client, processId);
    }

    void authenticateWithToken(wl_client *client, const char *authenticationToken)
    {
        WindowManagerServerIntegration::instance()->authenticateWithToken(client, authenticationToken);
    }

    void changeScreenVisibility(wl_client *client, int visible)
    {
        WindowManagerServerIntegration::instance()->changeScreenVisibility(client, visible);
    }

};

void map_client_to_process(wl_client *client, struct wl_windowmanager *windowMgr, uint32_t processId)
{
    reinterpret_cast<WindowManagerObject *>(windowMgr)->mapClientToProcess(client, processId);
}

void authenticate_with_token(wl_client *client, struct wl_windowmanager *windowMgr, const char *wl_authentication_token)
{
    reinterpret_cast<WindowManagerObject *>(windowMgr)->authenticateWithToken(client, wl_authentication_token);
}

const static struct wl_windowmanager_interface windowmanager_interface = {
    map_client_to_process,
    authenticate_with_token
};

WindowManagerServerIntegration *WindowManagerServerIntegration::m_instance = 0;

WindowManagerServerIntegration::WindowManagerServerIntegration(QObject *parent)
    : QObject(parent)
    , m_orientationInDegrees(0)
{
    m_instance = this;
}

void WindowManagerServerIntegration::initialize(Wayland::Display *waylandDisplay)
{
    m_windowManagerObject = new WindowManagerObject();
    waylandDisplay->addGlobalObject(m_windowManagerObject->base(),
                                    &wl_windowmanager_interface, &windowmanager_interface, 0);
}

void WindowManagerServerIntegration::removeClient(wl_client *client)
{
    WaylandManagedClient *managedClient = m_managedClients.take(client);
    delete managedClient;
}

void WindowManagerServerIntegration::mapClientToProcess(wl_client *client, uint32_t processId)
{
    WaylandManagedClient *managedClient = m_managedClients.value(client, new WaylandManagedClient);
    managedClient->m_processId = processId;
    m_managedClients.insert(client, managedClient);
}

void WindowManagerServerIntegration::authenticateWithToken(wl_client *client, const char *token)
{
    WaylandManagedClient *managedClient = m_managedClients.value(client, new WaylandManagedClient);
    managedClient->m_authenticationToken = QByteArray(token);
    m_managedClients.insert(client, managedClient);
}

void WindowManagerServerIntegration::changeScreenVisibility(wl_client *client, int visible)
{
    m_managedClients[client]->m_isVisibleOnScreen = visible != 0;

    qDebug() << Q_FUNC_INFO << visible;
    wl_client_post_event(client, m_windowManagerObject->base(),
                         WL_WINDOWMANAGER_CLIENT_ONSCREEN_VISIBILITY, visible);
}

void WindowManagerServerIntegration::updateOrientation(wl_client *client)
{
    setScreenOrientation(client, m_orientationInDegrees);
}

void WindowManagerServerIntegration::setScreenOrientation(wl_client *client, qint32 orientationInDegrees)
{
    m_orientationInDegrees = orientationInDegrees;
    wl_client_post_event(client, m_windowManagerObject->base(),
                         WL_WINDOWMANAGER_SET_SCREEN_ROTATION, orientationInDegrees);
}

WaylandManagedClient *WindowManagerServerIntegration::managedClient(wl_client *client) const
{
    return m_managedClients.value(client, 0);
}

WindowManagerServerIntegration *WindowManagerServerIntegration::instance()
{
    return m_instance;
}

/// ///
/// / WaylandManagedClient
/// ///

WaylandManagedClient::WaylandManagedClient()
    : m_processId(0)
{
}

qint64 WaylandManagedClient::processId() const
{
    return m_processId;
}

QByteArray WaylandManagedClient::authenticationToken() const
{
    return m_authenticationToken;
}
<commit_msg>Remove debug output<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Compositor.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "waylandwindowmanagerintegration.h"

#include "waylandobject.h"
#include "wayland_wrapper/wldisplay.h"
#include "wayland_wrapper/wlcompositor.h"

#include "wayland-server.h"
#include "wayland-windowmanager-server-protocol.h"

// the protocol files are generated with wayland-scanner, in the following manner:
// wayland-scanner client-header < windowmanager.xml > wayland-windowmanager-client-protocol.h
// wayland-scanner server-header < windowmanager.xml > wayland-windowmanager-server-protocol.h
// wayland-scanner code < windowmanager.xml > wayland-windowmanager-protocol.c
//
// wayland-scanner can be found from wayland sources.

class WindowManagerObject : public Wayland::Object<struct wl_object>
{
public:

    void mapClientToProcess(wl_client *client, uint32_t processId)
    {
        WindowManagerServerIntegration::instance()->mapClientToProcess(client, processId);
    }

    void authenticateWithToken(wl_client *client, const char *authenticationToken)
    {
        WindowManagerServerIntegration::instance()->authenticateWithToken(client, authenticationToken);
    }

    void changeScreenVisibility(wl_client *client, int visible)
    {
        WindowManagerServerIntegration::instance()->changeScreenVisibility(client, visible);
    }

};

void map_client_to_process(wl_client *client, struct wl_windowmanager *windowMgr, uint32_t processId)
{
    reinterpret_cast<WindowManagerObject *>(windowMgr)->mapClientToProcess(client, processId);
}

void authenticate_with_token(wl_client *client, struct wl_windowmanager *windowMgr, const char *wl_authentication_token)
{
    reinterpret_cast<WindowManagerObject *>(windowMgr)->authenticateWithToken(client, wl_authentication_token);
}

const static struct wl_windowmanager_interface windowmanager_interface = {
    map_client_to_process,
    authenticate_with_token
};

WindowManagerServerIntegration *WindowManagerServerIntegration::m_instance = 0;

WindowManagerServerIntegration::WindowManagerServerIntegration(QObject *parent)
    : QObject(parent)
    , m_orientationInDegrees(0)
{
    m_instance = this;
}

void WindowManagerServerIntegration::initialize(Wayland::Display *waylandDisplay)
{
    m_windowManagerObject = new WindowManagerObject();
    waylandDisplay->addGlobalObject(m_windowManagerObject->base(),
                                    &wl_windowmanager_interface, &windowmanager_interface, 0);
}

void WindowManagerServerIntegration::removeClient(wl_client *client)
{
    WaylandManagedClient *managedClient = m_managedClients.take(client);
    delete managedClient;
}

void WindowManagerServerIntegration::mapClientToProcess(wl_client *client, uint32_t processId)
{
    WaylandManagedClient *managedClient = m_managedClients.value(client, new WaylandManagedClient);
    managedClient->m_processId = processId;
    m_managedClients.insert(client, managedClient);
}

void WindowManagerServerIntegration::authenticateWithToken(wl_client *client, const char *token)
{
    WaylandManagedClient *managedClient = m_managedClients.value(client, new WaylandManagedClient);
    managedClient->m_authenticationToken = QByteArray(token);
    m_managedClients.insert(client, managedClient);
}

void WindowManagerServerIntegration::changeScreenVisibility(wl_client *client, int visible)
{
    m_managedClients[client]->m_isVisibleOnScreen = visible != 0;

    wl_client_post_event(client, m_windowManagerObject->base(),
                         WL_WINDOWMANAGER_CLIENT_ONSCREEN_VISIBILITY, visible);
}

void WindowManagerServerIntegration::updateOrientation(wl_client *client)
{
    setScreenOrientation(client, m_orientationInDegrees);
}

void WindowManagerServerIntegration::setScreenOrientation(wl_client *client, qint32 orientationInDegrees)
{
    m_orientationInDegrees = orientationInDegrees;
    wl_client_post_event(client, m_windowManagerObject->base(),
                         WL_WINDOWMANAGER_SET_SCREEN_ROTATION, orientationInDegrees);
}

WaylandManagedClient *WindowManagerServerIntegration::managedClient(wl_client *client) const
{
    return m_managedClients.value(client, 0);
}

WindowManagerServerIntegration *WindowManagerServerIntegration::instance()
{
    return m_instance;
}

/// ///
/// / WaylandManagedClient
/// ///

WaylandManagedClient::WaylandManagedClient()
    : m_processId(0)
{
}

qint64 WaylandManagedClient::processId() const
{
    return m_processId;
}

QByteArray WaylandManagedClient::authenticationToken() const
{
    return m_authenticationToken;
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2012-2014 The SSDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include "log.h"
#include "sorted_set.h"

int main(int argc, char **argv){
	SortedSet zset;

	std::vector<std::string> keys;
	for(int i='a'; i<='z'; i++){
		char buf[10];
		snprintf(buf, sizeof(buf), "%c", i);
		keys.push_back(buf);
	}

	log_debug("");
	srand(time(NULL));
	for(int i=0; i<1000 * 1000; i++){
		std::string &key = keys[rand() % keys.size()];
		zset.add(key, rand()%30 - 15);
	}
	log_debug("");

	const std::string *key;
	int64_t score;
	int n = 0;
	while(zset.front(&key, &score)){
		printf("%s : %4lld\n", key->c_str(), score);
		zset.pop_front();
		n ++;
	}
	log_debug("%d", n);

	return 0;
}
<commit_msg>resolve compile error<commit_after>/*
Copyright (c) 2012-2014 The SSDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include "log.h"
#include "sorted_set.h"

int main(int argc, char **argv){
	SortedSet zset;

	std::vector<std::string> keys;
	for(int i='a'; i<='z'; i++){
		char buf[10];
		snprintf(buf, sizeof(buf), "%c", i);
		keys.push_back(buf);
	}

	log_debug("");
	srand(time(NULL));
	for(int i=0; i<1000 * 1000; i++){
		std::string &key = keys[rand() % keys.size()];
		zset.add(key, rand()%30 - 15);
	}
	log_debug("");

	std::string *key;
	int64_t score;
	int n = 0;
	while(zset.front(key, &score)){
		printf("%s : %4lld\n", key->c_str(), score);
		zset.pop_front();
		n ++;
	}
	log_debug("%d", n);

	return 0;
}
<|endoftext|>


<commit_before>#include "TRDData.h"
#include "TRDModuleImp.h"

#include "AliLog.h"
#include "AliTRDhit.h"
#include "AliTRDcluster.h"
#include "AliTRDcalibDB.h"
#include "AliTRDpadPlane.h"
#include "AliTRDgeometry.h"
#include "AliTRDdigitsManager.h"

using namespace Reve;
using namespace Alieve;
using namespace std;

ClassImp(TRDHits)
ClassImp(TRDDigits)
ClassImp(TRDClusters)

///////////////////////////////////////////////////////////
/////////////   TRDDigits             /////////////////////
///////////////////////////////////////////////////////////

//________________________________________________________
TRDDigits::TRDDigits(TRDChamber *p): OldQuadSet("digits", ""), RenderElement(), fParent(p)
{}

//________________________________________________________
void	TRDDigits::SetData(AliTRDdigitsManager *digits)
{

	fData.Allocate(fParent->rowMax, fParent->colMax, fParent->timeMax);
//	digits->Expand();
	for (Int_t  row = 0;  row <  fParent->rowMax;  row++)
		for (Int_t  col = 0;  col <  fParent->colMax;  col++)
			for (Int_t time = 0; time < fParent->timeMax; time++) {
				if(digits->GetDigitAmp(row, col, time, fParent->GetID()) < 0) continue;
				fData.SetDataUnchecked(row, col, time, digits->GetDigitAmp(row, col, time, fParent->GetID()));
	}
}

//________________________________________________________
void	TRDDigits::ComputeRepresentation()
{
// Calculate digits representation according to user settings. The
// user can set the following parameters:
// - digits scale (log/lin)
// - digits threshold
// - digits apparence (quads/boxes)

	fQuads.clear();
	fBoxes.fBoxes.clear();

	Double_t colSize, rowSize, scale;
	Double_t x, y, z;

	Int_t charge;
	Float_t t0;
	Float_t timeBinSize;

	AliTRDcalibDB* calibration = AliTRDcalibDB::Instance();
  Double_t cloc[4][3], cglo[3];
	Int_t color, dimension;
	fData.Expand();
	for (Int_t  row = 0;  row <  fParent->rowMax;  row++) {
		rowSize = .5 * fParent->fPadPlane->GetRowSize(row);
		z = fParent->fPadPlane->GetRowPos(row) - rowSize;

		for (Int_t  col = 0;  col <  fParent->colMax;  col++) {
			colSize = .5 * fParent->fPadPlane->GetColSize(col);
			y = fParent->fPadPlane->GetColPos(col) - colSize;
			t0 = calibration->GetT0(fParent->fDet, col, row);
			timeBinSize = calibration->GetVdrift(fParent->fDet, col, row)/fParent->samplingFrequency;

			for (Int_t time = 0; time < fParent->timeMax; time++) {
				charge = fData.GetDataUnchecked(row, col, time);
	  		if (charge < fParent->GetDigitsThreshold()) continue;

				x = fParent->fX0 - (time+0.5-t0)*timeBinSize;
				scale = fParent->GetDigitsLog() ? TMath::Log(float(charge))/TMath::Log(1024.) : charge/1024.;
				color  = 50+int(scale*50.);

				cloc[0][2] = z - rowSize * scale;
				cloc[0][1] = y - colSize * scale;
				cloc[0][0] = x;

				cloc[1][2] = z - rowSize * scale;
				cloc[1][1] = y + colSize * scale;
				cloc[1][0] = x;

				cloc[2][2] = z + rowSize * scale;
				cloc[2][1] = y + colSize * scale;
				cloc[2][0] = x;

				cloc[3][2] = z + rowSize * scale;
				cloc[3][1] = y - colSize * scale;
				cloc[3][0] = x;

				Float_t* p;
				if( fParent->GetDigitsBox()){
					fBoxes.fBoxes.push_back(Reve::Box());
					fBoxes.fBoxes.back().color[0] = (UChar_t)color;
					fBoxes.fBoxes.back().color[1] = (UChar_t)color;
					fBoxes.fBoxes.back().color[2] = (UChar_t)color;
					fBoxes.fBoxes.back().color[3] = (UChar_t)color;
					p = fBoxes.fBoxes.back().vertices;
					dimension = 2;
				} else {
					fQuads.push_back(Reve::Quad());
					fQuads.back().ColorFromIdx(color);
					p = fQuads.back().vertices;
					dimension = 1;
				}

				for(int id=0; id<dimension; id++)
				for (Int_t ic = 0; ic < 4; ic++) {
					cloc[ic][0] -= .5 * id * timeBinSize;
					fParent->fGeo->RotateBack(fParent->fDet,cloc[ic],cglo);
	      	p[0] = cglo[0]; p[1] = cglo[1]; p[2] = cglo[2];
					p+=3;
				}
			}  // end time loop
		}  // end col loop
	}  // end row loop
	fData.Compress(1);
}

//________________________________________________________
void TRDDigits::Paint(Option_t *option)
{
	if(fParent->GetDigitsBox()) fBoxes.Paint(option);
	else OldQuadSet::Paint(option);
}

//________________________________________________________
void TRDDigits::Reset()
{
	fQuads.clear();
	fBoxes.fBoxes.clear();
	fData.Reset();
}

///////////////////////////////////////////////////////////
/////////////   TRDHits               /////////////////////
///////////////////////////////////////////////////////////

//________________________________________________________
TRDHits::TRDHits(TRDChamber *p):PointSet("hits", 20), fParent(p)
{}

//________________________________________________________
void TRDHits::PointSelected(Int_t n)
{
	fParent->SpawnEditor();
	AliTRDhit *h = dynamic_cast<AliTRDhit*>(GetPointId(n));
	printf("\nDetector             : %d\n", h->GetDetector());
	printf("Region of production : %c\n", h->FromAmplification() ? 'A' : 'D');
	printf("TR photon            : %s\n", h->FromTRphoton() ? "Yes" : "No");
	printf("Charge               : %d\n", h->GetCharge());
	printf("MC track label       : %d\n", h->GetTrack());
	printf("Time from collision  : %f\n", h->GetTime());
}

///////////////////////////////////////////////////////////
/////////////   TRDHits               /////////////////////
///////////////////////////////////////////////////////////

//________________________________________________________
TRDClusters::TRDClusters(TRDChamber *p):TRDHits(p)
{}

//________________________________________________________
void TRDClusters::PointSelected(Int_t n)
{
	fParent->SpawnEditor();
	AliTRDcluster *c = dynamic_cast<AliTRDcluster*>(GetPointId(n));
	printf("\nDetector             : %d\n", c->GetDetector());
	printf("Charge               : %f\n", c->GetQ());
	printf("Sum S                : %4.0f\n", c->GetSumS());
	printf("Time bin             : %d\n", c->GetLocalTimeBin());
	printf("Signals              : ");
	Short_t *cSignals = c->GetSignals();
	for(Int_t ipad=0; ipad<7; ipad++) printf("%d ", cSignals[ipad]); printf("\n");
	printf("Central pad          : %d\n", c->GetPad());
	printf("MC track labels      : ");
	for(Int_t itrk=0; itrk<3; itrk++) printf("%d ", c->GetLabel(itrk)); printf("\n");
// Bool_t	AliCluster::GetGlobalCov(Float_t* cov) const
// Bool_t	AliCluster::GetGlobalXYZ(Float_t* xyz) const
// Float_t	AliCluster::GetSigmaY2() const
// Float_t	AliCluster::GetSigmaYZ() const
// Float_t	AliCluster::GetSigmaZ2() const
}

///////////////////////////////////////////////////////////
/////////////   TRDHitsEditor         /////////////////////
///////////////////////////////////////////////////////////
TRDHitsEditor::TRDHitsEditor(const TGWindow* p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGedFrame(p, width, height, options, back)
{
	MakeTitle("TRD Hits");

}

TRDHitsEditor::~TRDHitsEditor()
{}

void TRDHitsEditor::SetModel(TObject* obj)
{
	fM = dynamic_cast<TRDHits*>(obj);

// 	Float_t x, y, z;
// 	for(int ihit=0; ihit<fM->GetN(); ihit++){
// 		fM->GetPoint(ihit, x, y, z);
// 		printf("%3d : x=%6.3f y=%6.3f z=%6.3f\n", ihit, x, y, z);
// 	}
}

///////////////////////////////////////////////////////////
/////////////   TRDDigitsEditor       /////////////////////
///////////////////////////////////////////////////////////
TRDDigitsEditor::TRDDigitsEditor(const TGWindow* p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGedFrame(p, width, height, options, back)
{
	MakeTitle("TRD Digits");

}

TRDDigitsEditor::~TRDDigitsEditor()
{}

void TRDDigitsEditor::SetModel(TObject* obj)
{
	fM = dynamic_cast<TRDDigits*>(obj);
	fM->fParent->SpawnEditor();

// 	printf("Chamber %d", fM->fParent->GetID());
// 	for (Int_t  row = 0;  row <  fM->fParent->GetRowMax();  row++)
// 		for (Int_t  col = 0;  col <  fM->fParent->GetColMax();  col++)
// 			for (Int_t time = 0; time < fM->fParent->GetTimeMax(); time++) {
// 				printf("\tA(%d %d %d) = %d\n", row, col, time, fM->fData.GetDataUnchecked(row, col, time));
// 			}
}
<commit_msg>Small change required by the updated AliTRDcluster (Christoph)<commit_after>#include "TRDData.h"
#include "TRDModuleImp.h"

#include "AliLog.h"
#include "AliTRDhit.h"
#include "AliTRDcluster.h"
#include "AliTRDcalibDB.h"
#include "AliTRDpadPlane.h"
#include "AliTRDgeometry.h"
#include "AliTRDdigitsManager.h"

using namespace Reve;
using namespace Alieve;
using namespace std;

ClassImp(TRDHits)
ClassImp(TRDDigits)
ClassImp(TRDClusters)

///////////////////////////////////////////////////////////
/////////////   TRDDigits             /////////////////////
///////////////////////////////////////////////////////////

//________________________________________________________
TRDDigits::TRDDigits(TRDChamber *p): OldQuadSet("digits", ""), RenderElement(), fParent(p)
{}

//________________________________________________________
void	TRDDigits::SetData(AliTRDdigitsManager *digits)
{

	fData.Allocate(fParent->rowMax, fParent->colMax, fParent->timeMax);
//	digits->Expand();
	for (Int_t  row = 0;  row <  fParent->rowMax;  row++)
		for (Int_t  col = 0;  col <  fParent->colMax;  col++)
			for (Int_t time = 0; time < fParent->timeMax; time++) {
				if(digits->GetDigitAmp(row, col, time, fParent->GetID()) < 0) continue;
				fData.SetDataUnchecked(row, col, time, digits->GetDigitAmp(row, col, time, fParent->GetID()));
	}
}

//________________________________________________________
void	TRDDigits::ComputeRepresentation()
{
// Calculate digits representation according to user settings. The
// user can set the following parameters:
// - digits scale (log/lin)
// - digits threshold
// - digits apparence (quads/boxes)

	fQuads.clear();
	fBoxes.fBoxes.clear();

	Double_t colSize, rowSize, scale;
	Double_t x, y, z;

	Int_t charge;
	Float_t t0;
	Float_t timeBinSize;

	AliTRDcalibDB* calibration = AliTRDcalibDB::Instance();
  Double_t cloc[4][3], cglo[3];
	Int_t color, dimension;
	fData.Expand();
	for (Int_t  row = 0;  row <  fParent->rowMax;  row++) {
		rowSize = .5 * fParent->fPadPlane->GetRowSize(row);
		z = fParent->fPadPlane->GetRowPos(row) - rowSize;

		for (Int_t  col = 0;  col <  fParent->colMax;  col++) {
			colSize = .5 * fParent->fPadPlane->GetColSize(col);
			y = fParent->fPadPlane->GetColPos(col) - colSize;
			t0 = calibration->GetT0(fParent->fDet, col, row);
			timeBinSize = calibration->GetVdrift(fParent->fDet, col, row)/fParent->samplingFrequency;

			for (Int_t time = 0; time < fParent->timeMax; time++) {
				charge = fData.GetDataUnchecked(row, col, time);
	  		if (charge < fParent->GetDigitsThreshold()) continue;

				x = fParent->fX0 - (time+0.5-t0)*timeBinSize;
				scale = fParent->GetDigitsLog() ? TMath::Log(float(charge))/TMath::Log(1024.) : charge/1024.;
				color  = 50+int(scale*50.);

				cloc[0][2] = z - rowSize * scale;
				cloc[0][1] = y - colSize * scale;
				cloc[0][0] = x;

				cloc[1][2] = z - rowSize * scale;
				cloc[1][1] = y + colSize * scale;
				cloc[1][0] = x;

				cloc[2][2] = z + rowSize * scale;
				cloc[2][1] = y + colSize * scale;
				cloc[2][0] = x;

				cloc[3][2] = z + rowSize * scale;
				cloc[3][1] = y - colSize * scale;
				cloc[3][0] = x;

				Float_t* p;
				if( fParent->GetDigitsBox()){
					fBoxes.fBoxes.push_back(Reve::Box());
					fBoxes.fBoxes.back().color[0] = (UChar_t)color;
					fBoxes.fBoxes.back().color[1] = (UChar_t)color;
					fBoxes.fBoxes.back().color[2] = (UChar_t)color;
					fBoxes.fBoxes.back().color[3] = (UChar_t)color;
					p = fBoxes.fBoxes.back().vertices;
					dimension = 2;
				} else {
					fQuads.push_back(Reve::Quad());
					fQuads.back().ColorFromIdx(color);
					p = fQuads.back().vertices;
					dimension = 1;
				}

				for(int id=0; id<dimension; id++)
				for (Int_t ic = 0; ic < 4; ic++) {
					cloc[ic][0] -= .5 * id * timeBinSize;
					fParent->fGeo->RotateBack(fParent->fDet,cloc[ic],cglo);
	      	p[0] = cglo[0]; p[1] = cglo[1]; p[2] = cglo[2];
					p+=3;
				}
			}  // end time loop
		}  // end col loop
	}  // end row loop
	fData.Compress(1);
}

//________________________________________________________
void TRDDigits::Paint(Option_t *option)
{
	if(fParent->GetDigitsBox()) fBoxes.Paint(option);
	else OldQuadSet::Paint(option);
}

//________________________________________________________
void TRDDigits::Reset()
{
	fQuads.clear();
	fBoxes.fBoxes.clear();
	fData.Reset();
}

///////////////////////////////////////////////////////////
/////////////   TRDHits               /////////////////////
///////////////////////////////////////////////////////////

//________________________________________________________
TRDHits::TRDHits(TRDChamber *p):PointSet("hits", 20), fParent(p)
{}

//________________________________________________________
void TRDHits::PointSelected(Int_t n)
{
	fParent->SpawnEditor();
	AliTRDhit *h = dynamic_cast<AliTRDhit*>(GetPointId(n));
	printf("\nDetector             : %d\n", h->GetDetector());
	printf("Region of production : %c\n", h->FromAmplification() ? 'A' : 'D');
	printf("TR photon            : %s\n", h->FromTRphoton() ? "Yes" : "No");
	printf("Charge               : %d\n", h->GetCharge());
	printf("MC track label       : %d\n", h->GetTrack());
	printf("Time from collision  : %f\n", h->GetTime());
}

///////////////////////////////////////////////////////////
/////////////   TRDHits               /////////////////////
///////////////////////////////////////////////////////////

//________________________________________________________
TRDClusters::TRDClusters(TRDChamber *p):TRDHits(p)
{}

//________________________________________________________
void TRDClusters::PointSelected(Int_t n)
{
	fParent->SpawnEditor();
	AliTRDcluster *c = dynamic_cast<AliTRDcluster*>(GetPointId(n));
	printf("\nDetector             : %d\n", c->GetDetector());
	printf("Charge               : %f\n", c->GetQ());
	printf("Sum S                : %4.0f\n", c->GetSumS());
	printf("Time bin             : %d\n", c->GetLocalTimeBin());
	printf("Signals              : ");
	Short_t *cSignals = c->GetSignals();
	for(Int_t ipad=0; ipad<7; ipad++) printf("%d ", cSignals[ipad]); printf("\n");
	printf("Central pad          : %d\n", c->GetPadCol());
	printf("MC track labels      : ");
	for(Int_t itrk=0; itrk<3; itrk++) printf("%d ", c->GetLabel(itrk)); printf("\n");
// Bool_t	AliCluster::GetGlobalCov(Float_t* cov) const
// Bool_t	AliCluster::GetGlobalXYZ(Float_t* xyz) const
// Float_t	AliCluster::GetSigmaY2() const
// Float_t	AliCluster::GetSigmaYZ() const
// Float_t	AliCluster::GetSigmaZ2() const
}

///////////////////////////////////////////////////////////
/////////////   TRDHitsEditor         /////////////////////
///////////////////////////////////////////////////////////
TRDHitsEditor::TRDHitsEditor(const TGWindow* p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGedFrame(p, width, height, options, back)
{
	MakeTitle("TRD Hits");

}

TRDHitsEditor::~TRDHitsEditor()
{}

void TRDHitsEditor::SetModel(TObject* obj)
{
	fM = dynamic_cast<TRDHits*>(obj);

// 	Float_t x, y, z;
// 	for(int ihit=0; ihit<fM->GetN(); ihit++){
// 		fM->GetPoint(ihit, x, y, z);
// 		printf("%3d : x=%6.3f y=%6.3f z=%6.3f\n", ihit, x, y, z);
// 	}
}

///////////////////////////////////////////////////////////
/////////////   TRDDigitsEditor       /////////////////////
///////////////////////////////////////////////////////////
TRDDigitsEditor::TRDDigitsEditor(const TGWindow* p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGedFrame(p, width, height, options, back)
{
	MakeTitle("TRD Digits");

}

TRDDigitsEditor::~TRDDigitsEditor()
{}

void TRDDigitsEditor::SetModel(TObject* obj)
{
	fM = dynamic_cast<TRDDigits*>(obj);
	fM->fParent->SpawnEditor();

// 	printf("Chamber %d", fM->fParent->GetID());
// 	for (Int_t  row = 0;  row <  fM->fParent->GetRowMax();  row++)
// 		for (Int_t  col = 0;  col <  fM->fParent->GetColMax();  col++)
// 			for (Int_t time = 0; time < fM->fParent->GetTimeMax(); time++) {
// 				printf("\tA(%d %d %d) = %d\n", row, col, time, fM->fData.GetDataUnchecked(row, col, time));
// 			}
}
<|endoftext|>


<commit_before>//
// Urho3D Engine
// Copyright (c) 2008-2011 Lasse rni
//
// 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 "Precompiled.h"
#include "Thread.h"

#ifdef WIN32
#include <windows.h>
#else
#include <pthread.h>
#endif

#include "DebugNew.h"

#ifdef WIN32
DWORD WINAPI ThreadFunctionStatic(void* data)
{
    Thread* thread = static_cast<Thread*>(data);
    thread->ThreadFunction();
    return 0;
}
#else
void* ThreadFunctionStatic(void* data)
{
    Thread* thread = static_cast<Thread*>(data);
    thread->ThreadFunction();
    pthread_exit((void*)0);
    return 0;
}
#endif

Thread::Thread() :
    handle_(0),
    shouldRun_(false)
{
}

Thread::~Thread()
{
    Stop();
}

bool Thread::Start()
{
    // Check if already running
    if (handle_)
        return false;

    shouldRun_ = true;
    #ifdef WIN32
    handle_ = CreateThread(0, 0, ThreadFunctionStatic, this, 0, 0);
    #else
    handle_ = new pthread_t;
    pthread_attr_t type;
    pthread_attr_init(&type);
    pthread_attr_setdetachstate(&type, PTHREAD_CREATE_JOINABLE);
    pthread_create((pthread_t*)handle_, &type, ThreadFunctionStatic, this);
    #endif
    return handle_ != 0;
}

void Thread::Stop()
{
    // Check if already stopped
    if (!handle_)
        return;

    shouldRun_ = false;
    #ifdef WIN32
    WaitForSingleObject((HANDLE)handle_, INFINITE);
    CloseHandle((HANDLE)handle_);
    #else
    pthread_t* thread = (pthread_t*)handle_;
    if (thread)
        pthread_join(*thread, 0);
    delete thread;
    #endif
    handle_ = 0;
}

void Thread::SetPriority(int priority)
{
    #ifdef WIN32
    if (handle_)
        SetThreadPriority((HANDLE)handle_, priority);
    #else
    pthread_t* thread = (pthread_t*)handle_;
    if (thread)
        pthread_setschedprio(*thread, priority);
    #endif
}
<commit_msg>Fixed OSX build.<commit_after>//
// Urho3D Engine
// Copyright (c) 2008-2011 Lasse rni
//
// 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 "Precompiled.h"
#include "Thread.h"

#ifdef WIN32
#include <windows.h>
#else
#include <pthread.h>
#endif

#include "DebugNew.h"

#ifdef WIN32
DWORD WINAPI ThreadFunctionStatic(void* data)
{
    Thread* thread = static_cast<Thread*>(data);
    thread->ThreadFunction();
    return 0;
}
#else
void* ThreadFunctionStatic(void* data)
{
    Thread* thread = static_cast<Thread*>(data);
    thread->ThreadFunction();
    pthread_exit((void*)0);
    return 0;
}
#endif

Thread::Thread() :
    handle_(0),
    shouldRun_(false)
{
}

Thread::~Thread()
{
    Stop();
}

bool Thread::Start()
{
    // Check if already running
    if (handle_)
        return false;

    shouldRun_ = true;
    #ifdef WIN32
    handle_ = CreateThread(0, 0, ThreadFunctionStatic, this, 0, 0);
    #else
    handle_ = new pthread_t;
    pthread_attr_t type;
    pthread_attr_init(&type);
    pthread_attr_setdetachstate(&type, PTHREAD_CREATE_JOINABLE);
    pthread_create((pthread_t*)handle_, &type, ThreadFunctionStatic, this);
    #endif
    return handle_ != 0;
}

void Thread::Stop()
{
    // Check if already stopped
    if (!handle_)
        return;

    shouldRun_ = false;
    #ifdef WIN32
    WaitForSingleObject((HANDLE)handle_, INFINITE);
    CloseHandle((HANDLE)handle_);
    #else
    pthread_t* thread = (pthread_t*)handle_;
    if (thread)
        pthread_join(*thread, 0);
    delete thread;
    #endif
    handle_ = 0;
}

void Thread::SetPriority(int priority)
{
    #ifdef WIN32
    if (handle_)
        SetThreadPriority((HANDLE)handle_, priority);
    #endif
    #ifdef __linux__
    pthread_t* thread = (pthread_t*)handle_;
    if (thread)
        pthread_setschedprio(*thread, priority);
    #endif
}
<|endoftext|>


<commit_before>#include "GameObject.h"
#include "BaseComponent.h"
#include "Globals.h"
#include <GL/glew.h>
#include "TransformComponent.h"
#include <MathGeoLib/include/Math/float4x4.h>

GameObject::GameObject()
{
	BoundingBox.SetNegativeInfinity();
}

GameObject::~GameObject()
{
}

void GameObject::SetParent(GameObject* new_parent)
{
	if(_parent != nullptr)
	{
		_parent->RemoveChild(this);
		new_parent->_childs.push_back(this);
		_parent = new_parent;
	}
}

GameObject* GameObject::GetParent() const
{
	return _parent;
}

const std::vector<GameObject*>& GameObject::GetChilds() const
{
	return _childs;
}

void GameObject::AddChild(GameObject* child)
{
	if (child != nullptr)
	{
		if(child->_parent != nullptr)
			child->_parent->RemoveChild(this);
		child->_parent = this;
		_childs.push_back(child);
	}
}

void GameObject::RemoveChild(const GameObject* child)
{
	if(!_childs.empty())
	{
		for (auto it = _childs.begin(); it != _childs.cend(); ++it)
		{
			if (*it == child)
			{
				_childs.erase(it);
				break;
			}
		}
	}
}

const std::list<BaseComponent*>& GameObject::GetComponents() const
{
	return _components;
}

void GameObject::AddComponent(BaseComponent* component)
{
	if (component != nullptr)
	{
		component->Parent = this;
		_components.push_back(component);

		if (component->Name == "Transform")
			_transform = static_cast<TransformComponent*>(component);
	}
}

BaseComponent* GameObject::GetComponentByName(const std::string& name) const
{
	for (BaseComponent* component : _components)
	{
		if (component->Name == name)
			return component;
	}

	return nullptr;
}

void GameObject::DeleteComponentByName(const std::string& name)
{
	if(!_components.empty())
	{
		for (auto it = _components.begin(); it != _components.cend(); ++it)
		{
			if ((*it)->Name == name)
			{
				_components.erase(it);
				(*it)->CleanUp();
				RELEASE(*it);
			}
		}
	}
}

void GameObject::DeleteComponent(BaseComponent* component)
{
	_components.remove(component);
}

TransformComponent* GameObject::GetTransform() const
{
	return _transform;
}

void GameObject::DrawBoundingBox()
{
	glPushMatrix();

	if (BoundingBox.IsFinite())
	{
		glColor3f(0.f, 255.f, 0.f);
		glLineWidth(3.f);
		glBegin(GL_LINES);
		vec points[8];
		BoundingBox.GetCornerPoints(points);

		// LEFT SIDE
		glVertex3fv(&points[0][0]);
		glVertex3fv(&points[1][0]);

		glVertex3fv(&points[0][0]);
		glVertex3fv(&points[2][0]);

		glVertex3fv(&points[2][0]);
		glVertex3fv(&points[3][0]);

		glVertex3fv(&points[3][0]);
		glVertex3fv(&points[1][0]);

		// BACK SIDE
		glVertex3fv(&points[0][0]);
		glVertex3fv(&points[4][0]);

		glVertex3fv(&points[2][0]);
		glVertex3fv(&points[6][0]);

		glVertex3fv(&points[4][0]);
		glVertex3fv(&points[6][0]);

		// RIGHT SIDE
		glVertex3fv(&points[6][0]);
		glVertex3fv(&points[7][0]);

		glVertex3fv(&points[4][0]);
		glVertex3fv(&points[5][0]);

		glVertex3fv(&points[7][0]);
		glVertex3fv(&points[5][0]);

		// FRONT SIDE
		glVertex3fv(&points[1][0]);
		glVertex3fv(&points[5][0]);

		glVertex3fv(&points[3][0]);
		glVertex3fv(&points[7][0]);

		glEnd();
	}

	glPopMatrix();
}

void GameObject::DrawHierachy()
{
	GLboolean light = glIsEnabled(GL_LIGHTING);
	glDisable(GL_LIGHTING);
	glColor4f(0.f, 0.f, 1.f, 1.f);

	float4x4 transform = float4x4::identity;
	for (GameObject* child : _childs)
		child->DrawHierachy(transform);

	glColor4f(1.f, 1.f, 1.f, 1.f);

	if (light)
		glEnable(GL_LIGHTING);
}

void GameObject::DrawHierachy(const float4x4& transformMatrix)
{
	float4x4 localMatrix = transformMatrix * _transform->GetTransformMatrix();

	if (_parent && _parent->_transform)
	{
		glBegin(GL_LINES);
		float3 parentPos = transformMatrix.Col3(3);
		glVertex3fv(reinterpret_cast<GLfloat*>(&parentPos));
		float3 position = localMatrix.Col3(3);
		glVertex3fv(reinterpret_cast<GLfloat*>(&position));
		glEnd();
	}

	for (GameObject* child : _childs)
		child->DrawHierachy(localMatrix);
}

void GameObject::Update()
{
	glPushMatrix();
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);

	for (BaseComponent* baseComponent : _components)
	{
		if(baseComponent->Enabled)
			baseComponent->Update();
	}

	glBindTexture(GL_TEXTURE_2D, 0);

	glDisableClientState(GL_TEXTURE_COORD_ARRAY);

	for (GameObject* child : _childs)
	{
		child->Update();
	}

	glEnd();

	glPopMatrix();
}

bool GameObject::CleanUp()
{
	for (BaseComponent* component : _components)
	{
		component->CleanUp();
		RELEASE(component);
	}
	return true;
}

<commit_msg>Fix bounding box color<commit_after>#include "GameObject.h"
#include "BaseComponent.h"
#include "Globals.h"
#include <GL/glew.h>
#include "TransformComponent.h"
#include <MathGeoLib/include/Math/float4x4.h>

GameObject::GameObject()
{
	BoundingBox.SetNegativeInfinity();
}

GameObject::~GameObject()
{
}

void GameObject::SetParent(GameObject* new_parent)
{
	if(_parent != nullptr)
	{
		_parent->RemoveChild(this);
		new_parent->_childs.push_back(this);
		_parent = new_parent;
	}
}

GameObject* GameObject::GetParent() const
{
	return _parent;
}

const std::vector<GameObject*>& GameObject::GetChilds() const
{
	return _childs;
}

void GameObject::AddChild(GameObject* child)
{
	if (child != nullptr)
	{
		if(child->_parent != nullptr)
			child->_parent->RemoveChild(this);
		child->_parent = this;
		_childs.push_back(child);
	}
}

void GameObject::RemoveChild(const GameObject* child)
{
	if(!_childs.empty())
	{
		for (auto it = _childs.begin(); it != _childs.cend(); ++it)
		{
			if (*it == child)
			{
				_childs.erase(it);
				break;
			}
		}
	}
}

const std::list<BaseComponent*>& GameObject::GetComponents() const
{
	return _components;
}

void GameObject::AddComponent(BaseComponent* component)
{
	if (component != nullptr)
	{
		component->Parent = this;
		_components.push_back(component);

		if (component->Name == "Transform")
			_transform = static_cast<TransformComponent*>(component);
	}
}

BaseComponent* GameObject::GetComponentByName(const std::string& name) const
{
	for (BaseComponent* component : _components)
	{
		if (component->Name == name)
			return component;
	}

	return nullptr;
}

void GameObject::DeleteComponentByName(const std::string& name)
{
	if(!_components.empty())
	{
		for (auto it = _components.begin(); it != _components.cend(); ++it)
		{
			if ((*it)->Name == name)
			{
				_components.erase(it);
				(*it)->CleanUp();
				RELEASE(*it);
			}
		}
	}
}

void GameObject::DeleteComponent(BaseComponent* component)
{
	_components.remove(component);
}

TransformComponent* GameObject::GetTransform() const
{
	return _transform;
}

void GameObject::DrawBoundingBox()
{
	glPushMatrix();

	GLboolean light = glIsEnabled(GL_LIGHTING);
	glDisable(GL_LIGHTING);

	if (BoundingBox.IsFinite())
	{
		glLineWidth(3.f);
		glBegin(GL_LINES);
		glColor3f(0.f, 1.f, 0.f);
		vec points[8];
		BoundingBox.GetCornerPoints(points);

		// LEFT SIDE
		glVertex3fv(&points[0][0]);
		glVertex3fv(&points[1][0]);

		glVertex3fv(&points[0][0]);
		glVertex3fv(&points[2][0]);

		glVertex3fv(&points[2][0]);
		glVertex3fv(&points[3][0]);

		glVertex3fv(&points[3][0]);
		glVertex3fv(&points[1][0]);

		// BACK SIDE
		glVertex3fv(&points[0][0]);
		glVertex3fv(&points[4][0]);

		glVertex3fv(&points[2][0]);
		glVertex3fv(&points[6][0]);

		glVertex3fv(&points[4][0]);
		glVertex3fv(&points[6][0]);

		// RIGHT SIDE
		glVertex3fv(&points[6][0]);
		glVertex3fv(&points[7][0]);

		glVertex3fv(&points[4][0]);
		glVertex3fv(&points[5][0]);

		glVertex3fv(&points[7][0]);
		glVertex3fv(&points[5][0]);

		// FRONT SIDE
		glVertex3fv(&points[1][0]);
		glVertex3fv(&points[5][0]);

		glVertex3fv(&points[3][0]);
		glVertex3fv(&points[7][0]);

		glEnd();
	}

	if (light)
		glEnable(GL_LIGHTING);

	glPopMatrix();
}

void GameObject::DrawHierachy()
{
	GLboolean light = glIsEnabled(GL_LIGHTING);
	glDisable(GL_LIGHTING);
	glColor4f(0.f, 0.f, 1.f, 1.f);

	float4x4 transform = float4x4::identity;
	for (GameObject* child : _childs)
		child->DrawHierachy(transform);

	glColor4f(1.f, 1.f, 1.f, 1.f);

	if (light)
		glEnable(GL_LIGHTING);
}

void GameObject::DrawHierachy(const float4x4& transformMatrix)
{
	float4x4 localMatrix = transformMatrix * _transform->GetTransformMatrix();

	if (_parent && _parent->_transform)
	{
		glBegin(GL_LINES);
		float3 parentPos = transformMatrix.Col3(3);
		glVertex3fv(reinterpret_cast<GLfloat*>(&parentPos));
		float3 position = localMatrix.Col3(3);
		glVertex3fv(reinterpret_cast<GLfloat*>(&position));
		glEnd();
	}

	for (GameObject* child : _childs)
		child->DrawHierachy(localMatrix);
}

void GameObject::Update()
{
	glPushMatrix();
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);

	for (BaseComponent* baseComponent : _components)
	{
		if(baseComponent->Enabled)
			baseComponent->Update();
	}

	glBindTexture(GL_TEXTURE_2D, 0);

	glDisableClientState(GL_TEXTURE_COORD_ARRAY);

	for (GameObject* child : _childs)
	{
		child->Update();
	}

	glEnd();

	glPopMatrix();
}

bool GameObject::CleanUp()
{
	for (BaseComponent* component : _components)
	{
		component->CleanUp();
		RELEASE(component);
	}
	return true;
}

<|endoftext|>


<commit_before>/* This file is part of the Pangolin Project.
 * http://github.com/stevenlovegrove/Pangolin
 *
 * Copyright (c) 2013 Steven Lovegrove
 *
 * 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 <pangolin/video/drivers/openni.h>
#include <pangolin/factory/factory_registry.h>
#include <pangolin/video/iostream_operators.h>

namespace pangolin
{

OpenNiVideo::OpenNiVideo(OpenNiSensorType s1, OpenNiSensorType s2, ImageDim dim, int fps)
{
    sensor_type[0] = s1;
    sensor_type[1] = s2;

    XnStatus nRetVal = XN_STATUS_OK;
    nRetVal = context.Init();
    if (nRetVal != XN_STATUS_OK) {
        std::cerr << "context.Init: " << xnGetStatusString(nRetVal) << std::endl;
    }

    XnMapOutputMode mapMode;
    mapMode.nXRes = dim.x;
    mapMode.nYRes = dim.y;
    mapMode.nFPS = fps;

    sizeBytes = 0;

    bool use_depth = false;
    bool use_ir = false;
    bool use_rgb = false;
    bool depth_to_color = false;

    for(int i=0; i<2; ++i) {
        PixelFormat fmt;

        // Establish output pixel format for sensor streams
        switch( sensor_type[i] ) {
        case OpenNiDepth_1mm_Registered:
        case OpenNiDepth_1mm:
        case OpenNiIr:
        case OpenNiIrProj:
            fmt = PixelFormatFromString("GRAY16LE");
            break;
        case OpenNiIr8bit:
        case OpenNiIr8bitProj:
            fmt = PixelFormatFromString("GRAY8");
            break;
        case OpenNiRgb:
            fmt = PixelFormatFromString("RGB24");
            break;
        default:
            continue;
        }

        switch( sensor_type[i] ) {
        case OpenNiDepth_1mm_Registered:
            depth_to_color = true;
            break;
        case OpenNiDepth_1mm:
            use_depth = true;
            break;
        case OpenNiIr:
        case OpenNiIr8bit:
            use_ir = true;
            break;
        case OpenNiIrProj:
        case OpenNiIr8bitProj:
            use_ir = true;
            use_depth = true;
            break;
        case OpenNiRgb:
            use_rgb = true;
            break;
        default:
            break;
        }

        const StreamInfo stream(fmt, mapMode.nXRes, mapMode.nYRes, (mapMode.nXRes * fmt.bpp) / 8, (unsigned char*)0 + sizeBytes);
        sizeBytes += stream.SizeBytes();
        streams.push_back(stream);
    }

    if( use_depth ) {
        nRetVal = depthNode.Create(context);
        if (nRetVal != XN_STATUS_OK) {
            throw VideoException( (std::string)"Unable to create DepthNode: " + xnGetStatusString(nRetVal) );
        }else{
            nRetVal = depthNode.SetMapOutputMode(mapMode);
            if (nRetVal != XN_STATUS_OK) {
                throw VideoException( (std::string)"Invalid DepthNode mode: " + xnGetStatusString(nRetVal) );
            }
        }
    }

    if( use_rgb ) {
        nRetVal = imageNode.Create(context);
        if (nRetVal != XN_STATUS_OK) {
            throw VideoException( (std::string)"Unable to create ImageNode: " + xnGetStatusString(nRetVal) );
        }else{
            nRetVal = imageNode.SetMapOutputMode(mapMode);
            if (nRetVal != XN_STATUS_OK) {
                throw VideoException( (std::string)"Invalid ImageNode mode: " + xnGetStatusString(nRetVal) );
            }
        }
    }

    if (depth_to_color && use_rgb) {
        //Registration
        if( depthNode.IsCapabilitySupported(XN_CAPABILITY_ALTERNATIVE_VIEW_POINT) ) {
            nRetVal = depthNode.GetAlternativeViewPointCap().SetViewPoint( imageNode  );
            if (nRetVal != XN_STATUS_OK) {
                std::cerr << "depthNode.GetAlternativeViewPointCap().SetViewPoint(imageNode): " << xnGetStatusString(nRetVal) << std::endl;
            }
        }

        // Frame Sync
        if (depthNode.IsCapabilitySupported(XN_CAPABILITY_FRAME_SYNC))
        {
            if (depthNode.GetFrameSyncCap().CanFrameSyncWith(imageNode))
            {
                nRetVal = depthNode.GetFrameSyncCap().FrameSyncWith(imageNode);
                if (nRetVal != XN_STATUS_OK) {
                    std::cerr << "depthNode.GetFrameSyncCap().FrameSyncWith(imageNode): " << xnGetStatusString(nRetVal) << std::endl;
                }
            }
        }
    }

    if( use_ir ) {
        nRetVal = irNode.Create(context);
        if (nRetVal != XN_STATUS_OK) {
            throw VideoException( (std::string)"Unable to create IrNode: " + xnGetStatusString(nRetVal) );
        }else{
            nRetVal = irNode.SetMapOutputMode(mapMode);
            if (nRetVal != XN_STATUS_OK) {
                throw VideoException( (std::string)"Invalid IrNode mode: " + xnGetStatusString(nRetVal) );
            }
        }
    }

    Start();
}

OpenNiVideo::~OpenNiVideo()
{
    context.Release();
}

size_t OpenNiVideo::SizeBytes() const
{
    return sizeBytes;
}

const std::vector<StreamInfo>& OpenNiVideo::Streams() const
{
    return streams;
}

void OpenNiVideo::Start()
{
    //    XnStatus nRetVal =
    context.StartGeneratingAll();
}

void OpenNiVideo::Stop()
{
    context.StopGeneratingAll();
}

bool OpenNiVideo::GrabNext( unsigned char* image, bool /*wait*/ )
{
    //    XnStatus nRetVal = context.WaitAndUpdateAll();
    XnStatus nRetVal = context.WaitAnyUpdateAll();
    //    nRetVal = context.WaitOneUpdateAll(imageNode);

    if (nRetVal != XN_STATUS_OK) {
        std::cerr << "Failed updating data: " << xnGetStatusString(nRetVal) << std::endl;
        return false;
    }else{
        unsigned char* out_img = image;

        for(int i=0; i<2; ++i) {
            switch (sensor_type[i]) {
            case OpenNiDepth_1mm:
            case OpenNiDepth_1mm_Registered:
            {
                const XnDepthPixel* pDepthMap = depthNode.GetDepthMap();
                memcpy(out_img,pDepthMap, streams[i].SizeBytes() );
                break;
            }
            case OpenNiIr:
            case OpenNiIrProj:
            {
                const XnIRPixel* pIrMap = irNode.GetIRMap();
                memcpy(out_img, pIrMap, streams[i].SizeBytes() );
                break;
            }
            case OpenNiIr8bit:
            case OpenNiIr8bitProj:
            {
                const XnIRPixel* pIr16Map = irNode.GetIRMap();

                // rescale from 16-bit (10 effective) to 8-bit
                xn::IRMetaData meta_data;
                irNode.GetMetaData(meta_data);
                int w = meta_data.XRes();
                int h = meta_data.YRes();

                // Copy to out_img with conversion
                XnUInt8* pIrMapScaled = (XnUInt8*)out_img;
                for (int v = 0; v < h; ++v)
                for (int u = 0; u < w; ++u) {
                    int val = *pIr16Map >> 2; // 10bit to 8 bit
                    pIrMapScaled[w * v + u] = val;
                    pIr16Map++;
                }

                break;
            }
            case OpenNiRgb:
            {
                const XnUInt8* pImageMap = imageNode.GetImageMap();
                memcpy(out_img,pImageMap, streams[i].SizeBytes());
                break;
            }
            default:
                continue;
                break;
            }

            out_img += streams[i].SizeBytes();
        }

        return true;
    }
}

bool OpenNiVideo::GrabNewest( unsigned char* image, bool wait )
{
    return GrabNext(image,wait);
}

PANGOLIN_REGISTER_FACTORY(OpenNiVideo)
{
    struct OpenNiVideoFactory final : public FactoryInterface<VideoInterface> {
        std::unique_ptr<VideoInterface> Open(const Uri& uri) override {
            const ImageDim dim = uri.Get<ImageDim>("size", ImageDim(640,480));
            const unsigned int fps = uri.Get<unsigned int>("fps", 30);
            const bool autoexposure = uri.Get<bool>("autoexposure", true);

            OpenNiSensorType img1 = OpenNiRgb;
            OpenNiSensorType img2 = OpenNiUnassigned;

            if( uri.Contains("img1") ){
                img1 = openni_sensor(uri.Get<std::string>("img1", "depth"));
            }

            if( uri.Contains("img2") ){
                img2 = openni_sensor(uri.Get<std::string>("img2","rgb"));
            }

            OpenNiVideo* oniv = new OpenNiVideo(img1, img2, dim, fps);
            oniv->SetAutoExposure(autoexposure);
            return std::unique_ptr<VideoInterface>(oniv);
        }
    };

    auto factory = std::make_shared<OpenNiVideoFactory>();
    FactoryRegistry<VideoInterface>::I().RegisterFactory(factory,  10, "openni1");
    FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 100, "openni");
    FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 100, "oni");
    FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 100, "kinect");
}

}
<commit_msg>Revert "fix switch statement"<commit_after>/* This file is part of the Pangolin Project.
 * http://github.com/stevenlovegrove/Pangolin
 *
 * Copyright (c) 2013 Steven Lovegrove
 *
 * 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 <pangolin/video/drivers/openni.h>
#include <pangolin/factory/factory_registry.h>
#include <pangolin/video/iostream_operators.h>

namespace pangolin
{

OpenNiVideo::OpenNiVideo(OpenNiSensorType s1, OpenNiSensorType s2, ImageDim dim, int fps)
{
    sensor_type[0] = s1;
    sensor_type[1] = s2;

    XnStatus nRetVal = XN_STATUS_OK;
    nRetVal = context.Init();
    if (nRetVal != XN_STATUS_OK) {
        std::cerr << "context.Init: " << xnGetStatusString(nRetVal) << std::endl;
    }

    XnMapOutputMode mapMode;
    mapMode.nXRes = dim.x;
    mapMode.nYRes = dim.y;
    mapMode.nFPS = fps;

    sizeBytes = 0;

    bool use_depth = false;
    bool use_ir = false;
    bool use_rgb = false;
    bool depth_to_color = false;

    for(int i=0; i<2; ++i) {
        PixelFormat fmt;

        // Establish output pixel format for sensor streams
        switch( sensor_type[i] ) {
        case OpenNiDepth_1mm_Registered:
        case OpenNiDepth_1mm:
        case OpenNiIr:
        case OpenNiIrProj:
            fmt = PixelFormatFromString("GRAY16LE");
            break;
        case OpenNiIr8bit:
        case OpenNiIr8bitProj:
            fmt = PixelFormatFromString("GRAY8");
            break;
        case OpenNiRgb:
            fmt = PixelFormatFromString("RGB24");
            break;
        default:
            continue;
        }

        switch( sensor_type[i] ) {
        case OpenNiDepth_1mm_Registered:
            depth_to_color = true;
        case OpenNiDepth_1mm:
            use_depth = true;
            break;
        case OpenNiIr:
        case OpenNiIr8bit:
            use_ir = true;
            break;
        case OpenNiIrProj:
        case OpenNiIr8bitProj:
            use_ir = true;
            use_depth = true;
            break;
        case OpenNiRgb:
            use_rgb = true;
            break;
        default:
            break;
        }

        const StreamInfo stream(fmt, mapMode.nXRes, mapMode.nYRes, (mapMode.nXRes * fmt.bpp) / 8, (unsigned char*)0 + sizeBytes);
        sizeBytes += stream.SizeBytes();
        streams.push_back(stream);
    }

    if( use_depth ) {
        nRetVal = depthNode.Create(context);
        if (nRetVal != XN_STATUS_OK) {
            throw VideoException( (std::string)"Unable to create DepthNode: " + xnGetStatusString(nRetVal) );
        }else{
            nRetVal = depthNode.SetMapOutputMode(mapMode);
            if (nRetVal != XN_STATUS_OK) {
                throw VideoException( (std::string)"Invalid DepthNode mode: " + xnGetStatusString(nRetVal) );
            }
        }
    }

    if( use_rgb ) {
        nRetVal = imageNode.Create(context);
        if (nRetVal != XN_STATUS_OK) {
            throw VideoException( (std::string)"Unable to create ImageNode: " + xnGetStatusString(nRetVal) );
        }else{
            nRetVal = imageNode.SetMapOutputMode(mapMode);
            if (nRetVal != XN_STATUS_OK) {
                throw VideoException( (std::string)"Invalid ImageNode mode: " + xnGetStatusString(nRetVal) );
            }
        }
    }

    if (depth_to_color && use_rgb) {
        //Registration
        if( depthNode.IsCapabilitySupported(XN_CAPABILITY_ALTERNATIVE_VIEW_POINT) ) {
            nRetVal = depthNode.GetAlternativeViewPointCap().SetViewPoint( imageNode  );
            if (nRetVal != XN_STATUS_OK) {
                std::cerr << "depthNode.GetAlternativeViewPointCap().SetViewPoint(imageNode): " << xnGetStatusString(nRetVal) << std::endl;
            }
        }

        // Frame Sync
        if (depthNode.IsCapabilitySupported(XN_CAPABILITY_FRAME_SYNC))
        {
            if (depthNode.GetFrameSyncCap().CanFrameSyncWith(imageNode))
            {
                nRetVal = depthNode.GetFrameSyncCap().FrameSyncWith(imageNode);
                if (nRetVal != XN_STATUS_OK) {
                    std::cerr << "depthNode.GetFrameSyncCap().FrameSyncWith(imageNode): " << xnGetStatusString(nRetVal) << std::endl;
                }
            }
        }
    }

    if( use_ir ) {
        nRetVal = irNode.Create(context);
        if (nRetVal != XN_STATUS_OK) {
            throw VideoException( (std::string)"Unable to create IrNode: " + xnGetStatusString(nRetVal) );
        }else{
            nRetVal = irNode.SetMapOutputMode(mapMode);
            if (nRetVal != XN_STATUS_OK) {
                throw VideoException( (std::string)"Invalid IrNode mode: " + xnGetStatusString(nRetVal) );
            }
        }
    }

    Start();
}

OpenNiVideo::~OpenNiVideo()
{
    context.Release();
}

size_t OpenNiVideo::SizeBytes() const
{
    return sizeBytes;
}

const std::vector<StreamInfo>& OpenNiVideo::Streams() const
{
    return streams;
}

void OpenNiVideo::Start()
{
    //    XnStatus nRetVal =
    context.StartGeneratingAll();
}

void OpenNiVideo::Stop()
{
    context.StopGeneratingAll();
}

bool OpenNiVideo::GrabNext( unsigned char* image, bool /*wait*/ )
{
    //    XnStatus nRetVal = context.WaitAndUpdateAll();
    XnStatus nRetVal = context.WaitAnyUpdateAll();
    //    nRetVal = context.WaitOneUpdateAll(imageNode);

    if (nRetVal != XN_STATUS_OK) {
        std::cerr << "Failed updating data: " << xnGetStatusString(nRetVal) << std::endl;
        return false;
    }else{
        unsigned char* out_img = image;

        for(int i=0; i<2; ++i) {
            switch (sensor_type[i]) {
            case OpenNiDepth_1mm:
            case OpenNiDepth_1mm_Registered:
            {
                const XnDepthPixel* pDepthMap = depthNode.GetDepthMap();
                memcpy(out_img,pDepthMap, streams[i].SizeBytes() );
                break;
            }
            case OpenNiIr:
            case OpenNiIrProj:
            {
                const XnIRPixel* pIrMap = irNode.GetIRMap();
                memcpy(out_img, pIrMap, streams[i].SizeBytes() );
                break;
            }
            case OpenNiIr8bit:
            case OpenNiIr8bitProj:
            {
                const XnIRPixel* pIr16Map = irNode.GetIRMap();

                // rescale from 16-bit (10 effective) to 8-bit
                xn::IRMetaData meta_data;
                irNode.GetMetaData(meta_data);
                int w = meta_data.XRes();
                int h = meta_data.YRes();

                // Copy to out_img with conversion
                XnUInt8* pIrMapScaled = (XnUInt8*)out_img;
                for (int v = 0; v < h; ++v)
                for (int u = 0; u < w; ++u) {
                    int val = *pIr16Map >> 2; // 10bit to 8 bit
                    pIrMapScaled[w * v + u] = val;
                    pIr16Map++;
                }

                break;
            }
            case OpenNiRgb:
            {
                const XnUInt8* pImageMap = imageNode.GetImageMap();
                memcpy(out_img,pImageMap, streams[i].SizeBytes());
                break;
            }
            default:
                continue;
                break;
            }

            out_img += streams[i].SizeBytes();
        }

        return true;
    }
}

bool OpenNiVideo::GrabNewest( unsigned char* image, bool wait )
{
    return GrabNext(image,wait);
}

PANGOLIN_REGISTER_FACTORY(OpenNiVideo)
{
    struct OpenNiVideoFactory final : public FactoryInterface<VideoInterface> {
        std::unique_ptr<VideoInterface> Open(const Uri& uri) override {
            const ImageDim dim = uri.Get<ImageDim>("size", ImageDim(640,480));
            const unsigned int fps = uri.Get<unsigned int>("fps", 30);
            const bool autoexposure = uri.Get<bool>("autoexposure", true);

            OpenNiSensorType img1 = OpenNiRgb;
            OpenNiSensorType img2 = OpenNiUnassigned;

            if( uri.Contains("img1") ){
                img1 = openni_sensor(uri.Get<std::string>("img1", "depth"));
            }

            if( uri.Contains("img2") ){
                img2 = openni_sensor(uri.Get<std::string>("img2","rgb"));
            }

            OpenNiVideo* oniv = new OpenNiVideo(img1, img2, dim, fps);
            oniv->SetAutoExposure(autoexposure);
            return std::unique_ptr<VideoInterface>(oniv);
        }
    };

    auto factory = std::make_shared<OpenNiVideoFactory>();
    FactoryRegistry<VideoInterface>::I().RegisterFactory(factory,  10, "openni1");
    FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 100, "openni");
    FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 100, "oni");
    FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 100, "kinect");
}

}
<|endoftext|>


<commit_before>/*
 * PlaceStructureSessionImplementation.cpp
 *
 *  Created on: Jun 13, 2011
 *      Author: crush
 */

#include "server/zone/objects/player/sessions/PlaceStructureSession.h"
#include "server/chat/ChatManager.h"
#include "server/zone/managers/planet/PlanetManager.h"
#include "server/zone/managers/structure/StructureManager.h"
#include "server/zone/managers/structure/tasks/StructureConstructionCompleteTask.h"
#include "server/zone/objects/area/ActiveArea.h"
#include "server/zone/objects/building/BuildingObject.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/installation/InstallationObject.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/objects/scene/SessionFacadeType.h"
#include "server/zone/objects/structure/StructureObject.h"
#include "server/zone/objects/tangible/deed/structure/StructureDeed.h"
#include "server/zone/packets/player/EnterStructurePlacementModeMessage.h"
#include "server/zone/templates/tangible/SharedStructureObjectTemplate.h"
#include "server/zone/objects/area/areashapes/CircularAreaShape.h"
#include "server/zone/Zone.h"

int PlaceStructureSessionImplementation::constructStructure(float x, float y, int angle) {
	positionX = x;
	positionY = y;
	directionAngle = angle;

	TemplateManager* templateManager = TemplateManager::instance();

	String serverTemplatePath = deedObject->getGeneratedObjectTemplate();
	Reference<SharedStructureObjectTemplate*> serverTemplate = dynamic_cast<SharedStructureObjectTemplate*>(templateManager->getTemplate(serverTemplatePath.hashCode()));

	if (serverTemplate == NULL || temporaryNoBuildZone != NULL)
		return cancelSession(); //Something happened, the server template is not a structure template or temporaryNoBuildZone already set.

	placeTemporaryNoBuildZone(serverTemplate);

	String barricadeServerTemplatePath = serverTemplate->getConstructionMarkerTemplate();
	int constructionDuration = 100; //Set the duration for 100ms as a fall back if it doesn't have a barricade template.

	if (!barricadeServerTemplatePath.isEmpty()) {
		constructionBarricade = ObjectManager::instance()->createObject(barricadeServerTemplatePath.hashCode(), 0, "");

		if (constructionBarricade != NULL) {
			constructionBarricade->initializePosition(x, 0, y); //The construction barricades are always at the terrain height.

			StructureFootprint* structureFootprint = serverTemplate->getStructureFootprint();

			if (structureFootprint != NULL && (structureFootprint->getRowSize() > structureFootprint->getColSize())) {
				angle = angle + 180;
			}

			constructionBarricade->rotate(angle); //All construction barricades need to be rotated 180 degrees for some reason.
			//constructionBarricade->insertToZone(zone);

			Locker tLocker(constructionBarricade);

			zone->transferObject(constructionBarricade, -1, true);

			constructionDuration = serverTemplate->getLotSize() * 3000; //3 seconds per lot.
		}
	}

	Reference<Task*> task = new StructureConstructionCompleteTask(creatureObject);
	task->schedule(constructionDuration);

	return 0;
}

void PlaceStructureSessionImplementation::placeTemporaryNoBuildZone(SharedStructureObjectTemplate* serverTemplate) {
	Reference<StructureFootprint*> structureFootprint =	serverTemplate->getStructureFootprint();

	//float temporaryNoBuildZoneWidth = structureFootprint->getLength() + structureFootprint->getWidth();

	ManagedReference<CircularAreaShape*> areaShape = new CircularAreaShape();

	Locker alocker(areaShape);

	// Guild halls are approximately 55 m long, 64 m radius will surely cover that in all directions.
	// Even if the placement coordinate aren't in the center of the building.
	areaShape->setRadius(64);
	areaShape->setAreaCenter(positionX, positionY);

	temporaryNoBuildZone = (zone->getZoneServer()->createObject(String("object/active_area.iff").hashCode(), 0)).castTo<ActiveArea*>();

	Locker locker(temporaryNoBuildZone);

	temporaryNoBuildZone->initializePosition(positionX, 0, positionY);
	temporaryNoBuildZone->setAreaShape(areaShape);
	temporaryNoBuildZone->setNoBuildArea(true);

	zone->transferObject(temporaryNoBuildZone, -1, true);
}

void PlaceStructureSessionImplementation::removeTemporaryNoBuildZone() {
	if (temporaryNoBuildZone != NULL) {
		Locker locker(temporaryNoBuildZone);

		temporaryNoBuildZone->destroyObjectFromWorld(true);
	}
}

int PlaceStructureSessionImplementation::completeSession() {
	if (constructionBarricade != NULL) {
		Locker locker(constructionBarricade);

		constructionBarricade->destroyObjectFromWorld(true);
	}

	String serverTemplatePath = deedObject->getGeneratedObjectTemplate();

	StructureManager* structureManager = StructureManager::instance();
	ManagedReference<StructureObject*> structureObject = structureManager->placeStructure(creatureObject, serverTemplatePath, positionX, positionY, directionAngle);

	removeTemporaryNoBuildZone();

	if (structureObject == NULL) {
		ManagedReference<SceneObject*> inventory = creatureObject->getSlottedObject("inventory");

		if (inventory != NULL)
			inventory->transferObject(deedObject, -1, true);

		return cancelSession();
	}

	Locker clocker(structureObject, creatureObject);

	structureObject->setDeedObjectID(deedObject->getObjectID());

	deedObject->notifyStructurePlaced(creatureObject, structureObject);

	ManagedReference<PlayerObject*> ghost = creatureObject->getPlayerObject();

	if (ghost != NULL) {

		//Create Waypoint
		ManagedReference<WaypointObject*> waypointObject = ( zone->getZoneServer()->createObject(String("object/waypoint/world_waypoint_blue.iff").hashCode(), 1)).castTo<WaypointObject*>();
		waypointObject->setCustomObjectName(structureObject->getDisplayedName(), false);
		waypointObject->setActive(true);
		waypointObject->setPosition(positionX, 0, positionY);
		waypointObject->setPlanetCRC(zone->getZoneCRC());

		ghost->addWaypoint(waypointObject, false, true);

		//Create an email.
		ManagedReference<ChatManager*> chatManager = zone->getZoneServer()->getChatManager();

		if (chatManager != NULL) {
			UnicodeString subject = "@player_structure:construction_complete_subject";

			StringIdChatParameter emailBody("@player_structure:construction_complete");
			emailBody.setTO(structureObject->getObjectName());
			emailBody.setDI(ghost->getLotsRemaining());

			chatManager->sendMail("@player_structure:construction_complete_sender", subject, emailBody, creatureObject->getFirstName(), waypointObject);
		}

		if (structureObject->isBuildingObject()) {
			BuildingObject* building = cast<BuildingObject*>(structureObject.get());
			if (building->getSignObject() != NULL) {
				building->setCustomObjectName(creatureObject->getFirstName() + "'s House", true); //Set the house sign.
			}
		}
	}

	return cancelSession(); //Canceling the session just removes the session from the player's map.
}
<commit_msg>[Fixed] stability issue<commit_after>/*
 * PlaceStructureSessionImplementation.cpp
 *
 *  Created on: Jun 13, 2011
 *      Author: crush
 */

#include "server/zone/objects/player/sessions/PlaceStructureSession.h"
#include "server/chat/ChatManager.h"
#include "server/zone/managers/planet/PlanetManager.h"
#include "server/zone/managers/structure/StructureManager.h"
#include "server/zone/managers/structure/tasks/StructureConstructionCompleteTask.h"
#include "server/zone/objects/area/ActiveArea.h"
#include "server/zone/objects/building/BuildingObject.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/installation/InstallationObject.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/objects/scene/SessionFacadeType.h"
#include "server/zone/objects/structure/StructureObject.h"
#include "server/zone/objects/tangible/deed/structure/StructureDeed.h"
#include "server/zone/packets/player/EnterStructurePlacementModeMessage.h"
#include "server/zone/templates/tangible/SharedStructureObjectTemplate.h"
#include "server/zone/objects/area/areashapes/CircularAreaShape.h"
#include "server/zone/Zone.h"

int PlaceStructureSessionImplementation::constructStructure(float x, float y, int angle) {
	positionX = x;
	positionY = y;
	directionAngle = angle;

	TemplateManager* templateManager = TemplateManager::instance();

	String serverTemplatePath = deedObject->getGeneratedObjectTemplate();
	Reference<SharedStructureObjectTemplate*> serverTemplate = dynamic_cast<SharedStructureObjectTemplate*>(templateManager->getTemplate(serverTemplatePath.hashCode()));

	if (serverTemplate == NULL || temporaryNoBuildZone != NULL)
		return cancelSession(); //Something happened, the server template is not a structure template or temporaryNoBuildZone already set.

	placeTemporaryNoBuildZone(serverTemplate);

	String barricadeServerTemplatePath = serverTemplate->getConstructionMarkerTemplate();
	int constructionDuration = 100; //Set the duration for 100ms as a fall back if it doesn't have a barricade template.

	if (!barricadeServerTemplatePath.isEmpty()) {
		constructionBarricade = ObjectManager::instance()->createObject(barricadeServerTemplatePath.hashCode(), 0, "");

		if (constructionBarricade != NULL) {
			constructionBarricade->initializePosition(x, 0, y); //The construction barricades are always at the terrain height.

			StructureFootprint* structureFootprint = serverTemplate->getStructureFootprint();

			if (structureFootprint != NULL && (structureFootprint->getRowSize() > structureFootprint->getColSize())) {
				angle = angle + 180;
			}

			constructionBarricade->rotate(angle); //All construction barricades need to be rotated 180 degrees for some reason.
			//constructionBarricade->insertToZone(zone);

			Locker tLocker(constructionBarricade);

			zone->transferObject(constructionBarricade, -1, true);

			constructionDuration = serverTemplate->getLotSize() * 3000; //3 seconds per lot.
		}
	}

	Reference<Task*> task = new StructureConstructionCompleteTask(creatureObject);
	task->schedule(constructionDuration);

	return 0;
}

void PlaceStructureSessionImplementation::placeTemporaryNoBuildZone(SharedStructureObjectTemplate* serverTemplate) {
	Reference<StructureFootprint*> structureFootprint =	serverTemplate->getStructureFootprint();

	//float temporaryNoBuildZoneWidth = structureFootprint->getLength() + structureFootprint->getWidth();

	ManagedReference<CircularAreaShape*> areaShape = new CircularAreaShape();

	Locker alocker(areaShape);

	// Guild halls are approximately 55 m long, 64 m radius will surely cover that in all directions.
	// Even if the placement coordinate aren't in the center of the building.
	areaShape->setRadius(64);
	areaShape->setAreaCenter(positionX, positionY);

	temporaryNoBuildZone = (zone->getZoneServer()->createObject(String("object/active_area.iff").hashCode(), 0)).castTo<ActiveArea*>();

	Locker locker(temporaryNoBuildZone);

	temporaryNoBuildZone->initializePosition(positionX, 0, positionY);
	temporaryNoBuildZone->setAreaShape(areaShape);
	temporaryNoBuildZone->setNoBuildArea(true);

	zone->transferObject(temporaryNoBuildZone, -1, true);
}

void PlaceStructureSessionImplementation::removeTemporaryNoBuildZone() {
	if (temporaryNoBuildZone != NULL) {
		Locker locker(temporaryNoBuildZone);

		temporaryNoBuildZone->destroyObjectFromWorld(true);
	}
}

int PlaceStructureSessionImplementation::completeSession() {
	if (constructionBarricade != NULL) {
		Locker locker(constructionBarricade);

		constructionBarricade->destroyObjectFromWorld(true);
	}

	String serverTemplatePath = deedObject->getGeneratedObjectTemplate();

	StructureManager* structureManager = StructureManager::instance();
	ManagedReference<StructureObject*> structureObject = structureManager->placeStructure(creatureObject, serverTemplatePath, positionX, positionY, directionAngle);

	removeTemporaryNoBuildZone();

	if (structureObject == NULL) {
		ManagedReference<SceneObject*> inventory = creatureObject->getSlottedObject("inventory");

		if (inventory != NULL)
			inventory->transferObject(deedObject, -1, true);

		return cancelSession();
	}

	Locker clocker(structureObject, creatureObject);

	structureObject->setDeedObjectID(deedObject->getObjectID());

	deedObject->notifyStructurePlaced(creatureObject, structureObject);

	ManagedReference<PlayerObject*> ghost = creatureObject->getPlayerObject();

	if (ghost != NULL) {

		//Create Waypoint
		ManagedReference<WaypointObject*> waypointObject = ( zone->getZoneServer()->createObject(String("object/waypoint/world_waypoint_blue.iff").hashCode(), 1)).castTo<WaypointObject*>();

		Locker locker(waypointObject);

		waypointObject->setCustomObjectName(structureObject->getDisplayedName(), false);
		waypointObject->setActive(true);
		waypointObject->setPosition(positionX, 0, positionY);
		waypointObject->setPlanetCRC(zone->getZoneCRC());

		ghost->addWaypoint(waypointObject, false, true);

		locker.release();

		//Create an email.
		ManagedReference<ChatManager*> chatManager = zone->getZoneServer()->getChatManager();

		if (chatManager != NULL) {
			UnicodeString subject = "@player_structure:construction_complete_subject";

			StringIdChatParameter emailBody("@player_structure:construction_complete");
			emailBody.setTO(structureObject->getObjectName());
			emailBody.setDI(ghost->getLotsRemaining());

			chatManager->sendMail("@player_structure:construction_complete_sender", subject, emailBody, creatureObject->getFirstName(), waypointObject);
		}

		if (structureObject->isBuildingObject()) {
			BuildingObject* building = cast<BuildingObject*>(structureObject.get());
			if (building->getSignObject() != NULL) {
				building->setCustomObjectName(creatureObject->getFirstName() + "'s House", true); //Set the house sign.
			}
		}
	}

	return cancelSession(); //Canceling the session just removes the session from the player's map.
}
<|endoftext|>