<commit_before>#include "stdafx.h"
#include "Engineer.h"
#include "ActorManager.h"
#include "ObjectTable.h"
#include "Physics.h"

Engineer::Engineer()
{
	m_ClassName = CharacterClass::ENGINEER;
}

Engineer::~Engineer()
{
}

bool Engineer::UseSkill( ClassSkill skill, int id, const D3DXVECTOR3& direction )
{
	switch ( skill )
	{
	case ClassSkill::PUSH:
		return SkillPush( id, direction );
	case ClassSkill::OCCUPY:
		return SkillOccupy( id, direction );
	case ClassSkill::DESTROY:
		return SkillDestroy( id, direction );
	case ClassSkill::SHARE_FUEL:
		return SkillShareFuel( id, direction );
	case ClassSkill::GATHER:
		return SkillGather( id, direction );
	case ClassSkill::SET_SHELTER:
		return SkillShelter( id, direction );
	case ClassSkill::SET_DISPENSER:
		return SkillDispenser( id, direction );
	default:
		break;
	}

	return false;
}

bool Engineer::SkillGather( int id, const D3DXVECTOR3& direction )
{
	if ( m_GlobalCooldown > 0.0f || m_CooldownTable[static_cast<int>(ClassSkill::GATHER)] > 0.0f )
		return false;

	Character* character = GObjectTable->GetActorManager()->GetCharacterList().at( id );
	D3DXVECTOR3 viewDirection = character->GetViewDirection( direction );
	D3DXVECTOR3	startPoint = character->GetTransform()->GetPosition();

	D3DXVECTOR3 tmppos = GObjectTable->GetActorManager()->GetResourceDebrisList().at(0)->GetTransform()->GetPosition();
	printf_s( "debirs no 0 pos is : %f %f %f\n", tmppos.x, tmppos.y, tmppos.z );
	// 안맞으면 false 리턴
	if ( !DebrisInRay( viewDirection, startPoint ) )
	{
		return false;
	}

	// 캐릭터 자원 증가
	character->GetClassComponent()->IncreaseResource( DEBRIS_TO_RESOURCE_AMOUNT );

	// 조심해!! 지금은 일단 리스트에서 삭제함.
	// 혹시 추후에 데브리가 리젠되는 식으로 기획이 변경되면 이부분을 수정할 것

	// 레이에 맞은 데브리 삭제
	GObjectTable->GetActorManager()->RemoveResourceDebris( GObjectTable->GetActorManager()->GetGatheredDebris() );

	SetCooldown( ClassSkill::GATHER );

	// broadcast
	GObjectTable->GetActorManager()->BroadcastCharacterChange( static_cast<int>( id ), ChangeType::RESOURCE_GATHER );

	return true;
}

bool Engineer::SkillShelter( int id, const D3DXVECTOR3& direction )
{
	return false;
}

bool Engineer::SkillDispenser( int id, const D3DXVECTOR3& direction )
{
	// 쿨탐 체크
	if ( m_GlobalCooldown > 0.0f || m_CooldownTable[static_cast<int>( ClassSkill::SET_DISPENSER )] > 0.0f )
		return false;

	if ( m_Resource < DISPENSER_PRICE )
		return false;

	ISS* iss = GObjectTable->GetActorManager()->GetIss();

	Character* skillUserCharacter = GObjectTable->GetCharacter( id );
	assert( skillUserCharacter );

	D3DXVECTOR3 viewDirection = skillUserCharacter->GetViewDirection( direction );
	D3DXVec3Normalize( &viewDirection, &viewDirection );
	D3DXVECTOR3	startPoint = skillUserCharacter->GetTransform()->GetPosition();

	// 스킬 사용 방향에 있는 모듈 검색
	ISSModuleName targetModuleName = iss->ModuleOnRay( viewDirection, startPoint );

	if ( targetModuleName == ISSModuleName::NO_MODULE )
		return false;

	ISSModule* targetModule = iss->GetModule( targetModuleName );
	float distance = std::numeric_limits<float>::infinity();
	Physics::IntersectionCheckRayBox( nullptr, &distance, nullptr, viewDirection, startPoint, targetModule->GetCollisionBox() );

	// 모듈까지의 거리 체크 - 멀면 return false;
	if ( distance > SKILL_RANGE )
		return false;

	// 그렇지 않으면 바운딩 박스와 ray의 교점 위치에
	// ray 방향의 반대 방향을 정면으로 설정
	// actorManager에 등록
	D3DXVECTOR3 minePosition = startPoint + viewDirection * distance;
	GObjectTable->GetActorManager()->InstallDispenser( minePosition, -viewDirection, skillUserCharacter->GetTeam(), id );

	// 설치 완료
	printf_s( "dispenser installed \n" );

	return true;
}

bool Engineer::DebrisInRay( const D3DXVECTOR3 &viewDirection, const D3DXVECTOR3 &startPoint )
{
	float currentDistance = std::numeric_limits<float>::infinity( );
	int	debrisNumber = -1;

	auto& debrisList = GObjectTable->GetActorManager( )->GetResourceDebrisList( );
	for ( int i = 0; i < RESOURCE_DEBRIS_NUMBER; ++i )
	{
		// 조심해!! 지금은 일단 리스트에서 삭제함.
		// 혹시 추후에 데브리가 리젠되는 식으로 기획이 변경되면 이부분을 수정할 것
		if ( debrisList[i] == nullptr ) continue;

		// intersection 확인
		float tempDistance = std::numeric_limits<float>::infinity( );
		const CollisionBox* box = debrisList[i]->GetCollisionBox( );
		if ( Physics::IntersectionCheckRayBox( nullptr, &tempDistance, nullptr, viewDirection, startPoint, box ) )
		{
			// 스킬 사용 범위가 정해지면 그것과 비교해서 더 먼 애는 제외
			// 더 가까운 애로 교체
			if ( tempDistance < currentDistance && tempDistance < SKILL_RANGE )
			{
				currentDistance = tempDistance;
				debrisNumber = i;
			}
		}
	}

	GObjectTable->GetActorManager( )->SetGatheredDebris( debrisNumber );
	return ( debrisNumber == -1 ) ? false : true;

}

void Engineer::DoPeriodWork( float dTime )
{
	// 스킬이나 캐릭터 상태 변화 필요한 부분 ㄱㄱ
	UNREFERENCED_PARAMETER( dTime );
}
<commit_msg>데브리 삭제관련 버그 수정<commit_after>#include "stdafx.h"
#include "Engineer.h"
#include "ActorManager.h"
#include "ObjectTable.h"
#include "Physics.h"

Engineer::Engineer()
{
	m_ClassName = CharacterClass::ENGINEER;
}

Engineer::~Engineer()
{
}

bool Engineer::UseSkill( ClassSkill skill, int id, const D3DXVECTOR3& direction )
{
	switch ( skill )
	{
	case ClassSkill::PUSH:
		return SkillPush( id, direction );
	case ClassSkill::OCCUPY:
		return SkillOccupy( id, direction );
	case ClassSkill::DESTROY:
		return SkillDestroy( id, direction );
	case ClassSkill::SHARE_FUEL:
		return SkillShareFuel( id, direction );
	case ClassSkill::GATHER:
		return SkillGather( id, direction );
	case ClassSkill::SET_SHELTER:
		return SkillShelter( id, direction );
	case ClassSkill::SET_DISPENSER:
		return SkillDispenser( id, direction );
	default:
		break;
	}

	return false;
}

bool Engineer::SkillGather( int id, const D3DXVECTOR3& direction )
{
	if ( m_GlobalCooldown > 0.0f || m_CooldownTable[static_cast<int>(ClassSkill::GATHER)] > 0.0f )
		return false;

	Character* character = GObjectTable->GetActorManager()->GetCharacterList().at( id );
	D3DXVECTOR3 viewDirection = character->GetViewDirection( direction );
	D3DXVECTOR3	startPoint = character->GetTransform()->GetPosition();

	D3DXVECTOR3 tmppos = GObjectTable->GetActorManager()->GetResourceDebrisList().at(0)->GetTransform()->GetPosition();
	printf_s( "debirs no 0 pos is : %f %f %f\n", tmppos.x, tmppos.y, tmppos.z );
	// 안맞으면 false 리턴
	if ( !DebrisInRay( viewDirection, startPoint ) )
	{
		return false;
	}

	// 캐릭터 자원 증가
	character->GetClassComponent()->IncreaseResource( DEBRIS_TO_RESOURCE_AMOUNT );

	// 조심해!! 지금은 일단 리스트에서 삭제함.
	// 혹시 추후에 데브리가 리젠되는 식으로 기획이 변경되면 이부분을 수정할 것

	// 레이에 맞은 데브리 삭제
	//GObjectTable->GetActorManager()->RemoveResourceDebris( GObjectTable->GetActorManager()->GetGatheredDebris() );

	SetCooldown( ClassSkill::GATHER );

	// broadcast
	GObjectTable->GetActorManager()->BroadcastCharacterChange( static_cast<int>( id ), ChangeType::RESOURCE_GATHER );

	return true;
}

bool Engineer::SkillShelter( int id, const D3DXVECTOR3& direction )
{
	return false;
}

bool Engineer::SkillDispenser( int id, const D3DXVECTOR3& direction )
{
	// 쿨탐 체크
	if ( m_GlobalCooldown > 0.0f || m_CooldownTable[static_cast<int>( ClassSkill::SET_DISPENSER )] > 0.0f )
		return false;

	if ( m_Resource < DISPENSER_PRICE )
		return false;

	ISS* iss = GObjectTable->GetActorManager()->GetIss();

	Character* skillUserCharacter = GObjectTable->GetCharacter( id );
	assert( skillUserCharacter );

	D3DXVECTOR3 viewDirection = skillUserCharacter->GetViewDirection( direction );
	D3DXVec3Normalize( &viewDirection, &viewDirection );
	D3DXVECTOR3	startPoint = skillUserCharacter->GetTransform()->GetPosition();

	// 스킬 사용 방향에 있는 모듈 검색
	ISSModuleName targetModuleName = iss->ModuleOnRay( viewDirection, startPoint );

	if ( targetModuleName == ISSModuleName::NO_MODULE )
		return false;

	ISSModule* targetModule = iss->GetModule( targetModuleName );
	float distance = std::numeric_limits<float>::infinity();
	Physics::IntersectionCheckRayBox( nullptr, &distance, nullptr, viewDirection, startPoint, targetModule->GetCollisionBox() );

	// 모듈까지의 거리 체크 - 멀면 return false;
	if ( distance > SKILL_RANGE )
		return false;

	// 그렇지 않으면 바운딩 박스와 ray의 교점 위치에
	// ray 방향의 반대 방향을 정면으로 설정
	// actorManager에 등록
	D3DXVECTOR3 minePosition = startPoint + viewDirection * distance;
	GObjectTable->GetActorManager()->InstallDispenser( minePosition, -viewDirection, skillUserCharacter->GetTeam(), id );

	// 설치 완료
	printf_s( "dispenser installed \n" );

	return true;
}

bool Engineer::DebrisInRay( const D3DXVECTOR3 &viewDirection, const D3DXVECTOR3 &startPoint )
{
	float currentDistance = std::numeric_limits<float>::infinity( );
	int	debrisNumber = -1;

	auto& debrisList = GObjectTable->GetActorManager( )->GetResourceDebrisList( );
	for ( int i = 0; i < RESOURCE_DEBRIS_NUMBER; ++i )
	{
		// 조심해!! 지금은 일단 리스트에서 삭제함.
		// 혹시 추후에 데브리가 리젠되는 식으로 기획이 변경되면 이부분을 수정할 것
		if ( debrisList[i] == nullptr ) continue;

		// intersection 확인
		float tempDistance = std::numeric_limits<float>::infinity( );
		const CollisionBox* box = debrisList[i]->GetCollisionBox( );
		if ( Physics::IntersectionCheckRayBox( nullptr, &tempDistance, nullptr, viewDirection, startPoint, box ) )
		{
			// 스킬 사용 범위가 정해지면 그것과 비교해서 더 먼 애는 제외
			// 더 가까운 애로 교체
			if ( tempDistance < currentDistance && tempDistance < SKILL_RANGE )
			{
				currentDistance = tempDistance;
				debrisNumber = i;
			}
		}
	}

	GObjectTable->GetActorManager( )->SetGatheredDebris( debrisNumber );
	return ( debrisNumber == -1 ) ? false : true;

}

