<commit_before>#include <sys/socket.h>

#include "utils.h"
#include "client_base.h"

const int WRITE_QUEUE_SIZE = -1;

int BaseClient::total_clients = 0;

BaseClient::BaseClient(ev::loop_ref &loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)
	: io(loop),
	  async(loop),
	  destroyed(false),
	  closed(false),
	  sock(sock_),
	  database_pool(database_pool_),
	  write_queue(WRITE_QUEUE_SIZE)
{
	sig.set<BaseClient, &BaseClient::signal_cb>(this);
	sig.start(SIGINT);

	async.set<BaseClient, &BaseClient::async_cb>(this);
	async.start();

	io.set<BaseClient, &BaseClient::io_cb>(this);
	io.start(sock, ev::READ);
}

BaseClient::~BaseClient()
{
	destroy();
	sig.stop();
	LOG_OBJ(this, "DELETED!\n");
}

void BaseClient::signal_cb(ev::sig &signal, int revents)
{
	LOG_EV(this, "Signaled destroy!!\n");
	destroy();
	delete this;
}

void BaseClient::destroy()
{
	if (destroyed) {
		return;
	}

	destroyed = true;

	close();

	// Stop and free watcher if client socket is closing
	io.stop();
	async.stop();

	::close(sock);
	LOG_OBJ(this, "DESTROYED!\n");
}

void BaseClient::close() {
	if (closed) {
		return;
	}

	closed = true;
	LOG_OBJ(this, "CLOSED!\n");
}

void BaseClient::async_cb(ev::async &watcher, int revents)
{
	if (destroyed) {
		return;
	}

	LOG_EV(this, "ASYNC_CB (sock=%d) %x\n", sock, revents);

	if (write_queue.empty()) {
		if (closed) {
			destroy();
		}
	} else {
		io.set(ev::READ|ev::WRITE);
	}

	if (destroyed) {
		delete this;
	}
}

void BaseClient::io_cb(ev::io &watcher, int revents)
{
	if (destroyed) {
		return;
	}

	LOG_EV(this, "IO_CB (sock=%d) %x\n", sock, revents);

	if (revents & EV_ERROR) {
		LOG_ERR(this, "ERROR: got invalid event (sock=%d): %s\n", sock, strerror(errno));
		destroy();
		return;
	}

	if (revents & EV_READ)
		read_cb(watcher);

	if (revents & EV_WRITE)
		write_cb(watcher);

	if (write_queue.empty()) {
		if (closed) {
			destroy();
		} else {
			io.set(ev::READ);
		}
	} else {
		io.set(ev::READ|ev::WRITE);
	}

	if (destroyed) {
		delete this;
	}
}

void BaseClient::write_cb(ev::io &watcher)
{
	if (!write_queue.empty()) {
		Buffer* buffer = write_queue.front();

		size_t buf_size = buffer->nbytes();
		const char * buf = buffer->dpos();

		LOG_CONN(this, "(sock=%d) <<-- '%s'\n", sock, repr(buf, buf_size).c_str());

		ssize_t written = ::write(watcher.fd, buf, buf_size);

		if (written < 0) {
			if (errno != EAGAIN) {
				LOG_ERR(this, "ERROR: write error (sock=%d): %s\n", sock, strerror(errno));
				destroy();
			}
		} else if (written == 0) {
			// nothing written?
		} else {
			buffer->pos += written;
			if (buffer->nbytes() == 0) {
				write_queue.pop(buffer);
				delete buffer;
			}
		}
	}
}

void BaseClient::read_cb(ev::io &watcher)
{
	char buf[1024];

	ssize_t received = ::read(watcher.fd, buf, sizeof(buf));

	if (received < 0) {
		if (errno != EAGAIN) {
			LOG_ERR(this, "ERROR: read error (sock=%d): %s\n", sock, strerror(errno));
			destroy();
		}
	} else if (received == 0) {
		// The peer has closed its half side of the connection.
		LOG_CONN(this, "Received EOF (sock=%d)!\n", sock);
		destroy();
	} else {
		LOG_CONN(this, "(sock=%d) -->> '%s'\n", sock, repr(buf, received).c_str());
		on_read(buf, received);
	}
}

void BaseClient::write(const char *buf, size_t buf_size)
{
	Buffer *buffer = new Buffer('\0', buf, buf_size);
	write_queue.push(buffer);

	async.send();
}
<commit_msg>Assert watcher.fd == sock<commit_after>#include <assert.h>
#include <sys/socket.h>

#include "utils.h"
#include "client_base.h"

const int WRITE_QUEUE_SIZE = -1;

int BaseClient::total_clients = 0;

BaseClient::BaseClient(ev::loop_ref &loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)
	: io(loop),
	  async(loop),
	  destroyed(false),
	  closed(false),
	  sock(sock_),
	  database_pool(database_pool_),
	  write_queue(WRITE_QUEUE_SIZE)
{
	sig.set<BaseClient, &BaseClient::signal_cb>(this);
	sig.start(SIGINT);

	async.set<BaseClient, &BaseClient::async_cb>(this);
	async.start();

	io.set<BaseClient, &BaseClient::io_cb>(this);
	io.start(sock, ev::READ);
}

BaseClient::~BaseClient()
{
	destroy();
	sig.stop();
	LOG_OBJ(this, "DELETED!\n");
}

void BaseClient::signal_cb(ev::sig &signal, int revents)
{
	LOG_EV(this, "Signaled destroy!!\n");
	destroy();
	delete this;
}

void BaseClient::destroy()
{
	if (destroyed) {
		return;
	}

	destroyed = true;

	close();

	// Stop and free watcher if client socket is closing
	io.stop();
	async.stop();

	::close(sock);
	LOG_OBJ(this, "DESTROYED!\n");
}

void BaseClient::close() {
	if (closed) {
		return;
	}

	closed = true;
	LOG_OBJ(this, "CLOSED!\n");
}

void BaseClient::async_cb(ev::async &watcher, int revents)
{
	if (destroyed) {
		return;
	}

	LOG_EV(this, "ASYNC_CB (sock=%d) %x\n", sock, revents);

	if (write_queue.empty()) {
		if (closed) {
			destroy();
		}
	} else {
		io.set(ev::READ|ev::WRITE);
	}

	if (destroyed) {
		delete this;
	}
}

void BaseClient::io_cb(ev::io &watcher, int revents)
{
	if (destroyed) {
		return;
	}

	assert(sock == watcher.fd);

	LOG_EV(this, "IO_CB (sock=%d) %x\n", sock, revents);

	if (revents & EV_ERROR) {
		LOG_ERR(this, "ERROR: got invalid event (sock=%d): %s\n", sock, strerror(errno));
		destroy();
		return;
	}

	if (revents & EV_READ)
		read_cb(watcher);

	if (revents & EV_WRITE)
		write_cb(watcher);

	if (write_queue.empty()) {
		if (closed) {
			destroy();
		} else {
			io.set(ev::READ);
		}
	} else {
		io.set(ev::READ|ev::WRITE);
	}

	if (destroyed) {
		delete this;
	}
}

void BaseClient::write_cb(ev::io &watcher)
{
	if (!write_queue.empty()) {
		Buffer* buffer = write_queue.front();

		size_t buf_size = buffer->nbytes();
		const char * buf = buffer->dpos();

		LOG_CONN(this, "(sock=%d) <<-- '%s'\n", sock, repr(buf, buf_size).c_str());

		ssize_t written = ::write(sock, buf, buf_size);

		if (written < 0) {
			if (errno != EAGAIN) {
				LOG_ERR(this, "ERROR: write error (sock=%d): %s\n", sock, strerror(errno));
				destroy();
			}
		} else if (written == 0) {
			// nothing written?
		} else {
			buffer->pos += written;
			if (buffer->nbytes() == 0) {
				write_queue.pop(buffer);
				delete buffer;
			}
		}
	}
}

void BaseClient::read_cb(ev::io &watcher)
{
	char buf[1024];

	ssize_t received = ::read(sock, buf, sizeof(buf));

	if (received < 0) {
		if (errno != EAGAIN) {
			LOG_ERR(this, "ERROR: read error (sock=%d): %s\n", sock, strerror(errno));
			destroy();
		}
	} else if (received == 0) {
		// The peer has closed its half side of the connection.
		LOG_CONN(this, "Received EOF (sock=%d)!\n", sock);
		destroy();
	} else {
		LOG_CONN(this, "(sock=%d) -->> '%s'\n", sock, repr(buf, received).c_str());
		on_read(buf, received);
	}
}

void BaseClient::write(const char *buf, size_t buf_size)
{
	Buffer *buffer = new Buffer('\0', buf, buf_size);
	write_queue.push(buffer);

	async.send();
}
<|endoftext|>


<commit_before>#include "playerwidget.h"
#include "ui_playerwidget.h"
#include "musicselector.h"

static QString _ms2mmss(qint64 ms)
{
	int ss = ms / 1000;
	int mm = ss / 60;
	ss = ss % 60;

	QString str;
	str.sprintf("%02d:%02d", mm, ss);
	return str;
}

LRCX_BEGIN_NS

PlayerWidget::PlayerWidget(QWidget *parent)
	: QDockWidget(parent)
	, m_ui(new Ui::PlayerWidget)
{
	m_ui->setupUi(this);

	connect(m_ui->btn_Open, SIGNAL(clicked(bool)), this, SLOT(onBtnOpen_Clicked()));
	connect(m_ui->btn_PlayPause, SIGNAL(clicked(bool)), this, SLOT(onBtnPlayPause_Clicked()));
	connect(m_ui->slider_Duration, SIGNAL(sliderReleased()), this, SLOT(onSliderDuration_Changed()) );
}

PlayerWidget::~PlayerWidget()
{

}

QString PlayerWidget::getTitle() const
{
	return m_ui->le_Title->text().trimmed();
}

QString PlayerWidget::getArtist() const
{
	return m_ui->le_Artist->text().trimmed();
}

QString PlayerWidget::getAlbum() const
{
	return m_ui->le_Album->text().trimmed();
}

QString PlayerWidget::getEditor() const
{
	return m_ui->le_Editor->text().trimmed();
}

qint64 PlayerWidget::getCurrentPosition() const
{
	if (m_player)
		return m_player->position();
	return 0;
}

void PlayerWidget::onBtnOpen_Clicked()
{
	std::unique_ptr<Player> player(MusicSelector::select());
	if (player == nullptr)
		return ;

	m_ui->le_Title->setText(player->metaData(Player::Title).toString());
	m_ui->le_Artist->setText(player->metaData(Player::Artist).toString());
	m_ui->le_Album->setText(player->metaData(Player::AlbumTitle).toString());
	if (m_ui->le_Editor->text().trimmed().isEmpty())
		m_ui->le_Editor->setText(tr("LyricsX"));

	m_ui->btn_PlayPause->setEnabled(true);
	m_ui->slider_Duration->setEnabled(true);

	if (m_player)
		m_player->disconnect();

	m_player = std::move(player);

	connect(m_player.get(), SIGNAL(stateChanged(Player::State)), this, SLOT(onPlayerStateChanged(Player::State)));
	connect(m_player.get(), SIGNAL(durationChanged(qint64)), this, SLOT(onPlayerDurationChanged(qint64)));
	connect(m_player.get(), SIGNAL(positionChanged(qint64)), this, SLOT(onPlayerPositionChanged(qint64)));
}

void PlayerWidget::onBtnPlayPause_Clicked()
{
	if (m_player)
	{
		if (m_player->state() == Player::Playing)
			m_player->pause();
		else
			m_player->play();
	}
}

void PlayerWidget::onSliderDuration_Changed()
{
	if (m_player)
	{
		int pos = m_ui->slider_Duration->value();
		if (m_player->position() != pos)
		{
			m_ui->slider_Duration->blockSignals(true);
			m_player->setPosition(pos);
			m_ui->slider_Duration->blockSignals(false);
		}
	}
}

void PlayerWidget::onPlayerStateChanged(Player::State state)
{
	QIcon icon = QIcon::fromTheme(state == Player::Playing ?
									  "media-playback-pause" :
									  "media-playback-start"
				);
	m_ui->btn_PlayPause->setIcon(icon);
}

void PlayerWidget::onPlayerDurationChanged(qint64 duration)
{
	m_ui->slider_Duration->setMaximum(duration);
}

void PlayerWidget::onPlayerPositionChanged(qint64 pos)
{
	qint64 total = m_player->duration();
	QString strText = _ms2mmss(pos) + "/" + _ms2mmss(total);
	m_ui->label_Duration->setText(strText);

	m_ui->slider_Duration->blockSignals(true);
	m_ui->slider_Duration->setValue(pos);
	m_ui->slider_Duration->blockSignals(false);
}

LRCX_END_NS
<commit_msg>update window title while selected music<commit_after>#include "playerwidget.h"
#include "ui_playerwidget.h"
#include "musicselector.h"

static QString _ms2mmss(qint64 ms)
{
	int ss = ms / 1000;
	int mm = ss / 60;
	ss = ss % 60;

	QString str;
	str.sprintf("%02d:%02d", mm, ss);
	return str;
}

LRCX_BEGIN_NS

PlayerWidget::PlayerWidget(QWidget *parent)
	: QDockWidget(parent)
	, m_ui(new Ui::PlayerWidget)
{
	m_ui->setupUi(this);

	connect(m_ui->btn_Open, SIGNAL(clicked(bool)), this, SLOT(onBtnOpen_Clicked()));
	connect(m_ui->btn_PlayPause, SIGNAL(clicked(bool)), this, SLOT(onBtnPlayPause_Clicked()));
	connect(m_ui->slider_Duration, SIGNAL(sliderReleased()), this, SLOT(onSliderDuration_Changed()) );
}

PlayerWidget::~PlayerWidget()
{

}

QString PlayerWidget::getTitle() const
{
	return m_ui->le_Title->text().trimmed();
}

QString PlayerWidget::getArtist() const
{
	return m_ui->le_Artist->text().trimmed();
}

QString PlayerWidget::getAlbum() const
{
	return m_ui->le_Album->text().trimmed();
}

QString PlayerWidget::getEditor() const
{
	return m_ui->le_Editor->text().trimmed();
}

qint64 PlayerWidget::getCurrentPosition() const
{
	if (m_player)
		return m_player->position();
	return 0;
}

void PlayerWidget::onBtnOpen_Clicked()
{
	std::unique_ptr<Player> player(MusicSelector::select());
	if (player == nullptr)
		return ;

	m_ui->le_Title->setText(player->metaData(Player::Title).toString());
	m_ui->le_Artist->setText(player->metaData(Player::Artist).toString());
	m_ui->le_Album->setText(player->metaData(Player::AlbumTitle).toString());
	if (m_ui->le_Editor->text().trimmed().isEmpty())
		m_ui->le_Editor->setText(tr("LyricsX"));

	QString strTitle = player->metaData(Player::Artist).toString();
	strTitle += " - " + player->metaData(Player::Title).toString();
	setWindowTitle(strTitle);

	m_ui->btn_PlayPause->setEnabled(true);
	m_ui->slider_Duration->setEnabled(true);

	if (m_player)
		m_player->disconnect();

	m_player = std::move(player);

	connect(m_player.get(), SIGNAL(stateChanged(Player::State)), this, SLOT(onPlayerStateChanged(Player::State)));
	connect(m_player.get(), SIGNAL(durationChanged(qint64)), this, SLOT(onPlayerDurationChanged(qint64)));
	connect(m_player.get(), SIGNAL(positionChanged(qint64)), this, SLOT(onPlayerPositionChanged(qint64)));
}

void PlayerWidget::onBtnPlayPause_Clicked()
{
	if (m_player)
	{
		if (m_player->state() == Player::Playing)
			m_player->pause();
		else
			m_player->play();
	}
}

void PlayerWidget::onSliderDuration_Changed()
{
	if (m_player)
	{
		int pos = m_ui->slider_Duration->value();
		if (m_player->position() != pos)
		{
			m_ui->slider_Duration->blockSignals(true);
			m_player->setPosition(pos);
			m_ui->slider_Duration->blockSignals(false);
		}
	}
}

void PlayerWidget::onPlayerStateChanged(Player::State state)
{
	QIcon icon = QIcon::fromTheme(state == Player::Playing ?
									  "media-playback-pause" :
									  "media-playback-start"
				);
	m_ui->btn_PlayPause->setIcon(icon);
}

void PlayerWidget::onPlayerDurationChanged(qint64 duration)
{
	m_ui->slider_Duration->setMaximum(duration);
}

void PlayerWidget::onPlayerPositionChanged(qint64 pos)
{
	qint64 total = m_player->duration();
	QString strText = _ms2mmss(pos) + "/" + _ms2mmss(total);
	m_ui->label_Duration->setText(strText);

	m_ui->slider_Duration->blockSignals(true);
	m_ui->slider_Duration->setValue(pos);
	m_ui->slider_Duration->blockSignals(false);
}

LRCX_END_NS
<|endoftext|>


<commit_before>#ifndef DEDICATED_ONLY

#include "CViewport.h"

#include "gusgame.h"
#include "sound/sfx.h"
#include "gfx.h"
#include "gusanos/allegro.h"
#include "CWorm.h"
#include "game/WormInputHandler.h"
#include "CWormHuman.h"
#include "glua.h"
#include "lua/bindings-gfx.h"
#include "blitters/blitters.h"
#include "culling.h"
#include "CMap.h"
#include "game/Game.h"
#include <list>

#include "sprite_set.h" // TEMP
#include "sprite.h" // TEMP
#include "CGameScript.h"

#include <iostream>

using namespace std;

void CViewport::gusInit()
{
	dest = 0;
	hud = 0;
	fadeBuffer = 0;
}

void CViewport::gusReset()
{
	if(luaReference) lua.destroyReference(luaReference); luaReference = LuaReference();
	destroy_bitmap(dest); dest = 0;
	destroy_bitmap(hud); hud = 0;
	destroy_bitmap(fadeBuffer); fadeBuffer = 0;
}

struct TestCuller : public Culler<TestCuller>
{
	TestCuller(ALLEGRO_BITMAP* dest_, ALLEGRO_BITMAP* src_, int scrOffX_, int scrOffY_, int destOffX_, int destOffY_, Rect const& rect)
			: Culler<TestCuller>(rect), dest(dest_), src(src_),
			scrOffX(scrOffX_), scrOffY(scrOffY_), destOffX(destOffX_), destOffY(destOffY_)
	{
	}

	bool block(int x, int y)
	{
		return !gusGame.level().unsafeGetMaterial(x, y).worm_pass;
	}

	void line(int y, int x1, int x2)
	{
		//hline_add(dest, x1 + scrOffX, y + scrOffY, x2 + scrOffX + 1, makecol(50, 50, 50), 255);

		drawSpriteLine_add(
		    dest,
		    src,
		    x1 + scrOffX,
		    y + scrOffY,
		    x1 + destOffX,
		    y + destOffY,
		    x2 + destOffX + 1,
		    255);
	}

	ALLEGRO_BITMAP* dest;
	ALLEGRO_BITMAP* src;

	int scrOffX;
	int scrOffY;
	int destOffX;
	int destOffY;
};

static ALLEGRO_BITMAP* testLight = 0;

void CViewport::setDestination(ALLEGRO_BITMAP* where, int x, int y, int width, int height)
{
	if(width > where->w
	   || height > where->h) {
		errors << "CViewport::setDestination: " << width << "x" << height << " too big" << endl;
		return;
	}

	if(luaReference) lua.destroyReference(luaReference);
	destroy_bitmap(dest);
	destroy_bitmap(hud);
	if ( x < 0 )
		x = 0;
	if ( y < 0 )
		y = 0;
	if ( x + width > where->w )
		x = where->w - width;
	if ( y + height > where->h )
		y = where->h - height;
	dest = create_sub_bitmap(where,x,y,width,height);
	hud = create_sub_bitmap(where,x,y,width,height);

	destroy_bitmap(fadeBuffer);
	fadeBuffer = create_bitmap_ex(8, width, height);

	if(!testLight) {
		static int s = 500;
		destroy_bitmap(testLight);
		testLight = create_bitmap_ex(8, s, s);

		for(int y = 0; y < s; ++y)
			for(int x = 0; x < s; ++x) {
				double v = 1.0*(double(s)/2 - (IVec(x, y) - IVec(s/2, s/2)).length());
				if(v < 0.0)
					v = 0.0;
				int iv = int(v);
				putpixel_solid(testLight, x, y, iv);
			}
	}

	lua.pushFullReference(*this, LuaBindings::CViewportMetaTable);
	//lua.pushLightReference(this, LuaBindings::viewportMetaTable);
	luaReference = lua.createReference();
}

void CViewport::drawLight(IVec const& v)
{
	IVec off(Left,Top);
	IVec loff(v - IVec(testLight->w/2, testLight->h/2));

	Rect r(0, 0, gusGame.level().GetWidth() - 1, gusGame.level().GetHeight() - 1);
	r &= Rect(testLight) + loff;

	TestCuller testCuller(fadeBuffer, testLight, -off.x, -off.y, -loff.x, -loff.y, r);

	testCuller.cullOmni(v.x, v.y);
}

void CViewport::gusRender()
{
	{
		int destx = Left/2;
		int desty = Top/2;
		int destw = Width;
		int desth = Height;
		bool needDestReset = false;
		if(!dest)
			needDestReset = true;
		else if(dest->sub_x != destx || dest->sub_y != desty || dest->w != destw || dest->h != desth )
			needDestReset = true;
		else if(dest->surf.get() != gfx.buffer->surf.get())
			needDestReset = true;

		if(needDestReset)
			setDestination(gfx.buffer, destx, desty, destw, desth);
	}

	int offX = static_cast<int>(WorldX);
	int offY = static_cast<int>(WorldY);

	gusGame.level().gusDraw(dest, offX, offY);

	if ( gusGame.level().config()->darkMode && gusGame.level().lightmap )
		blit( gusGame.level().lightmap, fadeBuffer, offX,offY, 0, 0, fadeBuffer->w, fadeBuffer->h );

	for ( Grid::iterator iter = game.objects.beginAll(); iter; ++iter) {
		//iter->draw(dest, offX, offY);
		iter->draw(this);
	}

	/*
		static double a = 0.0;
		a += 0.003;
		*/

#if 0
	if(gfx.m_haxWormLight) {
		CWormInputHandler* player = game.localPlayers[0];

		CWorm* worm = player->getWorm();
		if(worm->isActive()) {
			IVec v(worm->pos);
			drawLight(v);
		}
	}
#endif

	if(gusGame.level().config()->darkMode)
		drawSprite_mult_8(dest, fadeBuffer, 0, 0);

	// only use the player/worm specific drawings in gus mods
	if(game.gameScript()->gusEngineUsed()) {
		CWormInputHandler* player = pcTargetWorm ? pcTargetWorm->inputHandler() : NULL;

		// Note that we only process worms in the Lua callbacks which have a player set.
		// Most Lua code depends on this assumption so it would break otherwise.

		EACH_CALLBACK(i, wormRender) {
			for(vector<CWormInputHandler*>::iterator playerIter = game.players.begin(); playerIter != game.players.end(); ++playerIter) {
				CWorm* worm = (*playerIter)->getWorm();
				if( worm && worm->isActive() && worm->inputHandler() ) {
					IVec renderPos( worm->getRenderPos() );
					int x = renderPos.x - offX;
					int y = renderPos.y - offY;
					//bool ownViewport = (*playerIter == player);
					LuaReference ownerRef;

					if ( player )
						ownerRef = player->getLuaReference();

					//lua.callReference(0, *i, (lua_Number)x, (lua_Number)y, worm->luaReference, luaReference, ownViewport);
					(lua.call(*i), (lua_Number)x, (lua_Number)y, worm->getLuaReference(), luaReference, ownerRef)();
				}
			}
		}

		// draw viewport specific stuff only for human worms
		if(pcTargetWorm && dynamic_cast<CWormHumanInputHandler*>(pcTargetWorm->inputHandler()) != NULL) {
			EACH_CALLBACK(i, viewportRender) {
				//lua.callReference(0, *i, luaReference, worm->luaReference);
				(lua.call(*i), luaReference, pcTargetWorm->getLuaReference())();
			}
		}
	}

	// no gus mod
	else {

	}
}

#endif
<commit_msg>cleanup. deleting old commented-out code<commit_after>#ifndef DEDICATED_ONLY

#include "CViewport.h"

#include "gusgame.h"
#include "sound/sfx.h"
#include "gfx.h"
#include "gusanos/allegro.h"
#include "CWorm.h"
#include "game/WormInputHandler.h"
#include "CWormHuman.h"
#include "glua.h"
#include "lua/bindings-gfx.h"
#include "blitters/blitters.h"
#include "culling.h"
#include "CMap.h"
#include "game/Game.h"
#include <list>

#include "sprite_set.h" // TEMP
#include "sprite.h" // TEMP
#include "CGameScript.h"

#include <iostream>

using namespace std;

void CViewport::gusInit()
{
	dest = 0;
	hud = 0;
	fadeBuffer = 0;
}

void CViewport::gusReset()
{
	if(luaReference) lua.destroyReference(luaReference); luaReference = LuaReference();
	destroy_bitmap(dest); dest = 0;
	destroy_bitmap(hud); hud = 0;
	destroy_bitmap(fadeBuffer); fadeBuffer = 0;
}