void Engineer::DoPeriodWork( float dTime )
{
	// 스킬이나 캐릭터 상태 변화 필요한 부분 ㄱㄱ
	UNREFERENCED_PARAMETER( dTime );
}
<|endoftext|>


<commit_before>/*************************************************************************
 * Copyright (c) 2013 eProsima. All rights reserved.
 *
 * This copy of FastCdr is licensed to you under the terms described in the
 * EPROSIMARTPS_LIBRARY_LICENSE file included in this distribution.
 *
 *************************************************************************/

/*
 * StatelessTest.cpp
 *
 *  Created on: Feb 26, 2014
 *      Author: Gonzalo Rodriguez Canosa
 *      email:  gonzalorodriguez@eprosima.com
 *      		grcanosa@gmail.com
 */

#include <stdio.h>
#include <string>
#include <iostream>
#include <iomanip>
#include <bitset>
#include <cstdint>
//

#include "eprosimartps/Participant.h"
#include "eprosimartps/dds/Publisher.h"
#include "eprosimartps/dds/Subscriber.h"
#include "eprosimartps/dds/DomainParticipant.h"
#include "eprosimartps/common/colors.h"
#include "eprosimartps/dds/ParameterList.h"
#include "eprosimartps/utils/RTPSLog.h"
#include "eprosimartps/dds/DDSTopicDataType.h"
#include "eprosimartps/reader/RTPSListener.h"

using namespace eprosima;
using namespace dds;
using namespace rtps;
using namespace std;

#define IPTEST1 23
#define IPTEST2 25
#define IPTEST3 27
#define IPTESTWIN 11

#define WR 1 //Writer 1, Reader 2

#if defined(__LITTLE_ENDIAN__)
const Endianness_t DEFAULT_ENDIAN = LITTLEEND;
#elif defined (__BIG_ENDIAN__)
const Endianness_t DEFAULT_ENDIAN = BIGEND;
#endif

#if defined(_WIN32)
#define COPYSTR strcpy_s
#else
#define COPYSTR strcpy
#endif

typedef struct TestType{
	char name[6]; //KEY
	int32_t value;
	double price;
	TestType()
	{
		value = -1;
		price = 0;
		strcpy(name,"UNDEF");
	}
	void print()
	{
		cout << "Name: ";
		printf("%s",name);
		cout << " |Value: "<< value;
		cout << " |Price: "<< price;
		cout << endl;
	}
}TestType;

class TestTypeDataType:public DDSTopicDataType
{
public:
	TestTypeDataType()
{
		m_topicDataTypeName = "TestType";
		m_typeSize = 6+4+sizeof(double);
		m_isGetKeyDefined = true;
};
	~TestTypeDataType(){};
	bool serialize(void*data,SerializedPayload_t* payload);
	bool deserialize(SerializedPayload_t* payload,void * data);
	bool getKey(void*data,InstanceHandle_t* ihandle);
};

//Funciones de serializacion y deserializacion para el ejemplo
bool TestTypeDataType::serialize(void*data,SerializedPayload_t* payload)
{
	payload->length = sizeof(TestType);
	payload->encapsulation = CDR_LE;
	if(payload->data !=NULL)
		free(payload->data);
	payload->data = (octet*)malloc(payload->length);
	memcpy(payload->data,data,payload->length);
	return true;
}

bool TestTypeDataType::deserialize(SerializedPayload_t* payload,void * data)
{
	//cout << "Deserializando length: " << payload->length << endl;
	memcpy(data,payload->data,payload->length);
	return true;
}

bool TestTypeDataType::getKey(void*data,InstanceHandle_t* handle)
{
	TestType* tp = (TestType*)data;
	handle->value[0]  = 0;
	handle->value[1]  = 0;
	handle->value[2]  = 0;
	handle->value[3]  = 5; //length of string in CDR BE
	handle->value[4]  = tp->name[0];
	handle->value[5]  = tp->name[1];
	handle->value[6]  = tp->name[2];
	handle->value[7]  = tp->name[3];
	handle->value[8]  = tp->name[4];
	for(uint8_t i=9;i<16;i++)
		handle->value[i]  = 0;
	return true;
}

class TestTypeListener: public RTPSListener{
public:
	TestTypeListener(){};
	~TestTypeListener(){};
	void newMessageCallback()
	{
		cout <<"New Message"<<endl;
	}
};

int main(int argc, char** argv)
{
	RTPSLog::setVerbosity(RTPSLog::EPROSIMA_INFO_VERBOSITY_LEVEL);
	int type;
	if(argc > 1)
	{
		RTPSLog::Info << "Parsing arguments: " << argv[1] << endl;
		RTPSLog::printInfo();
		if(strcmp(argv[1],"1")==0)
			type = 1;
		else if(strcmp(argv[1],"2")==0)
			type = 2;
		else if(strcmp(argv[1],"3")==0)
			type = 3;
	}
	else
		type = WR;

	TestTypeDataType TestTypeData;
	DomainParticipant::registerType((DDSTopicDataType*)&TestTypeData);

	ParticipantParams_t PParam;
	PParam.defaultSendPort = 10042;
	PParam.m_useSimpleParticipantDiscovery = false;
	Participant* p = DomainParticipant::createParticipant(PParam);

	switch(type)
	{
	case 1:
	{
		WriterParams_t WParam;
		WParam.historySize = 20;
		WParam.topicKind = WITH_KEY;
		WParam.topicDataType = "TestType";
		WParam.topicName = "Test_topic";
		Publisher* pub1 = DomainParticipant::createPublisher(p,WParam);
		Publisher* pub2 = DomainParticipant::createPublisher(p,WParam);
		ReaderParams_t Rparam;
		Rparam.historySize = 50;
		Rparam.topicDataType = std::string("TestType");
		Rparam.topicName = std::string("Test_topic");
		Rparam.topicKind = NO_KEY;
		Locator_t loc;
		loc.kind = 1;
		loc.port = 10469;
		Rparam.unicastLocatorList.push_back(loc); //Listen in the 10469 port
		Subscriber* sub = DomainParticipant::createSubscriber(p,Rparam);

		loc.set_IP4_address(192,168,1,IPTEST2);
		pub1->addReaderLocator(loc,true);
		pub2->addReaderLocator(loc,true);
		TestType tp1,tp2,tp_in;
		COPYSTR(tp1.name,"Obje1");
		COPYSTR(tp2.name,"Obje2");
		tp1.value = 0;
		tp1.price = 1.3;
		tp2.value = 0;
		tp2.price = -1.3;
		int n;
		cout << "Enter number to start: ";
		cin >> n;
		for(uint i = 0;i<10;i++)
		{
			tp1.value++;
			tp1.price *= (i+1);
			tp2.value++;
			tp2.price *= (i+1);
			pub1->write((void*)&tp1);
			pub2->write((void*)&tp2);
			if(pub1->getHistory_n() >= 0.8*WParam.historySize)
				pub1->removeMinSeqChange();
			if(pub2->getHistory_n() >= 0.8*WParam.historySize)
				pub2->removeMinSeqChange();
			if(i==8)
			{
				pub1->dispose((void*)&tp1);
				pub1->unregister((void*)&tp1);
				pub2->dispose((void*)&tp2);
				pub2->unregister((void*)&tp2);
				COPYSTR(tp1.name,"Obje3");
				tp1.value = 0;
				tp1.price = 1.5;
				COPYSTR(tp2.name,"Obje4");
				tp2.value = 0;
				tp2.price = 1.5;
			}
			while(sub->readMinSeqUnreadCache((void*)&tp_in))
			{
				tp_in.print();
			}
			if(sub->getHistory_n() >= 0.8*Rparam.historySize)
			{
				cout << "Taking all from subscriber" <<endl;
				std::vector<void*> data_vec;
				sub->takeAllCache(&data_vec);
				for(unsigned int i=0;i<data_vec.size();i++)
					((TestType*)data_vec[i])->print();
				cout << "Subscriber History has now: " << sub->getHistory_n() << " elements "<<endl;
			}
		}
		break;
	}
	case 2:
	{
		ReaderParams_t Rparam;
		Rparam.historySize = 50;
		Rparam.topicDataType = std::string("TestType");
		Rparam.topicName = std::string("Test_topic");
		Rparam.topicKind = WITH_KEY;
		Locator_t loc;
		loc.kind = 1;
		loc.port = 10469;
		Rparam.unicastLocatorList.push_back(loc); //Listen in port 10469
		Subscriber* sub = DomainParticipant::createSubscriber(p,Rparam);
		TestTypeListener listener;
		sub->assignListener((RTPSListener*)&listener);
		WriterParams_t WParam;
		WParam.historySize = 50;
		WParam.topicKind = NO_KEY;
		WParam.topicDataType = "TestType";
		WParam.topicName = "Test_topic";
		Publisher* pub1 = DomainParticipant::createPublisher(p,WParam);
		loc.set_IP4_address(192,168,1,IPTEST1);
		pub1->addReaderLocator(loc,false);
		while(1)
		{
			cout << "Blocking until new message arrives " << endl;
			sub->blockUntilNewMessage();
			cout << "After new message block " << sub->getHistory_n() << endl;
			TestType tp;
			while(sub->readMinSeqUnreadCache((void*)&tp))
			{
				tp.print();
				pub1->write((void*)&tp);
			}
			cout << "Read: " << sub->getReadElements_n() <<" from History: "<<sub->getHistory_n()<< endl;
			if(sub->getHistory_n() >= 0.5*Rparam.historySize)
			{
				cout << "Taking all" <<endl;
				std::vector<void*> data_vec;
				sub->takeAllCache(&data_vec);
				for(unsigned int i=0;i<data_vec.size();i++)
					((TestType*)data_vec[i])->print();
				cout << "History has now: " << sub->getHistory_n() << " elements ";
				cout << " and is FUll?: " << sub->isHistoryFull() << endl;
			}
		}
		break;
	}
	default:
		break;
	}

	cout << "Enter numer "<< endl;
	int n;
	cin >> n;
	DomainParticipant::stopAll();

	return 0;

}

<commit_msg>stateTess change<commit_after>/*************************************************************************
 * Copyright (c) 2013 eProsima. All rights reserved.
 *
 * This copy of FastCdr is licensed to you under the terms described in the
 * EPROSIMARTPS_LIBRARY_LICENSE file included in this distribution.
 *
 *************************************************************************/

/*
 * StatelessTest.cpp
 *
 *  Created on: Feb 26, 2014
 *      Author: Gonzalo Rodriguez Canosa
 *      email:  gonzalorodriguez@eprosima.com
 *      		grcanosa@gmail.com
 */

#include <stdio.h>
#include <string>
#include <iostream>
#include <iomanip>
#include <bitset>
#include <cstdint>
//

#include "eprosimartps/Participant.h"
#include "eprosimartps/dds/Publisher.h"
#include "eprosimartps/dds/Subscriber.h"
#include "eprosimartps/dds/DomainParticipant.h"
#include "eprosimartps/common/colors.h"
#include "eprosimartps/dds/ParameterList.h"
#include "eprosimartps/utils/RTPSLog.h"
#include "eprosimartps/dds/DDSTopicDataType.h"
#include "eprosimartps/reader/RTPSListener.h"

using namespace eprosima;
using namespace dds;
using namespace rtps;
using namespace std;

#define IPTEST1 23
#define IPTEST2 25
#define IPTEST3 27
#define IPTESTWIN 11

#define WR 1 //Writer 1, Reader 2

#if defined(__LITTLE_ENDIAN__)
const Endianness_t DEFAULT_ENDIAN = LITTLEEND;
#elif defined (__BIG_ENDIAN__)
const Endianness_t DEFAULT_ENDIAN = BIGEND;
#endif

#if defined(_WIN32)
#define COPYSTR strcpy_s
#else
#define COPYSTR strcpy
#endif

typedef struct TestType{
	char name[6]; //KEY
	int32_t value;
	double price;
	TestType()
	{
		value = -1;
		price = 0;
		strcpy(name,"UNDEF");
	}
	void print()
	{
		cout << "Name: ";
		printf("%s",name);
		cout << " |Value: "<< value;
		cout << " |Price: "<< price;
		cout << endl;
	}
}TestType;