struct TestCuller : public Culler<TestCuller>
{
	TestCuller(ALLEGRO_BITMAP* dest_, ALLEGRO_BITMAP* src_, int scrOffX_, int scrOffY_, int destOffX_, int destOffY_, Rect const& rect)
			: Culler<TestCuller>(rect), dest(dest_), src(src_),
			scrOffX(scrOffX_), scrOffY(scrOffY_), destOffX(destOffX_), destOffY(destOffY_)
	{
	}

	bool block(int x, int y)
	{
		return !gusGame.level().unsafeGetMaterial(x, y).worm_pass;
	}

	void line(int y, int x1, int x2)
	{
		//hline_add(dest, x1 + scrOffX, y + scrOffY, x2 + scrOffX + 1, makecol(50, 50, 50), 255);

		drawSpriteLine_add(
		    dest,
		    src,
		    x1 + scrOffX,
		    y + scrOffY,
		    x1 + destOffX,
		    y + destOffY,
		    x2 + destOffX + 1,
		    255);
	}

	ALLEGRO_BITMAP* dest;
	ALLEGRO_BITMAP* src;

	int scrOffX;
	int scrOffY;
	int destOffX;
	int destOffY;
};

static ALLEGRO_BITMAP* testLight = 0;

void CViewport::setDestination(ALLEGRO_BITMAP* where, int x, int y, int width, int height)
{
	if(width > where->w
	   || height > where->h) {
		errors << "CViewport::setDestination: " << width << "x" << height << " too big" << endl;
		return;
	}

	if(luaReference) lua.destroyReference(luaReference);
	destroy_bitmap(dest);
	destroy_bitmap(hud);
	if ( x < 0 )
		x = 0;
	if ( y < 0 )
		y = 0;
	if ( x + width > where->w )
		x = where->w - width;
	if ( y + height > where->h )
		y = where->h - height;
	dest = create_sub_bitmap(where,x,y,width,height);
	hud = create_sub_bitmap(where,x,y,width,height);

	destroy_bitmap(fadeBuffer);
	fadeBuffer = create_bitmap_ex(8, width, height);

	if(!testLight) {
		static int s = 500;
		destroy_bitmap(testLight);
		testLight = create_bitmap_ex(8, s, s);

		for(int y = 0; y < s; ++y)
			for(int x = 0; x < s; ++x) {
				double v = 1.0*(double(s)/2 - (IVec(x, y) - IVec(s/2, s/2)).length());
				if(v < 0.0)
					v = 0.0;
				int iv = int(v);
				putpixel_solid(testLight, x, y, iv);
			}
	}

	lua.pushFullReference(*this, LuaBindings::CViewportMetaTable);
	luaReference = lua.createReference();
}

void CViewport::drawLight(IVec const& v)
{
	IVec off(Left,Top);
	IVec loff(v - IVec(testLight->w/2, testLight->h/2));

	Rect r(0, 0, gusGame.level().GetWidth() - 1, gusGame.level().GetHeight() - 1);
	r &= Rect(testLight) + loff;

	TestCuller testCuller(fadeBuffer, testLight, -off.x, -off.y, -loff.x, -loff.y, r);

	testCuller.cullOmni(v.x, v.y);
}

void CViewport::gusRender()
{
	{
		int destx = Left/2;
		int desty = Top/2;
		int destw = Width;
		int desth = Height;
		bool needDestReset = false;
		if(!dest)
			needDestReset = true;
		else if(dest->sub_x != destx || dest->sub_y != desty || dest->w != destw || dest->h != desth )
			needDestReset = true;
		else if(dest->surf.get() != gfx.buffer->surf.get())
			needDestReset = true;

		if(needDestReset)
			setDestination(gfx.buffer, destx, desty, destw, desth);
	}

	int offX = static_cast<int>(WorldX);
	int offY = static_cast<int>(WorldY);

	gusGame.level().gusDraw(dest, offX, offY);

	if ( gusGame.level().config()->darkMode && gusGame.level().lightmap )
		blit( gusGame.level().lightmap, fadeBuffer, offX,offY, 0, 0, fadeBuffer->w, fadeBuffer->h );

	for ( Grid::iterator iter = game.objects.beginAll(); iter; ++iter)
		iter->draw(this);

#if 0
	if(gfx.m_haxWormLight) {
		CWormInputHandler* player = game.localPlayers[0];

		CWorm* worm = player->getWorm();
		if(worm->isActive()) {
			IVec v(worm->pos);
			drawLight(v);
		}
	}
#endif

	if(gusGame.level().config()->darkMode)
		drawSprite_mult_8(dest, fadeBuffer, 0, 0);

	// only use the player/worm specific drawings in gus mods
	if(game.gameScript()->gusEngineUsed()) {
		CWormInputHandler* player = pcTargetWorm ? pcTargetWorm->inputHandler() : NULL;

		// Note that we only process worms in the Lua callbacks which have a player set.
		// Most Lua code depends on this assumption so it would break otherwise.

		EACH_CALLBACK(i, wormRender) {
			for(vector<CWormInputHandler*>::iterator playerIter = game.players.begin(); playerIter != game.players.end(); ++playerIter) {
				CWorm* worm = (*playerIter)->getWorm();
				if( worm && worm->isActive() && worm->inputHandler() ) {
					IVec renderPos( worm->getRenderPos() );
					int x = renderPos.x - offX;
					int y = renderPos.y - offY;
					LuaReference ownerRef;

					if ( player )
						ownerRef = player->getLuaReference();

					(lua.call(*i), (lua_Number)x, (lua_Number)y, worm->getLuaReference(), luaReference, ownerRef)();
				}
			}
		}

		// draw viewport specific stuff only for human worms
		if(pcTargetWorm && dynamic_cast<CWormHumanInputHandler*>(pcTargetWorm->inputHandler()) != NULL) {
			EACH_CALLBACK(i, viewportRender) {
				(lua.call(*i), luaReference, pcTargetWorm->getLuaReference())();
			}
		}
	}
}

#endif
<|endoftext|>


<commit_before>/*  ************************************************************************************
 *
 *  ftVelocityMask
 *
 *  Created by Matthias Oostrik on 03/16.14.
 *  Copyright 2014 http://www.MatthiasOostrik.com All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the author nor the names of its contributors
 *       may be used to endorse or promote products derived from this software
 *       without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 *  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 *  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 *  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 *  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 *  OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 *  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 *  OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *  ************************************************************************************ */

#include "ftVelocityMask.h"

namespace flowTools {

	void	ftVelocityMask::setup(int _width, int _height){
		width = _width;
		height = _height;

		colorMaskSwapBuffer.allocate(width, height, GL_RGBA);
		colorMaskSwapBuffer.clear();

		luminanceMaskFbo.allocate(width, height, GL_RGB);
		luminanceMaskFbo.clear();

		parameters.setName("velocity mask");
		parameters.add(strength.set("strength", 1, 0, 10));
		parameters.add(saturation.set("saturation", 1, 1, 5));
		parameters.add(blurPasses.set("blur passes", 1, 0, 10));
		parameters.add(blurRadius.set("blur radius", 6, 0, 10));

	};

	void ftVelocityMask::update() {
		ofPushStyle();
		ofEnableBlendMode(OF_BLENDMODE_ALPHA);
		colorMaskSwapBuffer.clear();

		VelocityMaskShader.update(*colorMaskSwapBuffer.src, *densityTexture, *velocityTexture, strength.get());
		HSLShader.update(*colorMaskSwapBuffer.dst,
						 colorMaskSwapBuffer.src->getTextureReference(),
						 0,
						 saturation.get(),
						 1);
		colorMaskSwapBuffer.swap();

		if (blurPasses.get() > 0 && blurRadius.get() > 0) {
			gaussianBlurShader.update(*colorMaskSwapBuffer.src, blurPasses.get(), blurRadius.get());
		}
		luminanceShader.update(luminanceMaskFbo, colorMaskSwapBuffer.src->getTextureReference());

		ofPopStyle();
	}

	void ftVelocityMask::setDensity(ofTexture &tex) {
		densityTexture = &tex;
	}

	void ftVelocityMask::setVelocity(ofTexture &tex) {
		velocityTexture = &tex;
	}
}<commit_msg>Update ftVelocityMask.cpp<commit_after>/*  ************************************************************************************
 *
 *  ftVelocityMask
 *
 *  Created by Matthias Oostrik on 03/16.14.
 *  Copyright 2014 http://www.MatthiasOostrik.com All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the author nor the names of its contributors
 *       may be used to endorse or promote products derived from this software
 *       without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 *  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 *  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 *  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 *  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 *  OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 *  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 *  OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *  ************************************************************************************ */

#include "ftVelocityMask.h"

namespace flowTools {

	void	ftVelocityMask::setup(int _width, int _height){
		width = _width;
		height = _height;

		colorMaskSwapBuffer.allocate(width, height, GL_RGBA);
		colorMaskSwapBuffer.clear();

		luminanceMaskFbo.allocate(width, height, GL_RGB);
		luminanceMaskFbo.clear();

		parameters.setName("velocity mask");
		parameters.add(strength.set("strength", 1, 0, 10));
		parameters.add(saturation.set("saturation", 1, 1, 5));
		parameters.add(blurPasses.set("blur passes", 1, 0, 10));
		parameters.add(blurRadius.set("blur radius", 6, 0, 10));

	};

	void ftVelocityMask::update() {
		ofPushStyle();
		ofEnableBlendMode(OF_BLENDMODE_ALPHA);
		colorMaskSwapBuffer.clear();

		VelocityMaskShader.update(*colorMaskSwapBuffer.src, *densityTexture, *velocityTexture, strength.get());
		HSLShader.update(*colorMaskSwapBuffer.dst,
						 colorMaskSwapBuffer.src->getTextureReference(),
						 0,
						 saturation.get(),
						 1);
		colorMaskSwapBuffer.swap();

		if (blurPasses.get() > 0 && blurRadius.get() > 0) {
			gaussianBlurShader.update(*colorMaskSwapBuffer.src, blurPasses.get(), blurRadius.get());
		}

		ofEnableBlendMode(OF_BLENDMODE_DISABLED);
		luminanceShader.update(luminanceMaskFbo, colorMaskSwapBuffer.src->getTextureReference());

		ofPopStyle();
	}

	void ftVelocityMask::setDensity(ofTexture &tex) {
		densityTexture = &tex;
	}

	void ftVelocityMask::setVelocity(ofTexture &tex) {
		velocityTexture = &tex;
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TitledControl.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 19:16:21 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "taskpane/TitledControl.hxx"

#include "AccessibleTreeNode.hxx"
#include "taskpane/ControlContainer.hxx"
#include "TaskPaneFocusManager.hxx"
#include "taskpane/TaskPaneControlFactory.hxx"

#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

namespace sd { namespace toolpanel {

TitledControl::TitledControl (
    TreeNode* pParent,
    ::std::auto_ptr<TreeNode> pControl,
    const String& rTitle,
    TitleBar::TitleBarType eType)
    : ::Window (pParent->GetWindow(), WB_TABSTOP),
      TreeNode(pParent),
      msTitle(rTitle),
      mbVisible(true),
      mpUserData(NULL),
      mpControlFactory(NULL),
      mbExpansionModeIsToggle(eType!=TitleBar::TBT_CONTROL_TITLE)
{
    if (pControl.get() != NULL)
    {
        mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
            new TitleBar (this, rTitle, eType, pControl->IsExpandable())));
        pControl->SetParentNode (this);
    }
    mpControlContainer->AddControl (pControl);

    FocusManager::Instance().RegisterDownLink(this, GetControl()->GetWindow());
    FocusManager::Instance().RegisterUpLink(GetControl()->GetWindow(), this);

    SetBackground (Wallpaper());

    GetTitleBar()->GetWindow()->Show ();
    GetTitleBar()->GetWindow()->AddEventListener (
        LINK(this,TitledControl,WindowEventListener));

    UpdateStates ();
}

TitledControl::TitledControl (
    TreeNode* pParent,
    ::std::auto_ptr<ControlFactory> pControlFactory,
    const String& rTitle,
    TitleBar::TitleBarType eType)
    : ::Window (pParent->GetWindow(), WB_TABSTOP),
      TreeNode(pParent),
      msTitle (rTitle),
      mbVisible (true),
      mpUserData (NULL),
      mpControlFactory(pControlFactory),
      mbExpansionModeIsToggle(eType!=TitleBar::TBT_CONTROL_TITLE)
{
    mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
        new TitleBar (this, rTitle, eType, true)));

    // The second control is created on demand, i.e. when GetControl(true)
    // is called the first time.

    SetBackground (Wallpaper());

    GetTitleBar()->GetWindow()->Show ();
    GetTitleBar()->GetWindow()->AddEventListener (
        LINK(this,TitledControl,WindowEventListener));

    UpdateStates ();
}

TitledControl::~TitledControl (void)
{
    GetTitleBar()->GetWindow()->RemoveEventListener (
        LINK(this,TitledControl,WindowEventListener));
}

Size TitledControl::GetPreferredSize (void)
{
    Size aPreferredSize;
    if (GetControl(false) != NULL)
    {
        aPreferredSize = GetControl()->GetPreferredSize();
        if ( ! IsExpanded())
            aPreferredSize.Height() = 0;
    }
    else
        aPreferredSize = Size (GetSizePixel().Width(), 0);
    if (aPreferredSize.Width() == 0)
        aPreferredSize.Width() = 300;
    aPreferredSize.Height() += GetTitleBar()->GetPreferredHeight(
        aPreferredSize.Width());

    return aPreferredSize;
}

sal_Int32 TitledControl::GetPreferredWidth (sal_Int32 nHeight)
{
    int nPreferredWidth = 0;
    if (GetControl(false) != NULL)
        nPreferredWidth = GetControl()->GetPreferredWidth(
            nHeight - GetTitleBar()->GetWindow()->GetSizePixel().Height());
    else
        nPreferredWidth = GetSizePixel().Width();
    if (nPreferredWidth == 0)
        nPreferredWidth = 300;

    return nPreferredWidth;
}

sal_Int32 TitledControl::GetPreferredHeight (sal_Int32 nWidth)
{
    int nPreferredHeight = 0;
    if (IsExpanded() && GetControl(false)!=NULL)
        nPreferredHeight = GetControl()->GetPreferredHeight(nWidth);
    nPreferredHeight += GetTitleBar()->GetPreferredHeight(nWidth);

    return nPreferredHeight;
}

bool TitledControl::IsResizable (void)
{
    return IsExpanded()
        && GetControl()->IsResizable();
}

::Window* TitledControl::GetWindow (void)
{
    return this;
}

void TitledControl::Resize (void)
{
    Size aWindowSize (GetOutputSizePixel());

    int nTitleBarHeight
        = GetTitleBar()->GetPreferredHeight(aWindowSize.Width());
    GetTitleBar()->GetWindow()->SetPosSizePixel (
        Point (0,0),
        Size (aWindowSize.Width(), nTitleBarHeight));

    TreeNode* pControl = GetControl(false);
    if (pControl != NULL
        && pControl->GetWindow() != NULL
        && pControl->GetWindow()->IsVisible())
    {
        pControl->GetWindow()->SetPosSizePixel (
            Point (0,nTitleBarHeight),
            Size (aWindowSize.Width(), aWindowSize.Height()-nTitleBarHeight));
    }
}

void TitledControl::GetFocus (void)
{
    ::Window::GetFocus();
    if (GetTitleBar() != NULL)
        GetTitleBar()->SetFocus (true);
}

void TitledControl::LoseFocus (void)
{
    ::Window::LoseFocus();
    if (GetTitleBar() != NULL)
        GetTitleBar()->SetFocus (false);
}

void TitledControl::KeyInput (const KeyEvent& rEvent)
{
    KeyCode nCode = rEvent.GetKeyCode();
    if (nCode == KEY_SPACE)
    {
        // Toggle the expansion state of the control (when toggling is
        // supported.)  The focus remains on this control.
        GetParentNode()->GetControlContainer().SetExpansionState (
            this,
            ControlContainer::ES_TOGGLE);
    }
    else if (nCode == KEY_RETURN)
    {
        // Return, also called enter, enters the control and puts the
        // focus to the first child.  If the control is not yet
        // expanded then do that first.
        GetParentNode()->GetControlContainer().SetExpansionState (
            this,
            ControlContainer::ES_EXPAND);

        if ( ! FocusManager::Instance().TransferFocus(this,nCode))
        {
            // When already expanded then put focus on first child.
            TreeNode* pControl = GetControl(false);
            if (pControl!=NULL && IsExpanded())
                if (pControl->GetWindow() != NULL)
                    pControl->GetWindow()->GrabFocus();
        }
    }
    else if (nCode == KEY_ESCAPE)
    {
        if ( ! FocusManager::Instance().TransferFocus(this,nCode))
            // Put focus to parent.
            GetParent()->GrabFocus();
    }
    else
        Window::KeyInput (rEvent);
}

const String& TitledControl::GetTitle (void) const
{
    return msTitle;
}

bool TitledControl::Expand (bool bExpanded)
{
    bool bExpansionStateChanged (false);

    if (IsExpandable())
    {
        if (GetTitleBar()->IsExpanded() != bExpanded)
            bExpansionStateChanged |= GetTitleBar()->Expand (bExpanded);
        // Get the control.  Use the bExpanded parameter as argument to
        // indicate that a control is created via its factory only when it
        // is to be expanded.  When it is collapsed this is not necessary.
        TreeNode* pControl = GetControl(bExpanded);
        if (pControl != NULL
            && GetControl()->IsExpanded() != bExpanded)
        {
            bExpansionStateChanged |= pControl->Expand (bExpanded);
        }
        if (bExpansionStateChanged)
            UpdateStates();
    }

    return bExpansionStateChanged;
}

bool TitledControl::IsExpandable (void) const
{
    const TreeNode* pControl = GetConstControl(false);
    if (pControl != NULL)
        return pControl->IsExpandable();
    else
        // When a control factory is given but the control has not yet been
        // created we assume that the control is expandable.
        return true;
}

bool TitledControl::IsExpanded (void) const
{
    const TreeNode* pControl = GetConstControl(false);
    if (pControl != NULL)
        return pControl->IsExpanded();
    else
        return false;
}

void TitledControl::SetUserData (void* pUserData)
{
    mpUserData = pUserData;
}

void* TitledControl::GetUserData (void) const
{
    return mpUserData;
}

bool TitledControl::IsShowing (void) const
{
    return mbVisible;
}

void TitledControl::Show (bool bVisible)
{
    if (mbVisible != bVisible)
    {
        mbVisible = bVisible;
        UpdateStates ();
    }
}

void TitledControl::UpdateStates (void)
{
    if (mbVisible)
        GetWindow()->Show();
    else
        GetWindow()->Hide();

    TreeNode* pControl = GetControl(false);
    if (pControl!=NULL  &&  pControl->GetWindow() != NULL)
        if (IsVisible() && IsExpanded())
            pControl->GetWindow()->Show();
        else
            pControl->GetWindow()->Hide();
}

IMPL_LINK(TitledControl, WindowEventListener,
    VclSimpleEvent*, pEvent)
{
    if (pEvent!=NULL && pEvent->ISA(VclWindowEvent))
    {
        VclWindowEvent* pWindowEvent = static_cast<VclWindowEvent*>(pEvent);
        switch (pWindowEvent->GetId())
        {
            case VCLEVENT_WINDOW_MOUSEBUTTONUP:
                // Toggle expansion.
                GetParentNode()->GetControlContainer().SetExpansionState (
                    this,
                    mbExpansionModeIsToggle ? ControlContainer::ES_TOGGLE
                                            : ControlContainer::ES_EXPAND);
                break;
        }
    }
    return 0;
}

TreeNode* TitledControl::GetControl (bool bCreate)
{
    TreeNode* pNode = mpControlContainer->GetControl(1);
    if (pNode==NULL && mpControlFactory.get()!=NULL && bCreate)
    {
        // We have to create the control with the factory object.
        ::std::auto_ptr<TreeNode> pControl (mpControlFactory->CreateControl(this));//GetParentNode()));
        if (pControl.get() != NULL)
        {
            pControl->SetParentNode(this);
            mpControlContainer->AddControl(pControl);

            pNode = mpControlContainer->GetControl(1);
            FocusManager::Instance().RegisterDownLink(this, pNode->GetWindow());
            FocusManager::Instance().RegisterUpLink(pNode->GetWindow(), this);
        }
    }

    return pNode;
}

const TreeNode* TitledControl::GetConstControl (bool bCreate) const
{
    return const_cast<TitledControl*>(this)->GetControl(bCreate);
}

TitleBar* TitledControl::GetTitleBar (void)
{
    return static_cast<TitleBar*>(mpControlContainer->GetControl(0));
}

::com::sun::star::uno::Reference<
    ::com::sun::star::accessibility::XAccessible> TitledControl::CreateAccessibleObject (
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>& rxParent)
{
    return new ::accessibility::AccessibleTreeNode(
        *this,
        GetTitle(),
        GetTitle(),
        ::com::sun::star::accessibility::AccessibleRole::LIST_ITEM);
}

} } // end of namespace ::sd::toolpanel
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.11.38); FILE MERGED 2006/11/22 12:42:16 cl 1.11.38.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TitledControl.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 18:44:50 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#include "taskpane/TitledControl.hxx"

#include "AccessibleTreeNode.hxx"
#include "taskpane/ControlContainer.hxx"
#include "TaskPaneFocusManager.hxx"
#include "taskpane/TaskPaneControlFactory.hxx"

#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

namespace sd { namespace toolpanel {

TitledControl::TitledControl (
    TreeNode* pParent,
    ::std::auto_ptr<TreeNode> pControl,
    const String& rTitle,
    TitleBar::TitleBarType eType)
    : ::Window (pParent->GetWindow(), WB_TABSTOP),
      TreeNode(pParent),
      msTitle(rTitle),
      mbVisible(true),
      mpUserData(NULL),
      mpControlFactory(NULL),
      mbExpansionModeIsToggle(eType!=TitleBar::TBT_CONTROL_TITLE)
{
    if (pControl.get() != NULL)
    {
        mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
            new TitleBar (this, rTitle, eType, pControl->IsExpandable())));
        pControl->SetParentNode (this);
    }
    mpControlContainer->AddControl (pControl);

    FocusManager::Instance().RegisterDownLink(this, GetControl()->GetWindow());
    FocusManager::Instance().RegisterUpLink(GetControl()->GetWindow(), this);

    SetBackground (Wallpaper());

    GetTitleBar()->GetWindow()->Show ();
    GetTitleBar()->GetWindow()->AddEventListener (
        LINK(this,TitledControl,WindowEventListener));

    UpdateStates ();
}

TitledControl::TitledControl (
    TreeNode* pParent,
    ::std::auto_ptr<ControlFactory> pControlFactory,
    const String& rTitle,
    TitleBar::TitleBarType eType)
    : ::Window (pParent->GetWindow(), WB_TABSTOP),
      TreeNode(pParent),
      msTitle (rTitle),
      mbVisible (true),
      mpUserData (NULL),
      mpControlFactory(pControlFactory),
      mbExpansionModeIsToggle(eType!=TitleBar::TBT_CONTROL_TITLE)
{
    mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
        new TitleBar (this, rTitle, eType, true)));

    // The second control is created on demand, i.e. when GetControl(true)
    // is called the first time.

    SetBackground (Wallpaper());

    GetTitleBar()->GetWindow()->Show ();
    GetTitleBar()->GetWindow()->AddEventListener (
        LINK(this,TitledControl,WindowEventListener));

    UpdateStates ();
}

TitledControl::~TitledControl (void)
{
    GetTitleBar()->GetWindow()->RemoveEventListener (
        LINK(this,TitledControl,WindowEventListener));
}

Size TitledControl::GetPreferredSize (void)
{
    Size aPreferredSize;
    if (GetControl(false) != NULL)
    {
        aPreferredSize = GetControl()->GetPreferredSize();
        if ( ! IsExpanded())
            aPreferredSize.Height() = 0;
    }
    else
        aPreferredSize = Size (GetSizePixel().Width(), 0);
    if (aPreferredSize.Width() == 0)
        aPreferredSize.Width() = 300;
    aPreferredSize.Height() += GetTitleBar()->GetPreferredHeight(
        aPreferredSize.Width());

    return aPreferredSize;
}

sal_Int32 TitledControl::GetPreferredWidth (sal_Int32 nHeight)
{
    int nPreferredWidth = 0;
    if (GetControl(false) != NULL)
        nPreferredWidth = GetControl()->GetPreferredWidth(
            nHeight - GetTitleBar()->GetWindow()->GetSizePixel().Height());
    else
        nPreferredWidth = GetSizePixel().Width();
    if (nPreferredWidth == 0)
        nPreferredWidth = 300;

    return nPreferredWidth;
}

sal_Int32 TitledControl::GetPreferredHeight (sal_Int32 nWidth)
{
    int nPreferredHeight = 0;
    if (IsExpanded() && GetControl(false)!=NULL)
        nPreferredHeight = GetControl()->GetPreferredHeight(nWidth);
    nPreferredHeight += GetTitleBar()->GetPreferredHeight(nWidth);

    return nPreferredHeight;
}

bool TitledControl::IsResizable (void)
{
    return IsExpanded()
        && GetControl()->IsResizable();
}

::Window* TitledControl::GetWindow (void)
{
    return this;
}