class TestTypeDataType:public DDSTopicDataType
{
public:
	TestTypeDataType()
{
		m_topicDataTypeName = "TestType";
		m_typeSize = 6+4+sizeof(double);
		m_isGetKeyDefined = true;
};
	~TestTypeDataType(){};
	bool serialize(void*data,SerializedPayload_t* payload);
	bool deserialize(SerializedPayload_t* payload,void * data);
	bool getKey(void*data,InstanceHandle_t* ihandle);
};

//Funciones de serializacion y deserializacion para el ejemplo
bool TestTypeDataType::serialize(void*data,SerializedPayload_t* payload)
{
	payload->length = sizeof(TestType);
	payload->encapsulation = CDR_LE;
	if(payload->data !=NULL)
		free(payload->data);
	payload->data = (octet*)malloc(payload->length);
	memcpy(payload->data,data,payload->length);
	return true;
}

bool TestTypeDataType::deserialize(SerializedPayload_t* payload,void * data)
{
	//cout << "Deserializando length: " << payload->length << endl;
	memcpy(data,payload->data,payload->length);
	return true;
}

bool TestTypeDataType::getKey(void*data,InstanceHandle_t* handle)
{
	TestType* tp = (TestType*)data;
	handle->value[0]  = 0;
	handle->value[1]  = 0;
	handle->value[2]  = 0;
	handle->value[3]  = 5; //length of string in CDR BE
	handle->value[4]  = tp->name[0];
	handle->value[5]  = tp->name[1];
	handle->value[6]  = tp->name[2];
	handle->value[7]  = tp->name[3];
	handle->value[8]  = tp->name[4];
	for(uint8_t i=9;i<16;i++)
		handle->value[i]  = 0;
	return true;
}

class TestTypeListener: public RTPSListener{
public:
	TestTypeListener(){};
	~TestTypeListener(){};
	void newMessageCallback()
	{
		cout <<"New Message"<<endl;
	}
};

int main(int argc, char** argv)
{
	RTPSLog::setVerbosity(RTPSLog::EPROSIMA_INFO_VERBOSITY_LEVEL);
	int type;
	if(argc > 1)
	{
		RTPSLog::Info << "Parsing arguments: " << argv[1] << endl;
		RTPSLog::printInfo();
		if(strcmp(argv[1],"1")==0)
			type = 1;
		else if(strcmp(argv[1],"2")==0)
			type = 2;
		else if(strcmp(argv[1],"3")==0)
			type = 3;
	}
	else
		type = WR;

	TestTypeDataType TestTypeData;
	DomainParticipant::registerType((DDSTopicDataType*)&TestTypeData);

	ParticipantParams_t PParam;
	PParam.defaultSendPort = 10042;
	PParam.m_useSimpleParticipantDiscovery = false;
	Participant* p = DomainParticipant::createParticipant(PParam);

	switch(type)
	{
	case 1:
	{
		WriterParams_t WParam;
		WParam.historySize = 20;
		WParam.topicKind = WITH_KEY;
		WParam.topicDataType = "TestType";
		WParam.topicName = "Test_topic";
		Publisher* pub1 = DomainParticipant::createPublisher(p,WParam);
		Publisher* pub2 = DomainParticipant::createPublisher(p,WParam);
		ReaderParams_t Rparam;
		Rparam.historySize = 50;
		Rparam.topicDataType = std::string("TestType");
		Rparam.topicName = std::string("Test_topic");
		Rparam.topicKind = NO_KEY;
		Locator_t loc;
		loc.kind = 1;
		loc.port = 10469;
		Rparam.unicastLocatorList.push_back(loc); //Listen in the 10469 port
		Subscriber* sub = DomainParticipant::createSubscriber(p,Rparam);

		loc.set_IP4_address(192,168,1,IPTEST2);
		pub1->addReaderLocator(loc,true);
		pub2->addReaderLocator(loc,true);
		TestType tp1,tp2,tp_in;
		COPYSTR(tp1.name,"Obje1");
		COPYSTR(tp2.name,"Obje2");
		tp1.value = 0;
		tp1.price = 1.3;
		tp2.value = 0;
		tp2.price = -1.3;
		int n;
		cout << "Enter number to start: ";
		cin >> n;
		for(uint i = 0;i<10;i++)
		{
			tp1.value++;
			tp1.price *= (i+1);
			tp2.value++;
			tp2.price *= (i+1);
			pub1->write((void*)&tp1);
			pub2->write((void*)&tp2);
			if(pub1->getHistory_n() >= 0.8*WParam.historySize)
				pub1->removeMinSeqChange();
			if(pub2->getHistory_n() >= 0.8*WParam.historySize)
				pub2->removeMinSeqChange();
			if(i==8)
			{
				pub1->dispose((void*)&tp1);
				pub1->unregister((void*)&tp1);
				pub2->dispose((void*)&tp2);
				pub2->unregister((void*)&tp2);
				COPYSTR(tp1.name,"Obje3");
				tp1.value = 0;
				tp1.price = 1.5;
				COPYSTR(tp2.name,"Obje4");
				tp2.value = 0;
				tp2.price = 1.5;
			}
			if(sub->getHistory_n() >= 0.8*Rparam.historySize)
			{
				cout << "Taking all from subscriber" <<endl;
				std::vector<void*> data_vec;
				sub->takeAllCache(&data_vec);
				for(unsigned int i=0;i<data_vec.size();i++)
					((TestType*)data_vec[i])->print();
				cout << "Subscriber History has now: " << sub->getHistory_n() << " elements "<<endl;
			}
		}
		cout << "Sleeping 2 seconds"<<endl;
		sleep(3);
		while(sub->readMinSeqUnreadCache((void*)&tp_in))
		{
			tp_in.print();
		}
		break;
	}
	case 2:
	{
		ReaderParams_t Rparam;
		Rparam.historySize = 50;
		Rparam.topicDataType = std::string("TestType");
		Rparam.topicName = std::string("Test_topic");
		Rparam.topicKind = WITH_KEY;
		Locator_t loc;
		loc.kind = 1;
		loc.port = 10469;
		Rparam.unicastLocatorList.push_back(loc); //Listen in port 10469
		Subscriber* sub = DomainParticipant::createSubscriber(p,Rparam);
		TestTypeListener listener;
		sub->assignListener((RTPSListener*)&listener);
		WriterParams_t WParam;
		WParam.historySize = 50;
		WParam.topicKind = NO_KEY;
		WParam.topicDataType = "TestType";
		WParam.topicName = "Test_topic";
		Publisher* pub1 = DomainParticipant::createPublisher(p,WParam);
		loc.set_IP4_address(192,168,1,IPTEST1);
		pub1->addReaderLocator(loc,false);
		while(1)
		{
			cout << "Blocking until new message arrives " << endl;
			sub->blockUntilNewMessage();
			cout << "After new message block " << sub->getHistory_n() << endl;
			TestType tp;
			while(sub->readMinSeqUnreadCache((void*)&tp))
			{
				tp.print();
				pub1->write((void*)&tp);
			}
			cout << "Read: " << sub->getReadElements_n() <<" from History: "<<sub->getHistory_n()<< endl;
			if(sub->getHistory_n() >= 0.5*Rparam.historySize)
			{
				cout << "Taking all" <<endl;
				std::vector<void*> data_vec;
				sub->takeAllCache(&data_vec);
				for(unsigned int i=0;i<data_vec.size();i++)
					((TestType*)data_vec[i])->print();
				cout << "History has now: " << sub->getHistory_n() << " elements ";
				cout << " and is FUll?: " << sub->isHistoryFull() << endl;
			}
		}
		break;
	}
	default:
		break;
	}

	cout << "Enter numer "<< endl;
	int n;
	cin >> n;
	DomainParticipant::stopAll();

	return 0;

}

<|endoftext|>