void TitledControl::Resize (void)
{
    Size aWindowSize (GetOutputSizePixel());

    int nTitleBarHeight
        = GetTitleBar()->GetPreferredHeight(aWindowSize.Width());
    GetTitleBar()->GetWindow()->SetPosSizePixel (
        Point (0,0),
        Size (aWindowSize.Width(), nTitleBarHeight));

    TreeNode* pControl = GetControl(false);
    if (pControl != NULL
        && pControl->GetWindow() != NULL
        && pControl->GetWindow()->IsVisible())
    {
        pControl->GetWindow()->SetPosSizePixel (
            Point (0,nTitleBarHeight),
            Size (aWindowSize.Width(), aWindowSize.Height()-nTitleBarHeight));
    }
}

void TitledControl::GetFocus (void)
{
    ::Window::GetFocus();
    if (GetTitleBar() != NULL)
        GetTitleBar()->SetFocus (true);
}

void TitledControl::LoseFocus (void)
{
    ::Window::LoseFocus();
    if (GetTitleBar() != NULL)
        GetTitleBar()->SetFocus (false);
}

void TitledControl::KeyInput (const KeyEvent& rEvent)
{
    KeyCode nCode = rEvent.GetKeyCode();
    if (nCode == KEY_SPACE)
    {
        // Toggle the expansion state of the control (when toggling is
        // supported.)  The focus remains on this control.
        GetParentNode()->GetControlContainer().SetExpansionState (
            this,
            ControlContainer::ES_TOGGLE);
    }
    else if (nCode == KEY_RETURN)
    {
        // Return, also called enter, enters the control and puts the
        // focus to the first child.  If the control is not yet
        // expanded then do that first.
        GetParentNode()->GetControlContainer().SetExpansionState (
            this,
            ControlContainer::ES_EXPAND);

        if ( ! FocusManager::Instance().TransferFocus(this,nCode))
        {
            // When already expanded then put focus on first child.
            TreeNode* pControl = GetControl(false);
            if (pControl!=NULL && IsExpanded())
                if (pControl->GetWindow() != NULL)
                    pControl->GetWindow()->GrabFocus();
        }
    }
    else if (nCode == KEY_ESCAPE)
    {
        if ( ! FocusManager::Instance().TransferFocus(this,nCode))
            // Put focus to parent.
            GetParent()->GrabFocus();
    }
    else
        Window::KeyInput (rEvent);
}

const String& TitledControl::GetTitle (void) const
{
    return msTitle;
}

bool TitledControl::Expand (bool bExpanded)
{
    bool bExpansionStateChanged (false);

    if (IsExpandable())
    {
        if (GetTitleBar()->IsExpanded() != bExpanded)
            bExpansionStateChanged |= GetTitleBar()->Expand (bExpanded);
        // Get the control.  Use the bExpanded parameter as argument to
        // indicate that a control is created via its factory only when it
        // is to be expanded.  When it is collapsed this is not necessary.
        TreeNode* pControl = GetControl(bExpanded);
        if (pControl != NULL
            && GetControl()->IsExpanded() != bExpanded)
        {
            bExpansionStateChanged |= pControl->Expand (bExpanded);
        }
        if (bExpansionStateChanged)
            UpdateStates();
    }

    return bExpansionStateChanged;
}

bool TitledControl::IsExpandable (void) const
{
    const TreeNode* pControl = GetConstControl(false);
    if (pControl != NULL)
        return pControl->IsExpandable();
    else
        // When a control factory is given but the control has not yet been
        // created we assume that the control is expandable.
        return true;
}

bool TitledControl::IsExpanded (void) const
{
    const TreeNode* pControl = GetConstControl(false);
    if (pControl != NULL)
        return pControl->IsExpanded();
    else
        return false;
}

void TitledControl::SetUserData (void* pUserData)
{
    mpUserData = pUserData;
}

void* TitledControl::GetUserData (void) const
{
    return mpUserData;
}

bool TitledControl::IsShowing (void) const
{
    return mbVisible;
}

void TitledControl::Show (bool bVisible)
{
    if (mbVisible != bVisible)
    {
        mbVisible = bVisible;
        UpdateStates ();
    }
}

void TitledControl::UpdateStates (void)
{
    if (mbVisible)
        GetWindow()->Show();
    else
        GetWindow()->Hide();

    TreeNode* pControl = GetControl(false);
    if (pControl!=NULL  &&  pControl->GetWindow() != NULL)
        if (IsVisible() && IsExpanded())
            pControl->GetWindow()->Show();
        else
            pControl->GetWindow()->Hide();
}

IMPL_LINK(TitledControl, WindowEventListener,
    VclSimpleEvent*, pEvent)
{
    if (pEvent!=NULL && pEvent->ISA(VclWindowEvent))
    {
        VclWindowEvent* pWindowEvent = static_cast<VclWindowEvent*>(pEvent);
        switch (pWindowEvent->GetId())
        {
            case VCLEVENT_WINDOW_MOUSEBUTTONUP:
                // Toggle expansion.
                GetParentNode()->GetControlContainer().SetExpansionState (
                    this,
                    mbExpansionModeIsToggle ? ControlContainer::ES_TOGGLE
                                            : ControlContainer::ES_EXPAND);
                break;
        }
    }
    return 0;
}

TreeNode* TitledControl::GetControl (bool bCreate)
{
    TreeNode* pNode = mpControlContainer->GetControl(1);
    if (pNode==NULL && mpControlFactory.get()!=NULL && bCreate)
    {
        // We have to create the control with the factory object.
        ::std::auto_ptr<TreeNode> pControl (mpControlFactory->CreateControl(this));//GetParentNode()));
        if (pControl.get() != NULL)
        {
            pControl->SetParentNode(this);
            mpControlContainer->AddControl(pControl);

            pNode = mpControlContainer->GetControl(1);
            FocusManager::Instance().RegisterDownLink(this, pNode->GetWindow());
            FocusManager::Instance().RegisterUpLink(pNode->GetWindow(), this);
        }
    }

    return pNode;
}

const TreeNode* TitledControl::GetConstControl (bool bCreate) const
{
    return const_cast<TitledControl*>(this)->GetControl(bCreate);
}

TitleBar* TitledControl::GetTitleBar (void)
{
    return static_cast<TitleBar*>(mpControlContainer->GetControl(0));
}

::com::sun::star::uno::Reference<
    ::com::sun::star::accessibility::XAccessible> TitledControl::CreateAccessibleObject (
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>& )
{
    return new ::accessibility::AccessibleTreeNode(
        *this,
        GetTitle(),
        GetTitle(),
        ::com::sun::star::accessibility::AccessibleRole::LIST_ITEM);
}

} } // end of namespace ::sd::toolpanel
<|endoftext|>


<commit_before>#pragma once

#include "xson/object.hpp"
#include "xson/trace.hpp"
#include "xson/fast/decoder.hpp"

namespace xson {
namespace fson {

class decoder : public fast::decoder
{
public:

    decoder(std::istream& is) : fast::decoder(is)
    {}

    using fast::decoder::decode;

    void decode(double& d)
    {
        union{
            std::uint64_t i64;
            double d64;
        } i2d;
        decode(i2d.i64);
        d = i2d.d64;
    }

    void decode(bool& b)
    {
        std::uint8_t byte;
        decode(byte);
        b = static_cast<bool>(byte);
    }

    void decode(std::chrono::system_clock::time_point& tp)
    {
        using namespace std::chrono;
        std::int64_t i64;
        decode(i64);
        tp = system_clock::time_point{milliseconds{i64}};
    }

    void decode(object& parent)
    {
        std::uint8_t byte;
        decode(byte);

        while(byte != xson::eod && m_is)
        {
            xson::type type = static_cast<xson::type>(byte);
            std::string name;
            decode(name);
            auto& child = parent[name];

            std::int32_t i32;
            std::int64_t i64;
            double d;
            std::string str;
            bool b;
            std::chrono::system_clock::time_point tp;

            switch(type)
            {
                case type::object:
                case type::array:
                decode(child);
                child.type(type);
                break;

                case type::int32:
                decode(i32);
                child.value(i32);
                break;

                case type::int64:
                decode(i64);
                child.value(i64);
                break;

                case type::number:
                decode(d);
                child.value(d);
                break;

                case type::string:
                decode(str);
                child.value(str);
                break;

                case type::boolean:
                decode(b);
                child.value(b);
                break;

                case type::date:
                decode(tp);
                child.value(tp);
                break;

                case type::null:
                child.value(nullptr);
                break;
            }

            decode(byte);
        }
    }

};

inline std::istream& operator >> (std::istream& is, object& ob)
{
    decoder{is}.decode(ob);
    return is;
}

} // namespace fson
} // namespace xson
<commit_msg>Clean up<commit_after>#pragma once

#include "xson/object.hpp"
#include "xson/fast/decoder.hpp"

namespace xson {
namespace fson {

class decoder : public fast::decoder
{
public:

    decoder(std::istream& is) : fast::decoder(is)
    {}

    using fast::decoder::decode;

    void decode(double& d)
    {
        union{
            std::uint64_t i64;
            double d64;
        } i2d;
        decode(i2d.i64);
        d = i2d.d64;
    }

    void decode(bool& b)
    {
        std::uint8_t byte;
        decode(byte);
        b = static_cast<bool>(byte);
    }

    void decode(std::chrono::system_clock::time_point& tp)
    {
        using namespace std::chrono;
        std::int64_t i64;
        decode(i64);
        tp = system_clock::time_point{milliseconds{i64}};
    }

    void decode(object& parent)
    {
        std::uint8_t byte;
        decode(byte);

        while(byte != xson::eod && m_is)
        {
            xson::type type = static_cast<xson::type>(byte);
            std::string name;
            decode(name);
            auto& child = parent[name];

            std::int32_t i32;
            std::int64_t i64;
            double d;
            std::string str;
            bool b;
            std::chrono::system_clock::time_point tp;

            switch(type)
            {
                case type::object:
                case type::array:
                decode(child);
                child.type(type);
                break;

                case type::int32:
                decode(i32);
                child.value(i32);
                break;

                case type::int64:
                decode(i64);
                child.value(i64);
                break;

                case type::number:
                decode(d);
                child.value(d);
                break;

                case type::string:
                decode(str);
                child.value(str);
                break;

                case type::boolean:
                decode(b);
                child.value(b);
                break;

                case type::date:
                decode(tp);
                child.value(tp);
                break;

                case type::null:
                child.value(nullptr);
                break;
            }

            decode(byte);
        }
    }

};

inline std::istream& operator >> (std::istream& is, object& ob)
{
    decoder{is}.decode(ob);
    return is;
}

} // namespace fson
} // namespace xson
<|endoftext|>


<commit_before>#include "entity/entity_network_remote_peer.h"

#include "entity/entity_network_session.h"
#include "halley/entity/entity_factory.h"
#include "halley/entity/world.h"
#include "halley/support/logger.h"
#include "halley/utils/algorithm.h"

class NetworkComponent;
using namespace Halley;

EntityNetworkRemotePeer::EntityNetworkRemotePeer(EntityNetworkSession& parent, NetworkSession::PeerId peerId)
	: parent(&parent)
	, peerId(peerId)
{}

NetworkSession::PeerId EntityNetworkRemotePeer::getPeerId() const
{
	return peerId;
}

void EntityNetworkRemotePeer::sendEntities(Time t, gsl::span<const std::pair<EntityId, uint8_t>> entityIds, const EntityClientSharedData& clientData)
{
	Expects(isAlive());

	// Mark all as not alive
	for (auto& e: outboundEntities) {
		e.second.alive = false;
	}

	for (auto [entityId, ownerId]: entityIds) {
		if (ownerId == peerId) {
			// Don't send updates back to the owner
			continue;
		}

		const auto entity = parent->getWorld().getEntity(entityId);
		if (peerId == 0 || parent->isEntityInView(entity, clientData)) { // Always send to host
			if (const auto iter = outboundEntities.find(entityId); iter == outboundEntities.end()) {
				sendCreateEntity(entity);
			} else {
				sendUpdateEntity(t, iter->second, entity);
			}
		}
	}

	// Destroy dead entities
	for (auto& e: outboundEntities) {
		if (!e.second.alive) {
			sendDestroyEntity(e.second);
		}
	}
	std_ex::erase_if_value(outboundEntities, [](const OutboundEntity& e) { return !e.alive; });

	if (!hasSentData) {
		hasSentData = true;
		onFirstDataBatchSent();
	}
}

void EntityNetworkRemotePeer::receiveEntityPacket(NetworkSession::PeerId fromPeerId, EntityNetworkHeaderType type, InboundNetworkPacket packet)
{
	Expects(isAlive());

	EntityNetworkEntityHeader header;
	packet.extractHeader(header);
	const auto networkEntityId = header.entityId;

	if (type == EntityNetworkHeaderType::Create) {
		receiveCreateEntity(networkEntityId, packet.getBytes());
	} else if (type == EntityNetworkHeaderType::Update) {
		receiveUpdateEntity(networkEntityId, packet.getBytes());
	} else if (type == EntityNetworkHeaderType::Destroy) {
		receiveDestroyEntity(networkEntityId);
	}
}

void EntityNetworkRemotePeer::destroy()
{
	if (alive) {
		if (parent->hasWorld()) {
			auto& world = parent->getWorld();
			for (const auto& [k, v] : inboundEntities) {
				world.destroyEntity(v.worldId);
			}
		}

		inboundEntities.clear();
		alive = false;
	}
}

bool EntityNetworkRemotePeer::isAlive() const
{
	return alive;
}

uint16_t EntityNetworkRemotePeer::assignId()
{
	for (uint16_t i = 0; i < std::numeric_limits<uint16_t>::max() - 1; ++i) {
		const uint16_t id = i + nextId;
		if (!allocatedOutboundIds.contains(id)) {
			allocatedOutboundIds.insert(id);
			nextId = id + 1;
			return id;
		}
	}
	throw Exception("Unable to allocate network id for entity.", HalleyExceptions::Network);
}

void EntityNetworkRemotePeer::sendCreateEntity(EntityRef entity)
{
	OutboundEntity result;

	result.networkId = assignId();
	result.data = parent->getFactory().serializeEntity(entity, parent->getEntitySerializationOptions());

	auto deltaData = parent->getFactory().entityDataToPrefabDelta(result.data, entity.getPrefab(), parent->getEntityDeltaOptions());
	auto bytes = Serializer::toBytes(result.data, parent->getByteSerializationOptions());
	const auto size = send(EntityNetworkHeaderType::Create, result.networkId, std::move(bytes));

	outboundEntities[entity.getEntityId()] = std::move(result);

	//Logger::logDev("Sending create " + entity.getName() + ": " + toString(size) + " bytes to peer " + toString(static_cast<int>(peerId)));
	//Logger::logDev("Create:\n" + EntityData(deltaData).toYAML() + "\n");
}

void EntityNetworkRemotePeer::sendUpdateEntity(Time t, OutboundEntity& remote, EntityRef entity)
{
	remote.alive = true; // Important: mark it back alive
	remote.timeSinceSend += t;
	if (remote.timeSinceSend < parent->getMinSendInterval()) {
		return;
	}

	auto newData = parent->getFactory().serializeEntity(entity, parent->getEntitySerializationOptions());
	auto deltaData = EntityDataDelta(remote.data, newData, parent->getEntityDeltaOptions());

	if (deltaData.hasChange()) {
		parent->onPreSendDelta(deltaData);
	}

	if (deltaData.hasChange()) {
		remote.data = std::move(newData);
		remote.timeSinceSend = 0;

		auto bytes = Serializer::toBytes(deltaData, parent->getByteSerializationOptions());
		const auto size = send(EntityNetworkHeaderType::Update, remote.networkId, std::move(bytes));

		//Logger::logDev("Sending update " + entity.getName() + ": " + toString(size) + " bytes to peer " + toString(static_cast<int>(peerId)));
		//Logger::logDev("Update:\n" + EntityData(deltaData).toYAML() + "\n");
	}
}

void EntityNetworkRemotePeer::sendDestroyEntity(OutboundEntity& remote)
{
	allocatedOutboundIds.erase(remote.networkId);

	send(EntityNetworkHeaderType::Destroy, remote.networkId, Bytes());

	//Logger::logDev("Sending destroy entity to peer " + toString(static_cast<int>(peerId)));
}

size_t EntityNetworkRemotePeer::send(EntityNetworkHeaderType type, EntityNetworkId networkId, Bytes data)
{
	// TODO: compress them into one update?

	const size_t size = data.size() + 3;

	auto packet = OutboundNetworkPacket(std::move(data));
	packet.addHeader(EntityNetworkEntityHeader(networkId));
	packet.addHeader(EntityNetworkHeader(type));
	parent->getSession().sendToPeer(packet, peerId);

	return size;
}

void EntityNetworkRemotePeer::receiveCreateEntity(EntityNetworkId id, gsl::span<const gsl::byte> data)
{
	const auto iter = inboundEntities.find(id);
	if (iter != inboundEntities.end()) {
		Logger::logWarning("Entity with network id " + toString(static_cast<int>(id)) + " already exists from peer " + toString(static_cast<int>(peerId)));
		return;
	}

	auto delta = Deserializer::fromBytes<EntityDataDelta>(data, parent->getByteSerializationOptions());
	auto [entityData, prefab, prefabUUID] = parent->getFactory().prefabDeltaToEntityData(delta);
	auto [entity, parentUUID] = parent->getFactory().loadEntityDelta(delta, {});

	if (parentUUID) {
		if (auto parentEntity = parent->getWorld().findEntity(parentUUID.value()); parentEntity) {
			entity.setParent(parentEntity.value());
		}
	}

	//Logger::logDev("Instantiating from network:\n" + entityData.toYAML());

	entity.setupNetwork(peerId);

	InboundEntity remote;
	remote.data = std::move(entityData);
	remote.worldId = entity.getEntityId();

	inboundEntities[id] = std::move(remote);

	parent->onRemoteEntityCreated(entity, peerId);
}

void EntityNetworkRemotePeer::receiveUpdateEntity(EntityNetworkId id, gsl::span<const gsl::byte> data)
{
	const auto iter = inboundEntities.find(id);
	if (iter == inboundEntities.end()) {
		Logger::logWarning("Entity with network id " + toString(static_cast<int>(id)) + " not found from peer " + toString(static_cast<int>(peerId)));
		return;
	}
	auto& remote = iter->second;

	auto entity = parent->getWorld().getEntity(remote.worldId);
	if (!entity.isValid()) {
		Logger::logWarning("Entity with network id " + toString(static_cast<int>(id)) + " not alive in the world from peer " + toString(static_cast<int>(peerId)));
		return;
	}

	auto delta = Deserializer::fromBytes<EntityDataDelta>(data, parent->getByteSerializationOptions());

	parent->getFactory().updateEntity(entity, delta, static_cast<int>(EntitySerialization::Type::SaveData));
	remote.data.applyDelta(delta);
}

void EntityNetworkRemotePeer::receiveDestroyEntity(EntityNetworkId id)
{
	const auto iter = inboundEntities.find(id);
	if (iter == inboundEntities.end()) {
		Logger::logWarning("Entity with network id " + toString(static_cast<int>(id)) + " not found from peer " + toString(static_cast<int>(peerId)));
		return;
	}
	auto& remote = iter->second;

	parent->getWorld().destroyEntity(remote.worldId);

	inboundEntities.erase(id);
}

void EntityNetworkRemotePeer::onFirstDataBatchSent()
{
	if (parent->getSession().getType() == NetworkSessionType::Host) {
		auto packet = OutboundNetworkPacket(Bytes());
		packet.addHeader(EntityNetworkHeader(EntityNetworkHeaderType::ReadyToStart));
		parent->getSession().sendToPeer(packet, peerId);
	}
}
<commit_msg>Fix creating entities over the network<commit_after>#include "entity/entity_network_remote_peer.h"

#include "entity/entity_network_session.h"
#include "halley/entity/entity_factory.h"
#include "halley/entity/world.h"
#include "halley/support/logger.h"
#include "halley/utils/algorithm.h"

class NetworkComponent;
using namespace Halley;

EntityNetworkRemotePeer::EntityNetworkRemotePeer(EntityNetworkSession& parent, NetworkSession::PeerId peerId)
	: parent(&parent)
	, peerId(peerId)
{}

NetworkSession::PeerId EntityNetworkRemotePeer::getPeerId() const
{
	return peerId;
}

void EntityNetworkRemotePeer::sendEntities(Time t, gsl::span<const std::pair<EntityId, uint8_t>> entityIds, const EntityClientSharedData& clientData)
{
	Expects(isAlive());

	// Mark all as not alive
	for (auto& e: outboundEntities) {
		e.second.alive = false;
	}

	for (auto [entityId, ownerId]: entityIds) {
		if (ownerId == peerId) {
			// Don't send updates back to the owner
			continue;
		}

		const auto entity = parent->getWorld().getEntity(entityId);
		if (peerId == 0 || parent->isEntityInView(entity, clientData)) { // Always send to host
			if (const auto iter = outboundEntities.find(entityId); iter == outboundEntities.end()) {
				sendCreateEntity(entity);
			} else {
				sendUpdateEntity(t, iter->second, entity);
			}
		}
	}

	// Destroy dead entities
	for (auto& e: outboundEntities) {
		if (!e.second.alive) {
			sendDestroyEntity(e.second);
		}
	}
	std_ex::erase_if_value(outboundEntities, [](const OutboundEntity& e) { return !e.alive; });

	if (!hasSentData) {
		hasSentData = true;
		onFirstDataBatchSent();
	}
}

void EntityNetworkRemotePeer::receiveEntityPacket(NetworkSession::PeerId fromPeerId, EntityNetworkHeaderType type, InboundNetworkPacket packet)
{
	Expects(isAlive());

	EntityNetworkEntityHeader header;
	packet.extractHeader(header);
	const auto networkEntityId = header.entityId;

	if (type == EntityNetworkHeaderType::Create) {
		receiveCreateEntity(networkEntityId, packet.getBytes());
	} else if (type == EntityNetworkHeaderType::Update) {
		receiveUpdateEntity(networkEntityId, packet.getBytes());
	} else if (type == EntityNetworkHeaderType::Destroy) {
		receiveDestroyEntity(networkEntityId);
	}
}

void EntityNetworkRemotePeer::destroy()
{
	if (alive) {
		if (parent->hasWorld()) {
			auto& world = parent->getWorld();
			for (const auto& [k, v] : inboundEntities) {
				world.destroyEntity(v.worldId);
			}
		}

		inboundEntities.clear();
		alive = false;
	}
}

bool EntityNetworkRemotePeer::isAlive() const
{
	return alive;
}

uint16_t EntityNetworkRemotePeer::assignId()
{
	for (uint16_t i = 0; i < std::numeric_limits<uint16_t>::max() - 1; ++i) {
		const uint16_t id = i + nextId;
		if (!allocatedOutboundIds.contains(id)) {
			allocatedOutboundIds.insert(id);
			nextId = id + 1;
			return id;
		}
	}
	throw Exception("Unable to allocate network id for entity.", HalleyExceptions::Network);
}

void EntityNetworkRemotePeer::sendCreateEntity(EntityRef entity)
{
	OutboundEntity result;

	result.networkId = assignId();
	result.data = parent->getFactory().serializeEntity(entity, parent->getEntitySerializationOptions());

	auto deltaData = parent->getFactory().entityDataToPrefabDelta(result.data, entity.getPrefab(), parent->getEntityDeltaOptions());
	auto bytes = Serializer::toBytes(deltaData, parent->getByteSerializationOptions());
	const auto size = send(EntityNetworkHeaderType::Create, result.networkId, std::move(bytes));

	outboundEntities[entity.getEntityId()] = std::move(result);

	//Logger::logDev("Sending create " + entity.getName() + ": " + toString(size) + " bytes to peer " + toString(static_cast<int>(peerId)));
	//Logger::logDev("Create:\n" + EntityData(deltaData).toYAML() + "\n");
}

void EntityNetworkRemotePeer::sendUpdateEntity(Time t, OutboundEntity& remote, EntityRef entity)
{
	remote.alive = true; // Important: mark it back alive
	remote.timeSinceSend += t;
	if (remote.timeSinceSend < parent->getMinSendInterval()) {
		return;
	}

	auto newData = parent->getFactory().serializeEntity(entity, parent->getEntitySerializationOptions());
	auto deltaData = EntityDataDelta(remote.data, newData, parent->getEntityDeltaOptions());

	if (deltaData.hasChange()) {
		parent->onPreSendDelta(deltaData);
	}

	if (deltaData.hasChange()) {
		remote.data = std::move(newData);
		remote.timeSinceSend = 0;

		auto bytes = Serializer::toBytes(deltaData, parent->getByteSerializationOptions());
		const auto size = send(EntityNetworkHeaderType::Update, remote.networkId, std::move(bytes));

		//Logger::logDev("Sending update " + entity.getName() + ": " + toString(size) + " bytes to peer " + toString(static_cast<int>(peerId)));
		//Logger::logDev("Update:\n" + EntityData(deltaData).toYAML() + "\n");
	}
}

void EntityNetworkRemotePeer::sendDestroyEntity(OutboundEntity& remote)
{
	allocatedOutboundIds.erase(remote.networkId);

	send(EntityNetworkHeaderType::Destroy, remote.networkId, Bytes());

	//Logger::logDev("Sending destroy entity to peer " + toString(static_cast<int>(peerId)));
}