<commit_before>/*
    irceditaccountwidget.cpp - IRC Account Widget

    Copyright (c) 2005      by Tommi Rantala  <tommi.rantala@cs.helsinki.fi>
    Copyright (c) 2003      by Olivier Goffart  <ogoffart @ kde.org>
    Copyright (c) 2003      by Jason Keirstead  <jason@keirstead.org>
    Kopete    (c) 2003-2005 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include "irceditaccountwidget.h"

#include "ircaccount.h"
#include "ircusercontact.h"
#include "ircprotocol.h"
#include "kcodecaction.h"

#include "kircengine.h"

#include "kopetepasswordwidget.h"

#include <kmessagebox.h>
#include <klocale.h>
#include <klistview.h>
#include <kdebug.h>
#include <kextsock.h>
#include <kconfig.h>
#include <kglobal.h>
#include <kcharsets.h>

#include <qlabel.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <qcheckbox.h>
#include <qconnection.h>
#include <qvalidator.h>
#include <qcombobox.h>
#include <qlistbox.h>
#include <qlineedit.h>

IRCEditAccountWidget::IRCEditAccountWidget(IRCProtocol *proto, IRCAccount *ident, QWidget *parent, const char * )
	  : IRCEditAccountBase(parent), KopeteEditAccountWidget(ident)
{
	mProtocol = proto;

	// iso latin 1
	int currentCodec = 4;

	if( account() )
	{
		QString nickName = account()->mySelf()->nickName();
		QString serverInfo = account()->accountId();

		mNickName->setText( nickName );
		mAltNickname->setText( account()->altNick() );
		mUserName->setText( account()->userName() );
		m_realNameLineEdit->setText( account()->realName() );

		partMessage->setText( account()->defaultPart() );
		quitMessage->setText( account()->defaultQuit() );
		if( account()->codec() )
			currentCodec = account()->codec()->mibEnum();

		mPasswordWidget->load ( &account()->password() );

		preferSSL->setChecked(account()->configGroup()->readBoolEntry("PreferSSL"));
		autoShowServerWindow->setChecked( account()->configGroup()->readBoolEntry("AutoShowServerWindow") );
		autoConnect->setChecked( static_cast<Kopete::Account*>(account())->excludeConnect() );

		KConfigGroup *config = account()->configGroup();

		serverNotices->setCurrentItem( config->readNumEntry( "ServerNotices", IRCAccount::ServerWindow ) - 1 );
		serverMessages->setCurrentItem( config->readNumEntry( "ServerMessages", IRCAccount::ServerWindow ) - 1 );
		informationReplies->setCurrentItem( config->readNumEntry( "InformationReplies", IRCAccount::ActiveWindow ) - 1 );
		errorMessages->setCurrentItem( config->readNumEntry( "ErrorMessages", IRCAccount::ActiveWindow ) - 1 );

		account()->setMessageDestinations( serverNotices->currentItem(), serverMessages->currentItem(),
		informationReplies->currentItem(), errorMessages->currentItem()
						     );

		QStringList cmds = account()->connectCommands();
		for( QStringList::Iterator i = cmds.begin(); i != cmds.end(); ++i )
			new QListViewItem( commandList, *i );

		const QMap< QString, QString > replies = account()->customCtcpReplies();
		for( QMap< QString, QString >::ConstIterator it = replies.begin(); it != replies.end(); ++it )
			new QListViewItem( ctcpList, it.key(), it.data() );
	}

	mUserName->setValidator( new QRegExpValidator( QString::fromLatin1("^[^\\s]*$"), mUserName ) );
	mNickName->setValidator( new QRegExpValidator( QString::fromLatin1("^[^#+&][^\\s]*$"), mNickName ) );
	mAltNickname->setValidator( new QRegExpValidator( QString::fromLatin1("^[^#+&][^\\s]*$"), mAltNickname ) );

	charset->insertStringList( KCodecAction::supportedEncodings() );

	for (int i = 0; i < charset->count(); ++i) {
		QString encoding = KGlobal::charsets()->encodingForName(charset->text(i));

		if (KGlobal::charsets()->codecForName(encoding)->mibEnum() == currentCodec) {
			charset->setCurrentItem( i );
			break;
		}
	}

	connect( commandList, SIGNAL( contextMenu( KListView *, QListViewItem *, const QPoint & ) ),
		this, SLOT( slotCommandContextMenu( KListView *, QListViewItem *, const QPoint & ) ) );

	connect( ctcpList, SIGNAL( contextMenu( KListView *, QListViewItem *, const QPoint & ) ),
		this, SLOT( slotCtcpContextMenu( KListView *, QListViewItem *, const QPoint & ) ) );

	connect( addButton, SIGNAL( clicked() ), this, SLOT( slotAddCommand() ) );
	connect( editButton, SIGNAL( clicked() ), this, SLOT(slotEditNetworks() ) );
	connect( addReply, SIGNAL( clicked() ), this, SLOT( slotAddCtcp() ) );

	connect( network, SIGNAL( activated( const QString & ) ),
		this, SLOT( slotUpdateNetworkDescription( const QString &) ) );

	connect( IRCProtocol::protocol(), SIGNAL( networkConfigUpdated( const QString & ) ),
		this, SLOT( slotUpdateNetworks( const QString & ) ) );

	slotUpdateNetworks( QString::null );
}

IRCEditAccountWidget::~IRCEditAccountWidget()
{
}

IRCAccount *IRCEditAccountWidget::account ()
{
	return dynamic_cast<IRCAccount *>(KopeteEditAccountWidget::account () );
}

void IRCEditAccountWidget::slotUpdateNetworks( const QString & selectedNetwork )
{
	network->clear();

	uint i = 0;
	QStringList keys;
	for( QDictIterator<IRCNetwork> it( IRCProtocol::protocol()->networks() ); it.current(); ++it )
		keys.append( it.currentKey() );

	keys.sort();

	QStringList::Iterator end = keys.end();
	for( QStringList::Iterator it = keys.begin(); it != end; ++it )
	{
		IRCNetwork * current = IRCProtocol::protocol()->networks()[*it];
		network->insertItem( current->name );
		if ( ( account() && account()->networkName() == current->name ) || current->name == selectedNetwork )
		{
			network->setCurrentItem( i );
			description->setText( current->description );
		}
		++i;
	}
}

void IRCEditAccountWidget::slotEditNetworks()
{
	IRCProtocol::protocol()->editNetworks( network->currentText() );
}

void IRCEditAccountWidget::slotUpdateNetworkDescription( const QString &network )
{
	description->setText(
		IRCProtocol::protocol()->networks()[ network ]->description
	);
}

void IRCEditAccountWidget::slotCommandContextMenu( KListView *, QListViewItem *item, const QPoint &p )
{
	QPopupMenu popup;
	popup.insertItem( i18n("Remove Command"), 1 );
	if( popup.exec( p ) == 1 )
		delete item;
}

void IRCEditAccountWidget::slotCtcpContextMenu( KListView *, QListViewItem *item, const QPoint &p )
{
	QPopupMenu popup;
	popup.insertItem( i18n("Remove CTCP Reply"), 1 );
	if( popup.exec( p ) == 1 )
		delete item;
}

void IRCEditAccountWidget::slotAddCommand()
{
    if ( !commandEdit->text().isEmpty() )
    {
	new QListViewItem( commandList, commandEdit->text() );
	commandEdit->clear();
    }
}

void IRCEditAccountWidget::slotAddCtcp()
{
    if (  !newCTCP->text().isEmpty() && !newReply->text().isEmpty() )
    {
	new QListViewItem( ctcpList, newCTCP->text(), newReply->text() );
	newCTCP->clear();
	newReply->clear();
    }
}

QString IRCEditAccountWidget::generateAccountId( const QString &network )
{
	KConfig *config = KGlobal::config();
	QString nextId = network;

	uint accountNumber = 1;
	while( config->hasGroup( QString("Account_%1_%2").arg( m_protocol->pluginId() ).arg( nextId ) ) )
	{
		nextId = QString::fromLatin1("%1_%2").arg( network ).arg( ++accountNumber );
	}
	kdDebug( 14120 ) << k_funcinfo << " ID IS: " << nextId << endl;
	return nextId;
}

Kopete::Account *IRCEditAccountWidget::apply()
{
	QString nickName = mNickName->text();
	QString networkName = network->currentText();

	if( !account() )
	{
		setAccount( new IRCAccount( mProtocol, generateAccountId(networkName), QString::null, networkName, nickName ) );

	}
	else
	{
		account()->setNickName( nickName );
		account()->setNetwork( networkName );
	}

	mPasswordWidget->save( &account()->password() );

	account()->setAltNick( mAltNickname->text() );
	account()->setUserName( mUserName->text() );
	account()->setRealName( m_realNameLineEdit->text() );
	account()->setDefaultPart( partMessage->text() );
	account()->setDefaultQuit( quitMessage->text() );
	account()->setAutoShowServerWindow( autoShowServerWindow->isChecked() );
	account()->setExcludeConnect( autoConnect->isChecked() );
	account()->setMessageDestinations( serverNotices->currentItem() + 1, serverMessages->currentItem() + 1,
		informationReplies->currentItem() + 1, errorMessages->currentItem() + 1
	);

	account()->configGroup()->writeEntry("PreferSSL", preferSSL->isChecked());

	QStringList cmds;
	for( QListViewItem *i = commandList->firstChild(); i; i = i->nextSibling() )
		cmds.append( i->text(0) );

	QMap< QString, QString > replies;
	for( QListViewItem *i = ctcpList->firstChild(); i; i = i->nextSibling() )
		replies[ i->text(0) ] = i->text(1);

	account()->setCustomCtcpReplies( replies );
	account()->setConnectCommands( cmds );

	KCharsets *c = KGlobal::charsets();
	account()->setCodec( c->codecForName( c->encodingForName( charset->currentText() ) ) );

	return account();
}

bool IRCEditAccountWidget::validateData()
{
	if( mNickName->text().isEmpty() )
		KMessageBox::sorry(this, i18n("<qt>You must enter a nickname.</qt>"), i18n("Kopete"));
	else
		return true;

	return false;
}

#include "irceditaccountwidget.moc"
<commit_msg>CCBUG: 111688<commit_after>/*
    irceditaccountwidget.cpp - IRC Account Widget

    Copyright (c) 2005      by Tommi Rantala  <tommi.rantala@cs.helsinki.fi>
    Copyright (c) 2003      by Olivier Goffart  <ogoffart @ kde.org>
    Copyright (c) 2003      by Jason Keirstead  <jason@keirstead.org>
    Kopete    (c) 2003-2005 by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include "irceditaccountwidget.h"

#include "ircaccount.h"
#include "ircusercontact.h"
#include "ircprotocol.h"
#include "kcodecaction.h"

#include "kircengine.h"

#include "kopetepasswordwidget.h"

#include <kmessagebox.h>
#include <klocale.h>
#include <klistview.h>
#include <kdebug.h>
#include <kextsock.h>
#include <kconfig.h>
#include <kglobal.h>
#include <kcharsets.h>

#include <qlabel.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <qcheckbox.h>
#include <qconnection.h>
#include <qvalidator.h>
#include <qcombobox.h>
#include <qlistbox.h>
#include <qlineedit.h>

IRCEditAccountWidget::IRCEditAccountWidget(IRCProtocol *proto, IRCAccount *ident, QWidget *parent, const char * )
	  : IRCEditAccountBase(parent), KopeteEditAccountWidget(ident)
{
	mProtocol = proto;

	// iso latin 1
	int currentCodec = 4;

	if( account() )
	{
		QString nickName = account()->mySelf()->nickName();
		QString serverInfo = account()->accountId();

		mNickName->setText( nickName );
		mAltNickname->setText( account()->altNick() );
		mUserName->setText( account()->userName() );
		m_realNameLineEdit->setText( account()->realName() );

		partMessage->setText( account()->defaultPart() );
		quitMessage->setText( account()->defaultQuit() );
		if( account()->codec() )
			currentCodec = account()->codec()->mibEnum();

		mPasswordWidget->load ( &account()->password() );

		preferSSL->setChecked(account()->configGroup()->readBoolEntry("PreferSSL"));
		autoShowServerWindow->setChecked( account()->configGroup()->readBoolEntry("AutoShowServerWindow") );
		autoConnect->setChecked( static_cast<Kopete::Account*>(account())->excludeConnect() );

		KConfigGroup *config = account()->configGroup();

		serverNotices->setCurrentItem( config->readNumEntry( "ServerNotices", IRCAccount::ServerWindow ) - 1 );
		serverMessages->setCurrentItem( config->readNumEntry( "ServerMessages", IRCAccount::ServerWindow ) - 1 );
		informationReplies->setCurrentItem( config->readNumEntry( "InformationReplies", IRCAccount::ActiveWindow ) - 1 );
		errorMessages->setCurrentItem( config->readNumEntry( "ErrorMessages", IRCAccount::ActiveWindow ) - 1 );

		QStringList cmds = account()->connectCommands();
		for( QStringList::Iterator i = cmds.begin(); i != cmds.end(); ++i )
			new QListViewItem( commandList, *i );

		const QMap< QString, QString > replies = account()->customCtcpReplies();
		for( QMap< QString, QString >::ConstIterator it = replies.begin(); it != replies.end(); ++it )
			new QListViewItem( ctcpList, it.key(), it.data() );
	}

	mUserName->setValidator( new QRegExpValidator( QString::fromLatin1("^[^\\s]*$"), mUserName ) );
	mNickName->setValidator( new QRegExpValidator( QString::fromLatin1("^[^#+&][^\\s]*$"), mNickName ) );
	mAltNickname->setValidator( new QRegExpValidator( QString::fromLatin1("^[^#+&][^\\s]*$"), mAltNickname ) );

	charset->insertStringList( KCodecAction::supportedEncodings() );

	for (int i = 0; i < charset->count(); ++i) {
		QString encoding = KGlobal::charsets()->encodingForName(charset->text(i));

		if (KGlobal::charsets()->codecForName(encoding)->mibEnum() == currentCodec) {
			charset->setCurrentItem( i );
			break;
		}
	}

	connect( commandList, SIGNAL( contextMenu( KListView *, QListViewItem *, const QPoint & ) ),
		this, SLOT( slotCommandContextMenu( KListView *, QListViewItem *, const QPoint & ) ) );

	connect( ctcpList, SIGNAL( contextMenu( KListView *, QListViewItem *, const QPoint & ) ),
		this, SLOT( slotCtcpContextMenu( KListView *, QListViewItem *, const QPoint & ) ) );

	connect( addButton, SIGNAL( clicked() ), this, SLOT( slotAddCommand() ) );
	connect( editButton, SIGNAL( clicked() ), this, SLOT(slotEditNetworks() ) );
	connect( addReply, SIGNAL( clicked() ), this, SLOT( slotAddCtcp() ) );

	connect( network, SIGNAL( activated( const QString & ) ),
		this, SLOT( slotUpdateNetworkDescription( const QString &) ) );

	connect( IRCProtocol::protocol(), SIGNAL( networkConfigUpdated( const QString & ) ),
		this, SLOT( slotUpdateNetworks( const QString & ) ) );

	slotUpdateNetworks( QString::null );
}

IRCEditAccountWidget::~IRCEditAccountWidget()
{
}

IRCAccount *IRCEditAccountWidget::account ()
{
	return dynamic_cast<IRCAccount *>(KopeteEditAccountWidget::account () );
}

void IRCEditAccountWidget::slotUpdateNetworks( const QString & selectedNetwork )
{
	network->clear();

	uint i = 0;
	QStringList keys;
	for( QDictIterator<IRCNetwork> it( IRCProtocol::protocol()->networks() ); it.current(); ++it )
		keys.append( it.currentKey() );

	keys.sort();

	QStringList::Iterator end = keys.end();
	for( QStringList::Iterator it = keys.begin(); it != end; ++it )
	{
		IRCNetwork * current = IRCProtocol::protocol()->networks()[*it];
		network->insertItem( current->name );
		if ( ( account() && account()->networkName() == current->name ) || current->name == selectedNetwork )
		{
			network->setCurrentItem( i );
			description->setText( current->description );
		}
		++i;
	}
}

void IRCEditAccountWidget::slotEditNetworks()
{
	IRCProtocol::protocol()->editNetworks( network->currentText() );
}

void IRCEditAccountWidget::slotUpdateNetworkDescription( const QString &network )
{
	description->setText(
		IRCProtocol::protocol()->networks()[ network ]->description
	);
}

void IRCEditAccountWidget::slotCommandContextMenu( KListView *, QListViewItem *item, const QPoint &p )
{
	QPopupMenu popup;
	popup.insertItem( i18n("Remove Command"), 1 );
	if( popup.exec( p ) == 1 )
		delete item;
}

void IRCEditAccountWidget::slotCtcpContextMenu( KListView *, QListViewItem *item, const QPoint &p )
{
	QPopupMenu popup;
	popup.insertItem( i18n("Remove CTCP Reply"), 1 );
	if( popup.exec( p ) == 1 )
		delete item;
}

void IRCEditAccountWidget::slotAddCommand()
{
    if ( !commandEdit->text().isEmpty() )
    {
	new QListViewItem( commandList, commandEdit->text() );
	commandEdit->clear();
    }
}

void IRCEditAccountWidget::slotAddCtcp()
{
    if (  !newCTCP->text().isEmpty() && !newReply->text().isEmpty() )
    {
	new QListViewItem( ctcpList, newCTCP->text(), newReply->text() );
	newCTCP->clear();
	newReply->clear();
    }
}

QString IRCEditAccountWidget::generateAccountId( const QString &network )
{
	KConfig *config = KGlobal::config();
	QString nextId = network;

	uint accountNumber = 1;
	while( config->hasGroup( QString("Account_%1_%2").arg( m_protocol->pluginId() ).arg( nextId ) ) )
	{
		nextId = QString::fromLatin1("%1_%2").arg( network ).arg( ++accountNumber );
	}
	kdDebug( 14120 ) << k_funcinfo << " ID IS: " << nextId << endl;
	return nextId;
}

Kopete::Account *IRCEditAccountWidget::apply()
{
	QString nickName = mNickName->text();
	QString networkName = network->currentText();

	if( !account() )
	{
		setAccount( new IRCAccount( mProtocol, generateAccountId(networkName), QString::null, networkName, nickName ) );

	}
	else
	{
		account()->setNickName( nickName );
		account()->setNetwork( networkName );
	}

	mPasswordWidget->save( &account()->password() );

	account()->setAltNick( mAltNickname->text() );
	account()->setUserName( mUserName->text() );
	account()->setRealName( m_realNameLineEdit->text() );
	account()->setDefaultPart( partMessage->text() );
	account()->setDefaultQuit( quitMessage->text() );
	account()->setAutoShowServerWindow( autoShowServerWindow->isChecked() );
	account()->setExcludeConnect( autoConnect->isChecked() );
	account()->setMessageDestinations( serverNotices->currentItem() + 1, serverMessages->currentItem() + 1,
		informationReplies->currentItem() + 1, errorMessages->currentItem() + 1
	);

	account()->configGroup()->writeEntry("PreferSSL", preferSSL->isChecked());

	QStringList cmds;
	for( QListViewItem *i = commandList->firstChild(); i; i = i->nextSibling() )
		cmds.append( i->text(0) );

	QMap< QString, QString > replies;
	for( QListViewItem *i = ctcpList->firstChild(); i; i = i->nextSibling() )
		replies[ i->text(0) ] = i->text(1);

	account()->setCustomCtcpReplies( replies );
	account()->setConnectCommands( cmds );

	KCharsets *c = KGlobal::charsets();
	account()->setCodec( c->codecForName( c->encodingForName( charset->currentText() ) ) );

	return account();
}

bool IRCEditAccountWidget::validateData()
{
	if( mNickName->text().isEmpty() )
		KMessageBox::sorry(this, i18n("<qt>You must enter a nickname.</qt>"), i18n("Kopete"));
	else
		return true;

	return false;
}

#include "irceditaccountwidget.moc"
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Josef Gajdusek
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <Alignment.h>

#include "HDialog.h"
#include "YesNoView.h"

YesNoView::YesNoView(BRect frame, BString title)
	:
	DialogView(frame, title)
{
	BGroupLayout* gl = new BGroupLayout(B_HORIZONTAL, B_USE_SMALL_SPACING);
	gl->SetExplicitAlignment(BAlignment(B_ALIGN_RIGHT, B_ALIGN_VERTICAL_UNSET));
	fLayout->AddItem(gl);

	BMessage* ymsg = new BMessage(MSG_SELECTED);
	ymsg->AddString("value", "yes");
	fYesBtn = new BButton("Yes", ymsg);
	fYesBtn->SetExplicitAlignment(BAlignment(B_ALIGN_RIGHT, B_ALIGN_VERTICAL_UNSET));
	gl->AddView(fYesBtn);

	BMessage* nmsg = new BMessage(MSG_SELECTED);
	nmsg->AddString("value", "no");
	fNoBtn = new BButton("No", nmsg);
	fNoBtn->SetExplicitAlignment(BAlignment(B_ALIGN_RIGHT, B_ALIGN_VERTICAL_UNSET));
	gl->AddView(fNoBtn);
}

YesNoView::~YesNoView()
{
}

void YesNoView::AttachedToWindow()
{
	fYesBtn->SetTarget(be_app);
	fNoBtn->SetTarget(be_app);
}
<commit_msg>Swap Yes and No buttons in YesNoView<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Josef Gajdusek
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <Alignment.h>

#include "HDialog.h"
#include "YesNoView.h"

YesNoView::YesNoView(BRect frame, BString title)
	:
	DialogView(frame, title)
{
	BGroupLayout* gl = new BGroupLayout(B_HORIZONTAL, B_USE_SMALL_SPACING);
	gl->SetExplicitAlignment(BAlignment(B_ALIGN_RIGHT, B_ALIGN_VERTICAL_UNSET));
	fLayout->AddItem(gl);

	BMessage* nmsg = new BMessage(MSG_SELECTED);
	nmsg->AddString("value", "no");
	fNoBtn = new BButton("No", nmsg);
	fNoBtn->SetExplicitAlignment(BAlignment(B_ALIGN_RIGHT, B_ALIGN_VERTICAL_UNSET));
	gl->AddView(fNoBtn);

	BMessage* ymsg = new BMessage(MSG_SELECTED);
	ymsg->AddString("value", "yes");
	fYesBtn = new BButton("Yes", ymsg);
	fYesBtn->SetExplicitAlignment(BAlignment(B_ALIGN_RIGHT, B_ALIGN_VERTICAL_UNSET));
	gl->AddView(fYesBtn);
}

YesNoView::~YesNoView()
{
}

void YesNoView::AttachedToWindow()
{
	fYesBtn->SetTarget(be_app);
	fNoBtn->SetTarget(be_app);
}
<|endoftext|>


<commit_before>/*
 * By: ulises-jeremias
 * From: https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=401
 * Name: Overlapping Rectangles
 * Date: 24/11/2017
 */

#include <iostream>
#include <utility>
#include <algorithm>
#include <cmath>
#include <cstdio>

#define EPS 1e-9
#define INF 1 << 30

using namespace std;

typedef long long ll;
typedef pair<int, int> ii;

struct point
{
        int x, y;

        point() {
                x = y = 0;
        }

        point(int _x, int _y) : x(_x), y(_y) {
        };
};

int n;
char op;
point lower_left, upper_right, p, q;
point rectangles[2][5];

point to_vec(const point &a, const point &b)
{
        return point(a.x - b.x, a.y - b.y);
}

double cross(point a, point b)
{
        return (double) ((a.x * b.y) - (b.x * a.y));
}

double to_vec_cross(point a, point b, point c)
{
        return cross(to_vec(a, c), to_vec(b, c));
}

bool ccw(point a, point b, point p)
{
        return to_vec_cross(a, b, p) > 0.0;
}

bool is_inside(int idx)
{
        for (int i = 0; i < 4; i++) {
                if (!ccw(rectangles[0][i], rectangles[0][i + 1], rectangles[1][idx])) {
                        return false;
                }
        }

        return true;
}

int main(int argc, char const *argv[]) {
        #ifndef ONLINE_JUDGE
        #define ONLINE_JUDGE
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        #endif

        int TC, i;
        string line;
        bool overlap;

        scanf("%d", &TC);
        getchar();
        getline(cin, line);

        while (TC--) {
                for (i = 0; i < 2; ++i)
                {
                        scanf("%d %d", &lower_left.x, &lower_left.y);
                        scanf("%d %d", &upper_right.x, &upper_right.y);

                        rectangles[i][0].x = lower_left.x;
                        rectangles[i][0].y = upper_right.y;

                        rectangles[i][1].x = lower_left.x;
                        rectangles[i][1].y = lower_left.y;

                        rectangles[i][2].x = upper_right.x;
                        rectangles[i][2].y = lower_left.y;

                        rectangles[i][3].x = upper_right.x;
                        rectangles[i][3].y = upper_right.y;

                        rectangles[i][4].x = lower_left.x;
                        rectangles[i][4].y = upper_right.y;
                }

                overlap = false;
                for (i = 0; i < 4; ++i)
                {
                        if (is_inside(i)) {
                                overlap = true;
                                break;
                        }
                }

                if (overlap) {
                        point w;
                        p = rectangles[1][i];
                        if (i == 0) {
                                w = rectangles[0][2];
                                printf("%d %d %d %d\n", p.x, w.y, w.x, p.y);
                        } else if (i == 1) {
                                w = rectangles[0][3];
                                printf("%d %d %d %d\n", p.x, p.y, w.x, w.y);
                        } else if (i == 2) {
                                w = rectangles[0][0];
                                printf("%d %d %d %d\n", w.x, p.y, p.x, w.y);
                        } else {
                                w = rectangles[0][1];
                                printf("%d %d %d %d\n", w.x, w.y, p.x, p.y);
                        }
                } else {
                        cout << "No Overlap" << endl;
                }
        }

        return 0;
}
<commit_msg>Solved<commit_after>/*
 * By: ulises-jeremias
 * From: https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=401
 * Name: Overlapping Rectangles
 * Date: 24/11/2017
 */

#include <iostream>
#include <utility>
#include <algorithm>
#include <cmath>

#define EPS 1e-9
#define INF 1 <<  30

using namespace std;

typedef long long ll;
typedef pair<int, int> ii;

struct point
{
        int x, y;

        point() {
                x = y = 0;
        }

        point(int _x, int _y) : x(_x), y(_y) {
        };
};

point p1, p2, p3, p4, p5, p6;

int main () {
        #ifndef ONLINE_JUDGE
        #define ONLINE_JUDGE
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        #endif

        int TC, i, j;

        cin >> TC;
        while (TC--) {
                cin >> p1.x >> p1.y >> p2.x >> p2.y;
                cin >> p3.x >> p3.y >> p4.x >> p4.y;

                p5.x = max(p1.x, p3.x);
                p5.y = max(p1.y, p3.y);
                p6.x = min(p2.x, p4.x);
                p6.y = min(p2.y, p4.y);

                if (p5.x >= p6.x || p5.y >= p6.y) {
                        cout << "No Overlap" << endl;
                } else {
                        cout << p5.x << " " << p5.y << " " << p6.x << " " << p6.y << endl;
                }

                if (TC) {
                        cout << endl;
                }
        }

        return 0;
}
<|endoftext|>


<commit_before><commit_msg>fix various native themeing issues because of lacking restore<commit_after><|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 * Copyright (c) 2014, Daiki Maekawa and Robot Design and Control Lab.
 * 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.
 * 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 OWNER 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 <ros/ros.h>
#include <std_msgs/String.h>
#include <std_srvs/Empty.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Twist.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <actionlib/client/simple_action_client.h>
#include <tf/tf.h>
#include <tf/transform_listener.h>

#include <yaml-cpp/yaml.h>

#include <vector>
#include <fstream>
#include <string>

#include <visualization_msgs/MarkerArray.h>

#ifdef NEW_YAMLCPP
template<typename T>
void operator >> (const YAML::Node& node, T& i)
{
    i = node.as<T>();
}
#endif

class WaypointsNavigation{
public:
    WaypointsNavigation() :
        has_activate_(false),
        move_base_action_("move_base", true),
        rate_(10),
        last_moved_time_(0)
    {
        while((move_base_action_.waitForServer(ros::Duration(1.0)) == false) && (ros::ok() == true))
        {
            ROS_INFO("Waiting...");
        }

        ros::NodeHandle private_nh("~");
        private_nh.param("robot_frame", robot_frame_, std::string("/base_link"));
        private_nh.param("world_frame", world_frame_, std::string("/map"));

        double max_update_rate;
        private_nh.param("max_update_rate", max_update_rate, 10.0);
        rate_ = ros::Rate(max_update_rate);
        std::string filename = "";
        private_nh.param("filename", filename, filename);
        if(filename != ""){
            ROS_INFO_STREAM("Read waypoints data from " << filename);
            readFile(filename);
        }

        ros::NodeHandle nh;
        syscommand_sub_ = nh.subscribe("syscommand", 1, &WaypointsNavigation::syscommandCallback, this);
        cmd_vel_sub_ = nh.subscribe("icart_mini/cmd_vel", 1, &WaypointsNavigation::cmdVelCallback, this);
        marker_pub_ = nh.advertise<visualization_msgs::MarkerArray>("visualization_marker", 10);
        clear_costmaps_srv_ = nh.serviceClient<std_srvs::Empty>("/move_base/clear_costmaps");
    }