size_t EntityNetworkRemotePeer::send(EntityNetworkHeaderType type, EntityNetworkId networkId, Bytes data)
{
	// TODO: compress them into one update?

	const size_t size = data.size() + 3;

	auto packet = OutboundNetworkPacket(std::move(data));
	packet.addHeader(EntityNetworkEntityHeader(networkId));
	packet.addHeader(EntityNetworkHeader(type));
	parent->getSession().sendToPeer(packet, peerId);

	return size;
}

void EntityNetworkRemotePeer::receiveCreateEntity(EntityNetworkId id, gsl::span<const gsl::byte> data)
{
	const auto iter = inboundEntities.find(id);
	if (iter != inboundEntities.end()) {
		Logger::logWarning("Entity with network id " + toString(static_cast<int>(id)) + " already exists from peer " + toString(static_cast<int>(peerId)));
		return;
	}

	const auto delta = Deserializer::fromBytes<EntityDataDelta>(data, parent->getByteSerializationOptions());
	//Logger::logDev("Instantiating from network (" + toString(data.size()) + " bytes):\n\n" + EntityData(delta).toYAML());

	auto [entityData, prefab, prefabUUID] = parent->getFactory().prefabDeltaToEntityData(delta);
	auto [entity, parentUUID] = parent->getFactory().loadEntityDelta(delta, {});

	if (parentUUID) {
		if (auto parentEntity = parent->getWorld().findEntity(parentUUID.value()); parentEntity) {
			entity.setParent(parentEntity.value());
		}
	}

	entity.setupNetwork(peerId);

	InboundEntity remote;
	remote.data = std::move(entityData);
	remote.worldId = entity.getEntityId();

	inboundEntities[id] = std::move(remote);

	parent->onRemoteEntityCreated(entity, peerId);
}

void EntityNetworkRemotePeer::receiveUpdateEntity(EntityNetworkId id, gsl::span<const gsl::byte> data)
{
	const auto iter = inboundEntities.find(id);
	if (iter == inboundEntities.end()) {
		Logger::logWarning("Entity with network id " + toString(static_cast<int>(id)) + " not found from peer " + toString(static_cast<int>(peerId)));
		return;
	}
	auto& remote = iter->second;

	auto entity = parent->getWorld().getEntity(remote.worldId);
	if (!entity.isValid()) {
		Logger::logWarning("Entity with network id " + toString(static_cast<int>(id)) + " not alive in the world from peer " + toString(static_cast<int>(peerId)));
		return;
	}

	auto delta = Deserializer::fromBytes<EntityDataDelta>(data, parent->getByteSerializationOptions());

	parent->getFactory().updateEntity(entity, delta, static_cast<int>(EntitySerialization::Type::SaveData));
	remote.data.applyDelta(delta);
}

void EntityNetworkRemotePeer::receiveDestroyEntity(EntityNetworkId id)
{
	const auto iter = inboundEntities.find(id);
	if (iter == inboundEntities.end()) {
		Logger::logWarning("Entity with network id " + toString(static_cast<int>(id)) + " not found from peer " + toString(static_cast<int>(peerId)));
		return;
	}
	auto& remote = iter->second;

	parent->getWorld().destroyEntity(remote.worldId);

	inboundEntities.erase(id);
}

void EntityNetworkRemotePeer::onFirstDataBatchSent()
{
	if (parent->getSession().getType() == NetworkSessionType::Host) {
		auto packet = OutboundNetworkPacket(Bytes());
		packet.addHeader(EntityNetworkHeader(EntityNetworkHeaderType::ReadyToStart));
		parent->getSession().sendToPeer(packet, peerId);
	}
}
<|endoftext|>


<commit_before>#include <ros/ros.h>
// PCL specific includes
#include <sensor_msgs/PointCloud2.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>

ros::Publisher pub;
// How to avoid hard-coding a topic name?

void cloud_cb(const sensor_msgs::PointCloud2ConstPtr& input) {
  // Create a container for the data.
  sensor_msgs::PointCloud2 output;

  /* Do data processing here...*/
  output = *input; // modify input

  // Publish the data.
  pub.publish(output);
}

int main (int argc, char** argv) {
  // Initialize ROS
  ros::init (argc, argv, "my_pcl_tutorial");
  ros::NodeHandle nh;

  // Create a ROS subscriber for the input point cloud
  // when topic /input is incoming, cloud_cb callback is called
  ros::Subscriber sub = nh.subscribe("assemble_cloud", 1, cloud_cb);

  // Create a ROS publisher for the output point cloud
  // A node has both of publisheres and subscribers.
  pub = nh.advertise<sensor_msgs::PointCloud2>("output", 1);

  // Spin
  ros::spin();
}
<commit_msg>Deleted one file.<commit_after><|endoftext|>


<commit_before>#ifndef __sitksimpletransformix_cxx_
#define __sitksimpletransformix_cxx_

#include "sitkSimpleTransformix.h"
#include "sitkSimpleTransformix.hxx"

namespace itk {
  namespace simple {

SimpleTransformix
::SimpleTransformix( void )
{
  // Register this class with SimpleITK
  this->m_MemberFactory.reset( new detail::MemberFunctionFactory< MemberFunctionType >( this ) );
  this->m_MemberFactory->RegisterMemberFunctions< BasicPixelIDTypeList, 2 >();
  this->m_MemberFactory->RegisterMemberFunctions< BasicPixelIDTypeList, 3 >();

  #ifdef SITK_4D_IMAGES
    m_MemberFactory->RegisterMemberFunctions< BasicPixelIDTypeList, 4 >();
  #endif

  this->SetInputImage( Image() );

  this->ComputeSpatialJacobianOff();
  this->ComputeDeterminantOfSpatialJacobianOff();
  this->ComputeDeformationFieldOff();

  this->m_OutputDirectory             = ".";
  this->m_LogFileName                 = std::string();

  this->LogToFileOff();
  this->LogToConsoleOff();

  m_ResultImage = Image();
}

SimpleTransformix
::~SimpleTransformix( void )
{
}

const std::string
SimpleTransformix
::GetName( void )
{
  const std::string name = std::string( "SimpleTransformix" );
  return name;
}

SimpleTransformix::Self&
SimpleTransformix
::SetInputImage( const Image& inputImage )
{
  this->m_InputImage = inputImage;
  return *this;
}

Image&
SimpleTransformix
::GetInputImage( void )
{
  return this->m_InputImage;
}

SimpleTransformix::Self&
SimpleTransformix
::SetInputPointSetFileName( const std::string inputPointSetFileName )
{
  this->m_InputPointSetFileName = inputPointSetFileName;
  return *this;
}

std::string
SimpleTransformix
::GetInputPointSetFileName( void )
{
  return this->m_InputPointSetFileName;
}

SimpleTransformix::Self&
SimpleTransformix
::RemoveInputPointSetFileName( void )
{
  this->m_InputPointSetFileName = std::string();
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::SetComputeSpatialJacobian( const bool computeSpatialJacobian )
{
  this->m_ComputeSpatialJacobian = computeSpatialJacobian;
  return *this;
}

bool
SimpleTransformix
::GetComputeSpatialJacobian( void )
{
  return this->m_ComputeSpatialJacobian;
}

SimpleTransformix::Self&
SimpleTransformix
::ComputeSpatialJacobianOn( void )
{
  this->SetComputeSpatialJacobian( true );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::ComputeSpatialJacobianOff( void )
{
  this->SetComputeSpatialJacobian( false );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::SetComputeDeterminantOfSpatialJacobian( const bool computeDeterminantOfSpatialJacobian )
{
  this->m_ComputeSpatialJacobian = computeDeterminantOfSpatialJacobian;
  return *this;
}

bool
SimpleTransformix
::GetComputeDeterminantOfSpatialJacobian( void )
{
  return this->m_ComputeDeterminantOfSpatialJacobian;
}

SimpleTransformix::Self&
SimpleTransformix
::ComputeDeterminantOfSpatialJacobianOn( void )
{
  this->SetComputeDeterminantOfSpatialJacobian( true );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::ComputeDeterminantOfSpatialJacobianOff( void )
{
  this->SetComputeDeterminantOfSpatialJacobian( false );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::SetComputeDeformationField( const bool computeDeformationField )
{
  this->m_ComputeDeformationField = computeDeformationField;
  return *this;
}

bool
SimpleTransformix
::GetComputeDeformationField( void )
{
  return this->m_ComputeDeformationField;
}

SimpleTransformix::Self&
SimpleTransformix
::ComputeDeformationFieldOn( void )
{
  this->SetComputeDeformationField( true );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::ComputeDeformationFieldOff( void )
{
  this->SetComputeDeformationField( false );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::SetOutputDirectory( const std::string outputDirectory )
{
  this->m_OutputDirectory = outputDirectory;
  return *this;
}

std::string
SimpleTransformix
::GetOutputDirectory( void )
{
  return this->m_OutputDirectory;
}

SimpleTransformix::Self&
SimpleTransformix
::RemoveOutputDirectory( void )
{
  this->m_OutputDirectory = std::string();
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::SetLogFileName( std::string logFileName )
{
  this->m_LogFileName = logFileName;
  return *this;
}

std::string
SimpleTransformix
::GetLogFileName( void )
{
  return this->m_LogFileName;
}

SimpleTransformix::Self&
SimpleTransformix
::RemoveLogFileName( void )
{
  this->m_LogFileName = std::string();
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::SetLogToFile( bool logToFile )
{
  this->m_LogToFile = logToFile;
  return *this;
}

bool
SimpleTransformix
::GetLogToFile( void )
{
  return this->m_LogToFile;
}

SimpleTransformix::Self&
SimpleTransformix
::LogToFileOn()
{
  this->SetLogToFile( true );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::LogToFileOff()
{
  this->SetLogToFile( false );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::SetLogToConsole( bool logToConsole )
{
  this->m_LogToConsole = logToConsole;
  return *this;
}

bool
SimpleTransformix
::GetLogToConsole( void )
{
  return this->m_LogToConsole;
}

SimpleTransformix::Self&
SimpleTransformix
::LogToConsoleOn()
{
  this->SetLogToConsole( true );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::LogToConsoleOff()
{
  this->SetLogToConsole( false );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::SetTransformParameterMap( const ParameterMapVectorType parameterMapVector )
{
  this->m_TransformParameterMapVector = parameterMapVector;
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::SetTransformParameterMap( const ParameterMapType parameterMap )
{
  ParameterMapVectorType parameterMapVector;
  parameterMapVector.push_back( parameterMap );
  this->SetTransformParameterMap( parameterMapVector );
  return *this;
}

SimpleTransformix::ParameterMapVectorType
SimpleTransformix
::GetTransformParameterMap( void )
{
  return this->m_TransformParameterMapVector;
}

SimpleTransformix::ParameterMapType
SimpleTransformix
::ReadParameterFile( const std::string filename )
{
  ParameterFileParserPointer parser = ParameterFileParserType::New();
  parser->SetParameterFileName( filename );
  try
  {
    parser->ReadParameterFile();
  }
  catch( itk::ExceptionObject &e )
  {
    std::cout << e.what() << std::endl;
  }

  return parser->GetParameterMap();
}

SimpleTransformix::Self&
SimpleTransformix
::WriteParameterFile( const ParameterMapType parameterMap, const std::string parameterFileName )
{
  ParameterObjectPointer parameterObject = ParameterObjectType::New();
  parameterObject->WriteParameterFile( parameterMap, parameterFileName );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::PrettyPrint( void )
{
  this->PrettyPrint( this->GetTransformParameterMap() );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::PrettyPrint( const ParameterMapType parameterMap )
{
  ParameterMapVectorType parameterMapVector = ParameterMapVectorType( 1 );
  parameterMapVector[ 0 ] = parameterMap;
  this->PrettyPrint( parameterMapVector );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::PrettyPrint( const ParameterMapVectorType parameterMapList )
{
  for( unsigned int i = 0; i < parameterMapList.size(); ++i )
  {
    std::cout << "ParameterMap " << i << ": " << std::endl;
    ParameterMapConstIterator parameterMapIterator = parameterMapList[ i ].begin();
    ParameterMapConstIterator parameterMapIteratorEnd = parameterMapList[ i ].end();
    while( parameterMapIterator != parameterMapIteratorEnd )
    {
      std::cout << "  (" << parameterMapIterator->first;
      ParameterValueVectorType parameterMapValueVector = parameterMapIterator->second;

      for(unsigned int j = 0; j < parameterMapValueVector.size(); ++j)
      {
        std::stringstream stream( parameterMapValueVector[ j ] );
        float number;
        stream >> number;
        if( stream.fail() ) {
           std::cout << " \"" << parameterMapValueVector[ j ] << "\"";
        }
        else
        {
          std::cout << " " << number;
        }
      }

      std::cout << ")" << std::endl;
      parameterMapIterator++;
    }
  }

  return *this;
}

Image
SimpleTransformix
::Execute( void )
{
  const PixelIDValueEnum InputImagePixelEnum = this->m_InputImage.GetPixelID();
  const unsigned int InputImageDimension = this->m_InputImage.GetDimension();

  if( this->m_MemberFactory->HasMemberFunction( InputImagePixelEnum, InputImageDimension ) )
  {
    try {
      return this->m_MemberFactory->GetMemberFunction( InputImagePixelEnum, InputImageDimension )();
    } catch( itk::ExceptionObject &e ) {
      sitkExceptionMacro( << e );
    }
  }

  sitkExceptionMacro( << "SimpleTransformix does not support the combination of image type \""
                      << GetPixelIDValueAsString( InputImagePixelEnum ) << "\" ("
                      << GetPixelIDValueAsElastixParameter( InputImagePixelEnum ) << ") and dimension "
                      << InputImageDimension << "." );
}

Image
SimpleTransformix
::GetResultImage( void )
{
  if( this->IsEmpty( this->m_ResultImage ) )
  {
    sitkExceptionMacro( "No result image was found. Has transformix run yet?" )
  }

  return this->m_ResultImage;
}

bool
SimpleTransformix
::IsEmpty( const Image& image )
{
  bool isEmpty = image.GetWidth() == 0 && image.GetHeight() == 0;
  return isEmpty;
}

/**
 * Procedural interface
 */

Image
Transformix( const Image& inputImage, const SimpleTransformix::ParameterMapType parameterMap, const bool logToConsole, const std::string outputDirectory )
{
  SimpleTransformix::ParameterMapVectorType parameterMapVector;
  parameterMapVector.push_back( parameterMap );
  return Transformix( inputImage, parameterMapVector, logToConsole, outputDirectory );
}

Image
Transformix( const Image& inputImage, const SimpleTransformix::ParameterMapVectorType parameterMapVector, const bool logToConsole, const std::string outputDirectory )
{
  SimpleTransformix stfx;
  stfx.SetInputImage( inputImage );
  stfx.SetTransformParameterMap( parameterMapVector );
  stfx.SetOutputDirectory( outputDirectory );
  stfx.LogToFileOn();
  stfx.SetLogToConsole( logToConsole );

  return stfx.Execute();
}

} // end namespace simple
} // end namespace itk

#endif // __sitksimpletransformix_cxx_<commit_msg>BUG: Fix setting ComputeDeterminantOfSpatialJacobian<commit_after>#ifndef __sitksimpletransformix_cxx_
#define __sitksimpletransformix_cxx_

#include "sitkSimpleTransformix.h"
#include "sitkSimpleTransformix.hxx"

namespace itk {
  namespace simple {

SimpleTransformix
::SimpleTransformix( void )
{
  // Register this class with SimpleITK
  this->m_MemberFactory.reset( new detail::MemberFunctionFactory< MemberFunctionType >( this ) );
  this->m_MemberFactory->RegisterMemberFunctions< BasicPixelIDTypeList, 2 >();
  this->m_MemberFactory->RegisterMemberFunctions< BasicPixelIDTypeList, 3 >();

  #ifdef SITK_4D_IMAGES
    m_MemberFactory->RegisterMemberFunctions< BasicPixelIDTypeList, 4 >();
  #endif

  this->SetInputImage( Image() );

  this->ComputeSpatialJacobianOff();
  this->ComputeDeterminantOfSpatialJacobianOff();
  this->ComputeDeformationFieldOff();

  this->SetOutputDirectory( "" );
  this->SetLogFileName( "" );

  this->LogToFileOff();
  this->LogToConsoleOff();

  this->m_ResultImage = Image();
}

SimpleTransformix
::~SimpleTransformix( void )
{
}

const std::string
SimpleTransformix
::GetName( void )
{
  const std::string name = std::string( "SimpleTransformix" );
  return name;
}

SimpleTransformix::Self&
SimpleTransformix
::SetInputImage( const Image& inputImage )
{
  this->m_InputImage = inputImage;
  return *this;
}

Image&
SimpleTransformix
::GetInputImage( void )
{
  return this->m_InputImage;
}

SimpleTransformix::Self&
SimpleTransformix
::SetInputPointSetFileName( const std::string inputPointSetFileName )
{
  this->m_InputPointSetFileName = inputPointSetFileName;
  return *this;
}

std::string
SimpleTransformix
::GetInputPointSetFileName( void )
{
  return this->m_InputPointSetFileName;
}

SimpleTransformix::Self&
SimpleTransformix
::RemoveInputPointSetFileName( void )
{
  this->m_InputPointSetFileName = std::string();
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::SetComputeSpatialJacobian( const bool computeSpatialJacobian )
{
  this->m_ComputeSpatialJacobian = computeSpatialJacobian;
  return *this;
}

bool
SimpleTransformix
::GetComputeSpatialJacobian( void )
{
  return this->m_ComputeSpatialJacobian;
}

SimpleTransformix::Self&
SimpleTransformix
::ComputeSpatialJacobianOn( void )
{
  this->SetComputeSpatialJacobian( true );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::ComputeSpatialJacobianOff( void )
{
  this->SetComputeSpatialJacobian( false );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::SetComputeDeterminantOfSpatialJacobian( const bool computeDeterminantOfSpatialJacobian )
{
  this->m_ComputeDeterminantOfSpatialJacobian = computeDeterminantOfSpatialJacobian;
  return *this;
}

bool
SimpleTransformix
::GetComputeDeterminantOfSpatialJacobian( void )
{
  return this->m_ComputeDeterminantOfSpatialJacobian;
}

SimpleTransformix::Self&
SimpleTransformix
::ComputeDeterminantOfSpatialJacobianOn( void )
{
  this->SetComputeDeterminantOfSpatialJacobian( true );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::ComputeDeterminantOfSpatialJacobianOff( void )
{
  this->SetComputeDeterminantOfSpatialJacobian( false );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::SetComputeDeformationField( const bool computeDeformationField )
{
  this->m_ComputeDeformationField = computeDeformationField;
  return *this;
}

bool
SimpleTransformix
::GetComputeDeformationField( void )
{
  return this->m_ComputeDeformationField;
}

SimpleTransformix::Self&
SimpleTransformix
::ComputeDeformationFieldOn( void )
{
  this->SetComputeDeformationField( true );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::ComputeDeformationFieldOff( void )
{
  this->SetComputeDeformationField( false );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::SetOutputDirectory( const std::string outputDirectory )
{
  this->m_OutputDirectory = outputDirectory;
  return *this;
}

std::string
SimpleTransformix
::GetOutputDirectory( void )
{
  return this->m_OutputDirectory;
}

SimpleTransformix::Self&
SimpleTransformix
::RemoveOutputDirectory( void )
{
  this->m_OutputDirectory = std::string();
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::SetLogFileName( std::string logFileName )
{
  this->m_LogFileName = logFileName;
  return *this;
}

std::string
SimpleTransformix
::GetLogFileName( void )
{
  return this->m_LogFileName;
}

SimpleTransformix::Self&
SimpleTransformix
::RemoveLogFileName( void )
{
  this->m_LogFileName = std::string();
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::SetLogToFile( bool logToFile )
{
  this->m_LogToFile = logToFile;
  return *this;
}

bool
SimpleTransformix
::GetLogToFile( void )
{
  return this->m_LogToFile;
}

SimpleTransformix::Self&
SimpleTransformix
::LogToFileOn()
{
  this->SetLogToFile( true );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::LogToFileOff()
{
  this->SetLogToFile( false );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::SetLogToConsole( bool logToConsole )
{
  this->m_LogToConsole = logToConsole;
  return *this;
}

bool
SimpleTransformix
::GetLogToConsole( void )
{
  return this->m_LogToConsole;
}

SimpleTransformix::Self&
SimpleTransformix
::LogToConsoleOn()
{
  this->SetLogToConsole( true );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::LogToConsoleOff()
{
  this->SetLogToConsole( false );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::SetTransformParameterMap( const ParameterMapVectorType parameterMapVector )
{
  this->m_TransformParameterMapVector = parameterMapVector;
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::SetTransformParameterMap( const ParameterMapType parameterMap )
{
  ParameterMapVectorType parameterMapVector;
  parameterMapVector.push_back( parameterMap );
  this->SetTransformParameterMap( parameterMapVector );
  return *this;
}

SimpleTransformix::ParameterMapVectorType
SimpleTransformix
::GetTransformParameterMap( void )
{
  return this->m_TransformParameterMapVector;
}

SimpleTransformix::ParameterMapType
SimpleTransformix
::ReadParameterFile( const std::string filename )
{
  ParameterFileParserPointer parser = ParameterFileParserType::New();
  parser->SetParameterFileName( filename );
  try
  {
    parser->ReadParameterFile();
  }
  catch( itk::ExceptionObject &e )
  {
    std::cout << e.what() << std::endl;
  }

  return parser->GetParameterMap();
}

SimpleTransformix::Self&
SimpleTransformix
::WriteParameterFile( const ParameterMapType parameterMap, const std::string parameterFileName )
{
  ParameterObjectPointer parameterObject = ParameterObjectType::New();
  parameterObject->WriteParameterFile( parameterMap, parameterFileName );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::PrettyPrint( void )
{
  this->PrettyPrint( this->GetTransformParameterMap() );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::PrettyPrint( const ParameterMapType parameterMap )
{
  ParameterMapVectorType parameterMapVector = ParameterMapVectorType( 1 );
  parameterMapVector[ 0 ] = parameterMap;
  this->PrettyPrint( parameterMapVector );
  return *this;
}

SimpleTransformix::Self&
SimpleTransformix
::PrettyPrint( const ParameterMapVectorType parameterMapList )
{
  for( unsigned int i = 0; i < parameterMapList.size(); ++i )
  {
    std::cout << "ParameterMap " << i << ": " << std::endl;
    ParameterMapConstIterator parameterMapIterator = parameterMapList[ i ].begin();
    ParameterMapConstIterator parameterMapIteratorEnd = parameterMapList[ i ].end();
    while( parameterMapIterator != parameterMapIteratorEnd )
    {
      std::cout << "  (" << parameterMapIterator->first;
      ParameterValueVectorType parameterMapValueVector = parameterMapIterator->second;

      for(unsigned int j = 0; j < parameterMapValueVector.size(); ++j)
      {
        std::stringstream stream( parameterMapValueVector[ j ] );
        float number;
        stream >> number;
        if( stream.fail() ) {
           std::cout << " \"" << parameterMapValueVector[ j ] << "\"";
        }
        else
        {
          std::cout << " " << number;
        }
      }

      std::cout << ")" << std::endl;
      parameterMapIterator++;
    }
  }

  return *this;
}

Image
SimpleTransformix
::Execute( void )
{
  const PixelIDValueEnum InputImagePixelEnum = this->m_InputImage.GetPixelID();
  const unsigned int InputImageDimension = this->m_InputImage.GetDimension();

  if( this->m_MemberFactory->HasMemberFunction( InputImagePixelEnum, InputImageDimension ) )
  {
    try {
      return this->m_MemberFactory->GetMemberFunction( InputImagePixelEnum, InputImageDimension )();
    } catch( itk::ExceptionObject &e ) {
      sitkExceptionMacro( << e );
    }
  }

  sitkExceptionMacro( << "SimpleTransformix does not support the combination of image type \""
                      << GetPixelIDValueAsString( InputImagePixelEnum ) << "\" ("
                      << GetPixelIDValueAsElastixParameter( InputImagePixelEnum ) << ") and dimension "
                      << InputImageDimension << "." );
}

Image
SimpleTransformix
::GetResultImage( void )
{
  if( this->IsEmpty( this->m_ResultImage ) )
  {
    sitkExceptionMacro( "No result image was found. Has transformix run yet?" )
  }

  return this->m_ResultImage;
}

bool
SimpleTransformix
::IsEmpty( const Image& image )
{
  bool isEmpty = image.GetWidth() == 0 && image.GetHeight() == 0;
  return isEmpty;
}

/**
 * Procedural interface
 */

Image
Transformix( const Image& inputImage, const SimpleTransformix::ParameterMapType parameterMap, const bool logToConsole, const std::string outputDirectory )
{
  SimpleTransformix::ParameterMapVectorType parameterMapVector;
  parameterMapVector.push_back( parameterMap );
  return Transformix( inputImage, parameterMapVector, logToConsole, outputDirectory );
}

Image
Transformix( const Image& inputImage, const SimpleTransformix::ParameterMapVectorType parameterMapVector, const bool logToConsole, const std::string outputDirectory )
{
  SimpleTransformix stfx;
  stfx.SetInputImage( inputImage );
  stfx.SetTransformParameterMap( parameterMapVector );
  stfx.SetOutputDirectory( outputDirectory );
  stfx.LogToFileOn();
  stfx.SetLogToConsole( logToConsole );

  return stfx.Execute();
}

} // end namespace simple
} // end namespace itk

#endif // __sitksimpletransformix_cxx_<|endoftext|>