    void syscommandCallback(const std_msgs::String &msg){
        if(msg.data == "start"){
            has_activate_ = true;
        }
    }

    void cmdVelCallback(const geometry_msgs::Twist &msg){
        if(msg.linear.x > -0.001 && msg.linear.x < 0.001   &&
           msg.linear.y > -0.001 && msg.linear.y < 0.001   &&
           msg.linear.z > -0.001 && msg.linear.z < 0.001   &&
           msg.angular.x > -0.001 && msg.angular.x < 0.001 &&
           msg.angular.y > -0.001 && msg.angular.y < 0.001 &&
           msg.angular.z > -0.001 && msg.angular.z < 0.001){

            ROS_INFO("command velocity all zero");
        }else{
            last_moved_time_ = ros::Time::now().toSec();
        }
    }

    bool readFile(const std::string &filename){
        waypoints_.clear();
        try{
            std::ifstream ifs(filename.c_str(), std::ifstream::in);
            if(ifs.good() == false){
                return false;
            }

            YAML::Node node;
            node = YAML::Load(ifs);
            const YAML::Node &wp_node_tmp = node["waypoints"];
            const YAML::Node *wp_node = wp_node_tmp ? &wp_node_tmp : NULL;
            if(wp_node != NULL){
                for(int i=0; i < wp_node->size(); i++){
                    geometry_msgs::PointStamped point;

                    (*wp_node)[i]["point"]["x"] >> point.point.x;
                    (*wp_node)[i]["point"]["y"] >> point.point.y;
                    (*wp_node)[i]["point"]["z"] >> point.point.z;

                    waypoints_.push_back(point);

                }
            }else{
                return false;
            }

            const YAML::Node &fp_node_tmp = node["finish_pose"];
            const YAML::Node *fp_node = fp_node_tmp ? &fp_node_tmp : NULL;

            if(fp_node != NULL){
                (*fp_node)["pose"]["position"]["x"] >> finish_pose_.position.x;
                (*fp_node)["pose"]["position"]["y"] >> finish_pose_.position.y;
                (*fp_node)["pose"]["position"]["z"] >> finish_pose_.position.z;

                (*fp_node)["pose"]["orientation"]["x"] >> finish_pose_.orientation.x;
                (*fp_node)["pose"]["orientation"]["y"] >> finish_pose_.orientation.y;
                (*fp_node)["pose"]["orientation"]["z"] >> finish_pose_.orientation.z;
                (*fp_node)["pose"]["orientation"]["w"] >> finish_pose_.orientation.w;
            }else{
                return false;
            }

        }catch(YAML::ParserException &e){
            return false;

        }catch(YAML::RepresentationException &e){
            return false;
        }

        return true;
    }

    bool shouldSendGoal(){
        bool ret = true;
        actionlib::SimpleClientGoalState state = move_base_action_.getState();
        if((state != actionlib::SimpleClientGoalState::ACTIVE) &&
           (state != actionlib::SimpleClientGoalState::PENDING) &&
           (state != actionlib::SimpleClientGoalState::RECALLED) &&
           (state != actionlib::SimpleClientGoalState::PREEMPTED))
        {
            ret = false;
        }

        if(waypoints_.empty()){
            ret = false;
        }

        return ret;
    }

    bool navigationFinished(){
        return move_base_action_.getState() == actionlib::SimpleClientGoalState::SUCCEEDED;
    }

    bool onNavigationPoint(const geometry_msgs::Point &dest, double dist_err = 0.5){
        tf::StampedTransform robot_gl = getRobotPosGL();

        const double wx = dest.x;
        const double wy = dest.y;
        const double rx = robot_gl.getOrigin().x();
        const double ry = robot_gl.getOrigin().y();
        const double dist = std::sqrt(std::pow(wx - rx, 2) + std::pow(wy - ry, 2));

        return dist < dist_err;
    }

    tf::StampedTransform getRobotPosGL(){
        tf::StampedTransform robot_gl;
        try{
            tf_listener_.lookupTransform(world_frame_, robot_frame_, ros::Time(0.0), robot_gl);
        }catch(tf::TransformException &e){
            ROS_WARN_STREAM("tf::TransformException: " << e.what());
        }

        return robot_gl;
    }

    void sleep(){
        rate_.sleep();
        ros::spinOnce();
        publishMarkers();
    }

    void startNavigationGL(const geometry_msgs::Point &dest){
        geometry_msgs::Pose pose;
        pose.position = dest;
        pose.orientation = tf::createQuaternionMsgFromYaw(0.0);
        startNavigationGL(pose);
    }

    void startNavigationGL(const geometry_msgs::Pose &dest){
        move_base_msgs::MoveBaseGoal move_base_goal;
        move_base_goal.target_pose.header.stamp = ros::Time::now();
        move_base_goal.target_pose.header.frame_id = world_frame_;
        move_base_goal.target_pose.pose.position = dest.position;
        move_base_goal.target_pose.pose.orientation = dest.orientation;

        move_base_action_.sendGoal(move_base_goal);
    }

    void publishMarkers(){
        visualization_msgs::MarkerArray markers_array;
        for(int i=0; i < waypoints_.size(); i++){
            visualization_msgs::Marker marker, label;
            marker.header.frame_id = world_frame_;
            marker.header.stamp = ros::Time::now();
            marker.scale.x = 0.2;
            marker.scale.y = 0.2;
            marker.scale.z = 0.2;
            marker.pose.position.z = marker.scale.z / 2.0;
            marker.color.r = 0.8f;
            marker.color.g = 0.2f;
            marker.color.b = 0.2f;

            std::stringstream name;
            name << "waypoint " << i;
            marker.ns = name.str();
            marker.id = i;
            marker.pose.position.x = waypoints_[i].point.x;
            marker.pose.position.y = waypoints_[i].point.y;
            marker.type = visualization_msgs::Marker::SPHERE;
            marker.action = visualization_msgs::Marker::ADD;
            marker.color.a = 1.0f;
            markers_array.markers.push_back(marker);

            //ROS_INFO_STREAM("waypoints \n" << waypoints_[i]);
        }
        marker_pub_.publish(markers_array);
    }

    void run(){
        while(ros::ok()){
            if(has_activate_){
                for(int i=0; i < waypoints_.size(); i++){
                    ROS_INFO_STREAM("waypoint = " << waypoints_[i]);
                    if(!ros::ok()) break;

                    startNavigationGL(waypoints_[i].point);
                    double start_nav_time = ros::Time::now().toSec();
                    while(!onNavigationPoint(waypoints_[i].point)){
                        double time = ros::Time::now().toSec();
                        if(time - start_nav_time > 10.0 && time - last_moved_time_ > 10.0){
                            ROS_WARN("Resend the navigation goal.");
                            std_srvs::Empty empty;
                            clear_costmaps_srv_.call(empty);
                            startNavigationGL(waypoints_[i].point);
                            start_nav_time = time;
                        }
                        actionlib::SimpleClientGoalState state = move_base_action_.getState();
                        sleep();
                    }
                    ROS_INFO("waypoint goal");
                }
                ROS_INFO("waypoints clear");
                waypoints_.clear();
                startNavigationGL(finish_pose_);
                while(!navigationFinished() && ros::ok()) sleep();
                has_activate_ = false;
            }

            sleep();
        }
    }

private:
    actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> move_base_action_;
    std::vector<geometry_msgs::PointStamped> waypoints_;
    geometry_msgs::Pose finish_pose_;
    bool has_activate_;
    std::string robot_frame_, world_frame_;
    tf::TransformListener tf_listener_;
    ros::Rate rate_;
    ros::Subscriber syscommand_sub_;
    ros::Subscriber cmd_vel_sub_;
    ros::Publisher marker_pub_;
    ros::ServiceClient clear_costmaps_srv_;
    double last_moved_time_;
};

int main(int argc, char *argv[]){
    ros::init(argc, argv, ROS_PACKAGE_NAME);
    WaypointsNavigation w_nav;
    w_nav.run();

    return 0;
}
<commit_msg>Support yaml-cpp 0.3<commit_after>/*
 * Software License Agreement (BSD License)
 *
 * Copyright (c) 2014, Daiki Maekawa and Robot Design and Control Lab.
 * 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.
 * 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 OWNER 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 <ros/ros.h>
#include <std_msgs/String.h>
#include <std_srvs/Empty.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Twist.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <actionlib/client/simple_action_client.h>
#include <tf/tf.h>
#include <tf/transform_listener.h>

#include <yaml-cpp/yaml.h>

#include <vector>
#include <fstream>
#include <string>

#include <visualization_msgs/MarkerArray.h>

#ifdef NEW_YAMLCPP
template<typename T>
void operator >> (const YAML::Node& node, T& i)
{
    i = node.as<T>();
}
#endif

class WaypointsNavigation{
public:
    WaypointsNavigation() :
        has_activate_(false),
        move_base_action_("move_base", true),
        rate_(10),
        last_moved_time_(0)
    {
        while((move_base_action_.waitForServer(ros::Duration(1.0)) == false) && (ros::ok() == true))
        {
            ROS_INFO("Waiting...");
        }

        ros::NodeHandle private_nh("~");
        private_nh.param("robot_frame", robot_frame_, std::string("/base_link"));
        private_nh.param("world_frame", world_frame_, std::string("/map"));

        double max_update_rate;
        private_nh.param("max_update_rate", max_update_rate, 10.0);
        rate_ = ros::Rate(max_update_rate);
        std::string filename = "";
        private_nh.param("filename", filename, filename);
        if(filename != ""){
            ROS_INFO_STREAM("Read waypoints data from " << filename);
            readFile(filename);
        }

        ros::NodeHandle nh;
        syscommand_sub_ = nh.subscribe("syscommand", 1, &WaypointsNavigation::syscommandCallback, this);
        cmd_vel_sub_ = nh.subscribe("icart_mini/cmd_vel", 1, &WaypointsNavigation::cmdVelCallback, this);
        marker_pub_ = nh.advertise<visualization_msgs::MarkerArray>("visualization_marker", 10);
        clear_costmaps_srv_ = nh.serviceClient<std_srvs::Empty>("/move_base/clear_costmaps");
    }

    void syscommandCallback(const std_msgs::String &msg){
        if(msg.data == "start"){
            has_activate_ = true;
        }
    }

    void cmdVelCallback(const geometry_msgs::Twist &msg){
        if(msg.linear.x > -0.001 && msg.linear.x < 0.001   &&
           msg.linear.y > -0.001 && msg.linear.y < 0.001   &&
           msg.linear.z > -0.001 && msg.linear.z < 0.001   &&
           msg.angular.x > -0.001 && msg.angular.x < 0.001 &&
           msg.angular.y > -0.001 && msg.angular.y < 0.001 &&
           msg.angular.z > -0.001 && msg.angular.z < 0.001){

            ROS_INFO("command velocity all zero");
        }else{
            last_moved_time_ = ros::Time::now().toSec();
        }
    }

    bool readFile(const std::string &filename){
        waypoints_.clear();
        try{
            std::ifstream ifs(filename.c_str(), std::ifstream::in);
            if(ifs.good() == false){
                return false;
            }

            YAML::Node node;

            #ifdef NEW_YAMLCPP
                node = YAML::Load(ifs);
            #else
                YAML::Parser parser(ifs);
                parser.GetNextDocument(node);
            #endif

            #ifdef NEW_YAMLCPP
                const YAML::Node &wp_node_tmp = node["waypoints"];
                const YAML::Node *wp_node = wp_node_tmp ? &wp_node_tmp : NULL;
            #else
                const YAML::Node *wp_node = node.FindValue("waypoints");
            #endif

            if(wp_node != NULL){
                for(int i=0; i < wp_node->size(); i++){
                    geometry_msgs::PointStamped point;

                    (*wp_node)[i]["point"]["x"] >> point.point.x;
                    (*wp_node)[i]["point"]["y"] >> point.point.y;
                    (*wp_node)[i]["point"]["z"] >> point.point.z;

                    waypoints_.push_back(point);

                }
            }else{
                return false;
            }

            const YAML::Node &fp_node_tmp = node["finish_pose"];
            const YAML::Node *fp_node = fp_node_tmp ? &fp_node_tmp : NULL;

            if(fp_node != NULL){
                (*fp_node)["pose"]["position"]["x"] >> finish_pose_.position.x;
                (*fp_node)["pose"]["position"]["y"] >> finish_pose_.position.y;
                (*fp_node)["pose"]["position"]["z"] >> finish_pose_.position.z;

                (*fp_node)["pose"]["orientation"]["x"] >> finish_pose_.orientation.x;
                (*fp_node)["pose"]["orientation"]["y"] >> finish_pose_.orientation.y;
                (*fp_node)["pose"]["orientation"]["z"] >> finish_pose_.orientation.z;
                (*fp_node)["pose"]["orientation"]["w"] >> finish_pose_.orientation.w;
            }else{
                return false;
            }

        }catch(YAML::ParserException &e){
            return false;

        }catch(YAML::RepresentationException &e){
            return false;
        }

        return true;
    }

    bool shouldSendGoal(){
        bool ret = true;
        actionlib::SimpleClientGoalState state = move_base_action_.getState();
        if((state != actionlib::SimpleClientGoalState::ACTIVE) &&
           (state != actionlib::SimpleClientGoalState::PENDING) &&
           (state != actionlib::SimpleClientGoalState::RECALLED) &&
           (state != actionlib::SimpleClientGoalState::PREEMPTED))
        {
            ret = false;
        }

        if(waypoints_.empty()){
            ret = false;
        }

        return ret;
    }

    bool navigationFinished(){
        return move_base_action_.getState() == actionlib::SimpleClientGoalState::SUCCEEDED;
    }

    bool onNavigationPoint(const geometry_msgs::Point &dest, double dist_err = 0.5){
        tf::StampedTransform robot_gl = getRobotPosGL();

        const double wx = dest.x;
        const double wy = dest.y;
        const double rx = robot_gl.getOrigin().x();
        const double ry = robot_gl.getOrigin().y();
        const double dist = std::sqrt(std::pow(wx - rx, 2) + std::pow(wy - ry, 2));

        return dist < dist_err;
    }

    tf::StampedTransform getRobotPosGL(){
        tf::StampedTransform robot_gl;
        try{
            tf_listener_.lookupTransform(world_frame_, robot_frame_, ros::Time(0.0), robot_gl);
        }catch(tf::TransformException &e){
            ROS_WARN_STREAM("tf::TransformException: " << e.what());
        }

        return robot_gl;
    }

    void sleep(){
        rate_.sleep();
        ros::spinOnce();
        publishMarkers();
    }

    void startNavigationGL(const geometry_msgs::Point &dest){
        geometry_msgs::Pose pose;
        pose.position = dest;
        pose.orientation = tf::createQuaternionMsgFromYaw(0.0);
        startNavigationGL(pose);
    }

    void startNavigationGL(const geometry_msgs::Pose &dest){
        move_base_msgs::MoveBaseGoal move_base_goal;
        move_base_goal.target_pose.header.stamp = ros::Time::now();
        move_base_goal.target_pose.header.frame_id = world_frame_;
        move_base_goal.target_pose.pose.position = dest.position;
        move_base_goal.target_pose.pose.orientation = dest.orientation;

        move_base_action_.sendGoal(move_base_goal);
    }

    void publishMarkers(){
        visualization_msgs::MarkerArray markers_array;
        for(int i=0; i < waypoints_.size(); i++){
            visualization_msgs::Marker marker, label;
            marker.header.frame_id = world_frame_;
            marker.header.stamp = ros::Time::now();
            marker.scale.x = 0.2;
            marker.scale.y = 0.2;
            marker.scale.z = 0.2;
            marker.pose.position.z = marker.scale.z / 2.0;
            marker.color.r = 0.8f;
            marker.color.g = 0.2f;
            marker.color.b = 0.2f;

            std::stringstream name;
            name << "waypoint " << i;
            marker.ns = name.str();
            marker.id = i;
            marker.pose.position.x = waypoints_[i].point.x;
            marker.pose.position.y = waypoints_[i].point.y;
            marker.type = visualization_msgs::Marker::SPHERE;
            marker.action = visualization_msgs::Marker::ADD;
            marker.color.a = 1.0f;
            markers_array.markers.push_back(marker);

            //ROS_INFO_STREAM("waypoints \n" << waypoints_[i]);
        }
        marker_pub_.publish(markers_array);
    }

    void run(){
        while(ros::ok()){
            if(has_activate_){
                for(int i=0; i < waypoints_.size(); i++){
                    ROS_INFO_STREAM("waypoint = " << waypoints_[i]);
                    if(!ros::ok()) break;

                    startNavigationGL(waypoints_[i].point);
                    double start_nav_time = ros::Time::now().toSec();
                    while(!onNavigationPoint(waypoints_[i].point)){
                        double time = ros::Time::now().toSec();
                        if(time - start_nav_time > 10.0 && time - last_moved_time_ > 10.0){
                            ROS_WARN("Resend the navigation goal.");
                            std_srvs::Empty empty;
                            clear_costmaps_srv_.call(empty);
                            startNavigationGL(waypoints_[i].point);
                            start_nav_time = time;
                        }
                        actionlib::SimpleClientGoalState state = move_base_action_.getState();
                        sleep();
                    }
                    ROS_INFO("waypoint goal");
                }
                ROS_INFO("waypoints clear");
                waypoints_.clear();
                startNavigationGL(finish_pose_);
                while(!navigationFinished() && ros::ok()) sleep();
                has_activate_ = false;
            }

            sleep();
        }
    }

private:
    actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> move_base_action_;
    std::vector<geometry_msgs::PointStamped> waypoints_;
    geometry_msgs::Pose finish_pose_;
    bool has_activate_;
    std::string robot_frame_, world_frame_;
    tf::TransformListener tf_listener_;
    ros::Rate rate_;
    ros::Subscriber syscommand_sub_;
    ros::Subscriber cmd_vel_sub_;
    ros::Publisher marker_pub_;
    ros::ServiceClient clear_costmaps_srv_;
    double last_moved_time_;
};

int main(int argc, char *argv[]){
    ros::init(argc, argv, ROS_PACKAGE_NAME);
    WaypointsNavigation w_nav;
    w_nav.run();

    return 0;
}
<|endoftext|>


<commit_before><commit_msg>Cleaning up code.<commit_after><|endoftext|>


<commit_before><commit_msg>Edit whitespace.<commit_after><|endoftext|>


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

#include <QtCore/QBuffer>

#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QLayout>
#include <QtGui/QApplication>
#include <QtGui/QDesktopWidget>
#include <QtGui/QMessageBox>
#include <QtGui/QDesktopServices>

#include "aboutdialog.h"

QT_BEGIN_NAMESPACE

AboutLabel::AboutLabel(QWidget *parent)
    : QTextBrowser(parent)
{
    TRACE_OBJ
    setFrameStyle(QFrame::NoFrame);
    QPalette p;
    p.setColor(QPalette::Base, p.color(QPalette::Background));
    setPalette(p);
}

void AboutLabel::setText(const QString &text, const QByteArray &resources)
{
    TRACE_OBJ
    QDataStream in(resources);
    in >> m_resourceMap;

    QTextBrowser::setText(text);
}

QSize AboutLabel::minimumSizeHint() const
{
    TRACE_OBJ
    QTextDocument *doc = document();
    doc->adjustSize();
    return QSize(int(doc->size().width()), int(doc->size().height()));
}

QVariant AboutLabel::loadResource(int type, const QUrl &name)
{
    TRACE_OBJ
    if (type == 2 || type == 3) {
        if (m_resourceMap.contains(name.toString())) {
            return m_resourceMap.value(name.toString());
        }
    }
    return QVariant();
}

void AboutLabel::setSource(const QUrl &url)
{
    TRACE_OBJ
    if (url.isValid()
        && (url.scheme() == QLatin1String("http") || url.scheme() == QLatin1String("ftp")
            || url.scheme() == QLatin1String("mailto") || url.path().endsWith(QLatin1String("pdf")))) {
        if (!QDesktopServices::openUrl(url)) {
            QMessageBox::warning(this, tr("Warning"),
                         tr("Unable to launch external application.\n"),
                         tr("OK"));
        }
    }
}

AboutDialog::AboutDialog(QWidget *parent)
    : QDialog(parent, Qt::MSWindowsFixedSizeDialogHint|Qt::WindowTitleHint|Qt::WindowSystemMenuHint)
{
    TRACE_OBJ
    m_pixmapLabel = 0;
    m_aboutLabel = new AboutLabel();

    m_closeButton = new QPushButton();
    m_closeButton->setText(tr("&Close"));
    connect(m_closeButton, SIGNAL(clicked()),
        this, SLOT(close()));

    m_layout = new QGridLayout(this);
    m_layout->addWidget(m_aboutLabel, 1, 0, 1, -1);
    m_layout->addItem(new QSpacerItem(20, 10, QSizePolicy::Minimum, QSizePolicy::Fixed), 2, 1, 1, 1);
    m_layout->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding), 3, 0, 1, 1);
    m_layout->addWidget(m_closeButton, 3, 1, 1, 1);
    m_layout->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding), 3, 2, 1, 1);
}

void AboutDialog::setText(const QString &text, const QByteArray &resources)
{
    TRACE_OBJ
    m_aboutLabel->setText(text, resources);
    updateSize();
}

void AboutDialog::setPixmap(const QPixmap &pixmap)
{
    TRACE_OBJ
    if (!m_pixmapLabel) {
        m_pixmapLabel = new QLabel();
        m_layout->addWidget(m_pixmapLabel, 0, 0, 1, -1, Qt::AlignCenter);
    }
    m_pixmapLabel->setPixmap(pixmap);
    updateSize();
}

QString AboutDialog::documentTitle() const
{
    TRACE_OBJ
    return m_aboutLabel->documentTitle();
}

void AboutDialog::updateSize()
{
    TRACE_OBJ
    QSize screenSize = QApplication::desktop()->availableGeometry(QCursor::pos()).size();
    int limit = qMin(screenSize.width()/2, 500);

#ifdef Q_WS_MAC
    limit = qMin(screenSize.width()/2, 420);
#endif

    layout()->activate();
    int width = layout()->totalMinimumSize().width();

    if (width > limit)
        width = limit;

    QFontMetrics fm(qApp->font("QWorkspaceTitleBar"));
    int windowTitleWidth = qMin(fm.width(windowTitle()) + 50, limit);
    if (windowTitleWidth > width)
        width = windowTitleWidth;

    layout()->activate();
    int height = (layout()->hasHeightForWidth())
                     ? layout()->totalHeightForWidth(width)
                     : layout()->totalMinimumSize().height();
    setFixedSize(width, height);
    QCoreApplication::removePostedEvents(this, QEvent::LayoutRequest);
}

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

#include <QtCore/QBuffer>

#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QLayout>
#include <QtGui/QApplication>
#include <QtGui/QDesktopWidget>
#include <QtGui/QMessageBox>
#include <QtGui/QDesktopServices>

#include "aboutdialog.h"

QT_BEGIN_NAMESPACE

AboutLabel::AboutLabel(QWidget *parent)
    : QTextBrowser(parent)
{
    TRACE_OBJ
    setFrameStyle(QFrame::NoFrame);
    QPalette p;
    p.setColor(QPalette::Base, p.color(QPalette::Background));
    setPalette(p);
}

void AboutLabel::setText(const QString &text, const QByteArray &resources)
{
    TRACE_OBJ
    QDataStream in(resources);
    in >> m_resourceMap;

    QTextBrowser::setText(text);
}

QSize AboutLabel::minimumSizeHint() const
{
    TRACE_OBJ
    QTextDocument *doc = document();
    doc->adjustSize();
    return QSize(int(doc->size().width()), int(doc->size().height()));
}

QVariant AboutLabel::loadResource(int type, const QUrl &name)
{
    TRACE_OBJ
    if (type == 2 || type == 3) {
        if (m_resourceMap.contains(name.toString())) {
            return m_resourceMap.value(name.toString());
        }
    }
    return QVariant();
}

void AboutLabel::setSource(const QUrl &url)
{
    TRACE_OBJ
    if (url.isValid()
        && (url.scheme() == QLatin1String("http") || url.scheme() == QLatin1String("ftp")
            || url.scheme() == QLatin1String("mailto") || !HelpViewer::canOpenPage(url.path()))) {
        if (!QDesktopServices::openUrl(url)) {
            QMessageBox::warning(this, tr("Warning"),
                         tr("Unable to launch external application.\n"),
                         tr("OK"));
        }
    }
}

AboutDialog::AboutDialog(QWidget *parent)
    : QDialog(parent, Qt::MSWindowsFixedSizeDialogHint|Qt::WindowTitleHint|Qt::WindowSystemMenuHint)
{
    TRACE_OBJ
    m_pixmapLabel = 0;
    m_aboutLabel = new AboutLabel();

    m_closeButton = new QPushButton();
    m_closeButton->setText(tr("&Close"));
    connect(m_closeButton, SIGNAL(clicked()),
        this, SLOT(close()));

    m_layout = new QGridLayout(this);
    m_layout->addWidget(m_aboutLabel, 1, 0, 1, -1);
    m_layout->addItem(new QSpacerItem(20, 10, QSizePolicy::Minimum, QSizePolicy::Fixed), 2, 1, 1, 1);
    m_layout->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding), 3, 0, 1, 1);
    m_layout->addWidget(m_closeButton, 3, 1, 1, 1);
    m_layout->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding), 3, 2, 1, 1);
}

void AboutDialog::setText(const QString &text, const QByteArray &resources)
{
    TRACE_OBJ
    m_aboutLabel->setText(text, resources);
    updateSize();
}

void AboutDialog::setPixmap(const QPixmap &pixmap)
{
    TRACE_OBJ
    if (!m_pixmapLabel) {
        m_pixmapLabel = new QLabel();
        m_layout->addWidget(m_pixmapLabel, 0, 0, 1, -1, Qt::AlignCenter);
    }
    m_pixmapLabel->setPixmap(pixmap);
    updateSize();
}

QString AboutDialog::documentTitle() const
{
    TRACE_OBJ
    return m_aboutLabel->documentTitle();
}

void AboutDialog::updateSize()
{
    TRACE_OBJ
    QSize screenSize = QApplication::desktop()->availableGeometry(QCursor::pos()).size();
    int limit = qMin(screenSize.width()/2, 500);

#ifdef Q_WS_MAC
    limit = qMin(screenSize.width()/2, 420);
#endif

    layout()->activate();
    int width = layout()->totalMinimumSize().width();

    if (width > limit)
        width = limit;

    QFontMetrics fm(qApp->font("QWorkspaceTitleBar"));
    int windowTitleWidth = qMin(fm.width(windowTitle()) + 50, limit);
    if (windowTitleWidth > width)
        width = windowTitleWidth;

    layout()->activate();
    int height = (layout()->hasHeightForWidth())
                     ? layout()->totalHeightForWidth(width)
                     : layout()->totalMinimumSize().height();
    setFixedSize(width, height);
    QCoreApplication::removePostedEvents(this, QEvent::LayoutRequest);
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>#include <BackgroundManager.hpp>
#include <Player.hpp>

using namespace uth;

BackgroundManager::BackgroundManager(float bY, float fY, float mY)
{

}
bool BackgroundManager::Init(uth::Layer& bg, uth::Layer& fg)
{
	m_cameraPan = 0;
	m_cameraPanMax = 350;
	m_cameraPanSpd = 2.5;
	m_isCameraTurning = false;
	backG = &bg;
	backF = &fg;

	// Background
	GameObject* temp;

	//Sky
	backG->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "sky1" }));
	temp->AddComponent(new Background(c_mountainSpeedM/2,
		uthEngine.GetWindow().GetSize().y - 740, 0, true,
		"backgrounds/sky.png"));
	backG->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "sky1" }));
	temp->AddComponent(new Background(c_mountainSpeedM/2,
		uthEngine.GetWindow().GetSize().y - 740, 0, false,
		"backgrounds/sky.png"));

	//Mountains
	backG->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "mountain1" }));
	temp->AddComponent(new Background(c_mountainSpeedM,
		uthEngine.GetWindow().GetSize().y - 570, 0.5, true,
		"backgrounds/mountains01.png"));
	backG->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "mountain2" }));
	temp->AddComponent(new Background(c_mountainSpeedM,
		uthEngine.GetWindow().GetSize().y - 570, 0.5, false,
		"backgrounds/mountains02.png"));

	//Backcity
	backG->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "building3" }));
	temp->AddComponent(new Background(c_backSpeedM / 1.2f,
		uthEngine.GetWindow().GetSize().y - 480, 2, true,
		"backgrounds/buildings01.png"));
	backG->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "building4" }));
	temp->AddComponent(new Background(c_backSpeedM / 1.2f,
		uthEngine.GetWindow().GetSize().y - 480, 2, false,
		"backgrounds/buildings01.png"));

	backG->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "building1" }));
	temp->AddComponent(new Background(c_backSpeedM,
		uthEngine.GetWindow().GetSize().y - 480, 2,true,
		"backgrounds/buildings02.png"));
	backG->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "building2" }));
	temp->AddComponent(new Background(c_backSpeedM,
		uthEngine.GetWindow().GetSize().y - 480, 2, false,
		"backgrounds/buildings02.png"));

	//Frontcity
	backF->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "lantern1" }));
	temp->AddComponent(new Background(c_frontSpeedM,
		uthEngine.GetWindow().GetSize().y - 220, 4, true,
		"backgrounds/lanterns.png"));
	backF->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "lantern2" }));
	temp->AddComponent(new Background(c_frontSpeedM,
		uthEngine.GetWindow().GetSize().y - 220, 4, false,
		"backgrounds/lanterns.png"));

	return true;
}
void BackgroundManager::Update(float dt)
{
	CameraMovement(dt);

}
void BackgroundManager::CameraMovement(float dt)
{
	m_camera = &uthEngine.GetWindow().GetCamera();

	if (m_camShakeAmount > 0)
	{
		m_camShakeAmount -= dt;
		m_camera->transform.SetRotation(Randomizer::GetFloat(-m_camShakeAmount, m_camShakeAmount));
	}
	else
	{
		m_camera->transform.SetRotation(0);
	}

	m_camera->SetPosition(m_cameraPan, m_cameraStartPos.y);
	if (!m_isCameraTurning)
	{
		m_isCameraTurning = true;
		m_cameraPan = 0;
	}
	//Change direction depending where player is looking
	if (Player::isGoingRight)
	{
		m_cameraPan += dt*m_cameraPanSpd * ((m_cameraStartPos.x + m_cameraPanMax) - m_camera->GetPosition().x);
	}
	else
	{
		m_cameraPan += dt*m_cameraPanSpd * ((m_cameraStartPos.x - m_cameraPanMax) - m_camera->GetPosition().x);
	}
}
void BackgroundManager::SetCameraStartPos(pmath::Vec2 pos)
{
	m_cameraStartPos = pos;
	uthEngine.GetWindow().GetCamera().SetPosition(pos);
}
void BackgroundManager::Shake(float amount, float delay)
{

	auto childrenF = backF->Children("bg");
	auto childrenG = backG->Children("bg");

	//Set amount and delay to backgrounds
	for (auto& e : childrenF)
	{
		auto fg = static_cast<GameObject*>(e.get());
		fg->GetComponent<Background>()->Shake(amount);
	}
	for (auto& e : childrenG)
	{
		auto bg = static_cast<GameObject*>(e.get());
		bg->GetComponent<Background>()->Shake(amount);
	}
	m_camShakeAmount = amount*0.4f;
}
BackgroundManager::~BackgroundManager()
{
	DeInit();
}

void BackgroundManager::DeInit()
{

}<commit_msg>lowered lanterns<commit_after>#include <BackgroundManager.hpp>
#include <Player.hpp>

using namespace uth;

BackgroundManager::BackgroundManager(float bY, float fY, float mY)
{

}
bool BackgroundManager::Init(uth::Layer& bg, uth::Layer& fg)
{
	m_cameraPan = 0;
	m_cameraPanMax = 350;
	m_cameraPanSpd = 2.5;
	m_isCameraTurning = false;
	backG = &bg;
	backF = &fg;

	// Background
	GameObject* temp;

	//Sky
	backG->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "sky1" }));
	temp->AddComponent(new Background(c_mountainSpeedM/2,
		uthEngine.GetWindow().GetSize().y - 740, 0, true,
		"backgrounds/sky.png"));
	backG->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "sky1" }));
	temp->AddComponent(new Background(c_mountainSpeedM/2,
		uthEngine.GetWindow().GetSize().y - 740, 0, false,
		"backgrounds/sky.png"));

	//Mountains
	backG->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "mountain1" }));
	temp->AddComponent(new Background(c_mountainSpeedM,
		uthEngine.GetWindow().GetSize().y - 570, 0.5, true,
		"backgrounds/mountains01.png"));
	backG->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "mountain2" }));
	temp->AddComponent(new Background(c_mountainSpeedM,
		uthEngine.GetWindow().GetSize().y - 570, 0.5, false,
		"backgrounds/mountains02.png"));

	//Backcity
	backG->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "building3" }));
	temp->AddComponent(new Background(c_backSpeedM / 1.2f,
		uthEngine.GetWindow().GetSize().y - 480, 2, true,
		"backgrounds/buildings01.png"));
	backG->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "building4" }));
	temp->AddComponent(new Background(c_backSpeedM / 1.2f,
		uthEngine.GetWindow().GetSize().y - 480, 2, false,
		"backgrounds/buildings01.png"));

	backG->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "building1" }));
	temp->AddComponent(new Background(c_backSpeedM,
		uthEngine.GetWindow().GetSize().y - 480, 2,true,
		"backgrounds/buildings02.png"));
	backG->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "building2" }));
	temp->AddComponent(new Background(c_backSpeedM,
		uthEngine.GetWindow().GetSize().y - 480, 2, false,
		"backgrounds/buildings02.png"));

	//Frontcity
	backF->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "lantern1" }));
	temp->AddComponent(new Background(c_frontSpeedM,
		uthEngine.GetWindow().GetSize().y - 120, 4, true,
		"backgrounds/lanterns.png"));
	backF->AddChild(temp = new GameObject(std::vector<std::string>{ "bg", "lantern2" }));
	temp->AddComponent(new Background(c_frontSpeedM,
		uthEngine.GetWindow().GetSize().y - 120, 4, false,
		"backgrounds/lanterns.png"));

	return true;
}
void BackgroundManager::Update(float dt)
{
	CameraMovement(dt);

}
void BackgroundManager::CameraMovement(float dt)
{
	m_camera = &uthEngine.GetWindow().GetCamera();

	if (m_camShakeAmount > 0)
	{
		m_camShakeAmount -= dt;
		m_camera->transform.SetRotation(Randomizer::GetFloat(-m_camShakeAmount, m_camShakeAmount));
	}
	else
	{
		m_camera->transform.SetRotation(0);
	}

	m_camera->SetPosition(m_cameraPan, m_cameraStartPos.y);
	if (!m_isCameraTurning)
	{
		m_isCameraTurning = true;
		m_cameraPan = 0;
	}
	//Change direction depending where player is looking
	if (Player::isGoingRight)
	{
		m_cameraPan += dt*m_cameraPanSpd * ((m_cameraStartPos.x + m_cameraPanMax) - m_camera->GetPosition().x);
	}
	else
	{
		m_cameraPan += dt*m_cameraPanSpd * ((m_cameraStartPos.x - m_cameraPanMax) - m_camera->GetPosition().x);
	}
}
void BackgroundManager::SetCameraStartPos(pmath::Vec2 pos)
{
	m_cameraStartPos = pos;
	uthEngine.GetWindow().GetCamera().SetPosition(pos);
}
void BackgroundManager::Shake(float amount, float delay)
{

	auto childrenF = backF->Children("bg");
	auto childrenG = backG->Children("bg");

	//Set amount and delay to backgrounds
	for (auto& e : childrenF)
	{
		auto fg = static_cast<GameObject*>(e.get());
		fg->GetComponent<Background>()->Shake(amount);
	}
	for (auto& e : childrenG)
	{
		auto bg = static_cast<GameObject*>(e.get());
		bg->GetComponent<Background>()->Shake(amount);
	}
	m_camShakeAmount = amount*0.4f;
}
BackgroundManager::~BackgroundManager()
{
	DeInit();
}

void BackgroundManager::DeInit()
{

}<|endoftext|>