Example #1
0
func InitializePlayer(int plr)
{
	var i;
	// Script player owns power crystals
	if (GetPlayerType(plr) == C4PT_Script)
	{
		g_crystal_player = plr;
		for (i=0; i<GetPlayerCount(C4PT_User); ++i) SetHostility(plr, GetPlayerByIndex(i, C4PT_User), true, true, true);
		while (GetCrew(plr)) GetCrew(plr)->RemoveObject();
		InitPowerCrystals(plr);
		return true;
	}
	if (g_crystal_player != NO_OWNER) SetHostility(g_crystal_player, plr, true, true, true);
	// First player init base
	if (!g_was_player_init)
	{
		CreateScriptPlayer("POMMES", 0, 0, CSPF_FixedAttributes | CSPF_NoEliminationCheck | CSPF_Invisible);
		InitBase(plr);
		g_was_player_init = true;
	}
	// Position and materials
	var crew;
	for (i=0; crew=GetCrew(plr,i); ++i)
	{
		crew->SetPosition(2100+Random(40), 233-10);
		crew->CreateContents(Shovel);
	}
	return true;
}
//	初期化
void CMglDirectInputDeviceBase::Init( REFGUID rguid, LPCDIDATAFORMAT dataFormat, int nStateBufSize, HWND hWnd, DWORD dwCooperativeFlag )
{
	//	基底初期化
	InitBase();

	//	デフォルトのhWnd取得
	if ( hWnd == NULL )
		hWnd = GetDefaultHwnd();

	MyuAssert( m_pDi->CreateDevice( rguid, &m_pDevice, NULL ), DI_OK,
		"CMglDirectInputDeviceBase::Init  m_pDi->CreateDevice()に失敗" );

	MyuAssert( m_pDevice->SetDataFormat( dataFormat ), DI_OK,
		"CMglDirectInputDeviceBase::Init  m_pDevice->SetDataFormat()に失敗" );
    
	MyuAssert( m_pDevice->SetCooperativeLevel( hWnd, dwCooperativeFlag ), DI_OK,
		"CMglDirectInputDeviceBase::Init  m_pDevice->SetCooperativeLevel()に失敗" );

	//	ステートバッファ確保
	m_pStateBuf = new BYTE[nStateBufSize];
	m_pStateBuf2 = new BYTE[nStateBufSize];
	m_nStateBufSize = nStateBufSize;
	ZeroMemory(m_pStateBuf,nStateBufSize);		//	2008/06/29  初期化してなかったんですけど!!
	ZeroMemory(m_pStateBuf2,nStateBufSize);

	Acquire();

	m_hWnd = hWnd;
}
Example #3
0
func InitializePlayer(int plr)
{
	// Harsh zoom range
	for (var flag in [PLRZOOM_LimitMax, PLRZOOM_Direct])
		SetPlayerZoomByViewRange(plr,500,350,flag);
	SetPlayerViewLock(plr, true);
	// First player init base
	if (!g_was_player_init)
	{
		InitBase(plr);
		g_was_player_init = true;
	}
	// Position and materials
	var i, crew;
	for (i=0; crew=GetCrew(plr,i); ++i)
	{
		crew->SetPosition(100+Random(80), 192-10);
		crew->CreateContents(Shovel);
		if (!i)
		{
			crew->CreateContents(Hammer);
		}
		else if (i==1)
		{
			crew->CreateContents(Axe);
		}
	}
	return true;
}
void UIpConnection::InitLocalConnection(UNetDriver* InDriver, class FSocket* InSocket, const FURL& InURL, EConnectionState InState, int32 InMaxPacket, int32 InPacketOverhead)
{
	InitBase(InDriver, InSocket, InURL, InState, 
		// Use the default packet size/overhead unless overridden by a child class
		(InMaxPacket == 0 || InMaxPacket > MAX_PACKET_SIZE) ? MAX_PACKET_SIZE : InMaxPacket,
		InPacketOverhead == 0 ? UDP_HEADER_SIZE : InPacketOverhead);

	// Figure out IP address from the host URL
	bool bIsValid = false;
	// Get numerical address directly.
	RemoteAddr = InDriver->GetSocketSubsystem()->CreateInternetAddr();
	RemoteAddr->SetIp(*InURL.Host, bIsValid);
	RemoteAddr->SetPort(InURL.Port);

	// Try to resolve it if it failed
	if (bIsValid == false)
	{
		// Create thread to resolve the address.
		ResolveInfo = InDriver->GetSocketSubsystem()->GetHostByName(TCHAR_TO_ANSI(*InURL.Host));
		if (ResolveInfo == NULL)
		{
			Close();
			UE_LOG(LogNet, Verbose, TEXT("IpConnection::InitConnection: Unable to resolve %s"), *InURL.Host);
		}
	}

	// Initialize our send bunch
	InitSendBuffer();
}
Example #5
0
awxToolbar::awxToolbar(wxWindow* parent,
		   wxWindowID id) :
    wxWindow(parent,id,
		   wxDefaultPosition,wxSize(20,20),
		   wxNO_FULL_REPAINT_ON_RESIZE)
{
    InitBase();
};
Example #6
0
Terrain::Terrain(Eigen::Vector2f a_size, Eigen::Vector2i a_res, int n_hill, TerrainType a_type){
	m_type = TypeTerrain;
	m_frictness = 10;
	
	InitBase(a_size.x(), a_size.y(), a_res.x(), a_res.y(), n_hill, a_type);

	InitDraw();
}
Example #7
0
int main()
{
    if(!InitBase(TEXT("ScriptCompiler")))
        return 0;

    TerminateBase();

    return 0;
}
Example #8
0
BOOL ReadAsync(PIOAsyncDev ah, LARGE_INTEGER offset, LPVOID buffer, DWORD length, PCallback cb, LPVOID ctx) {
	PIOBaseOper aop = (PIOBaseOper)malloc(sizeof(IOBaseOper));
	
	InitBase(aop, ah, cb, ctx, TransferAsyncCompleteAction);
	ah->ovr.Offset = offset.LowPart; ah->ovr.OffsetHigh = offset.HighPart;

	if (!ReadFile(ah->dev, buffer, length, NULL, &ah->ovr) &&
		GetLastError() != ERROR_IO_PENDING) return FALSE;
	return TRUE;
}
Example #9
0
BOOL WriteAsync(PIOAsyncDev asyncDev, LARGE_INTEGER offset, LPVOID buffer, DWORD length, PCallback cb, LPVOID ctx) {
	PIOBaseOper baseOp = (PIOBaseOper)malloc(sizeof(IOBaseOper));

	InitBase(baseOp, asyncDev, cb, ctx, AsyncCompleteAction);
	asyncDev->ovr.Offset = offset.LowPart; asyncDev->ovr.OffsetHigh = offset.HighPart;

	if (!WriteFile(asyncDev->dev, buffer, length,NULL,&asyncDev->ovr) && GetLastError() != ERROR_IO_PENDING ) 
		return FALSE;
	return TRUE;
}
Example #10
0
S0MeterTCP::S0MeterTCP(const int ID, const std::string &IPAddress, const unsigned short usIPPort):
	m_szIPAddress(IPAddress)
{
	m_HwdID=ID;
	m_bDoRestart=false;
	m_stoprequested=false;
	m_usIPPort=usIPPort;
	m_retrycntr = S0METER_RETRY_DELAY;
	InitBase();
}
Example #11
0
bool UIpNetDriver::InitListen( FNetworkNotify* InNotify, FURL& LocalURL, bool bReuseAddressAndPort, FString& Error )
{
	if( !InitBase( false, InNotify, LocalURL, bReuseAddressAndPort, Error ) )
	{
		return false;
	}

	// Update result URL.
	//LocalURL.Host = LocalAddr->ToString(false);
	LocalURL.Port = LocalAddr->GetPort();
	UE_LOG(LogNet, Log, TEXT("%s IpNetDriver listening on port %i"), *GetDescription(), LocalURL.Port );

	return true;
}
bool AOnlineBeaconClient::InitClient(FURL& URL)
{
	bool bSuccess = false;

	if(URL.Valid)
	{
		if (InitBase() && NetDriver)
		{
			FString Error;
			if (NetDriver->InitConnect(this, URL, Error))
			{
				BeaconConnection = NetDriver->ServerConnection;

				// Kick off the connection handshake
				if (BeaconConnection->StatelessConnectComponent.IsValid())
				{
					BeaconConnection->StatelessConnectComponent.Pin()->SendInitialConnect();
				}

				SetConnectionState(EBeaconConnectionState::Pending);

				NetDriver->SetWorld(GetWorld());
				NetDriver->Notify = this;
				NetDriver->InitialConnectTimeout = BeaconConnectionInitialTimeout;
				NetDriver->ConnectionTimeout = BeaconConnectionTimeout;

				// Send initial message.
				uint8 IsLittleEndian = uint8(PLATFORM_LITTLE_ENDIAN);
				check(IsLittleEndian == !!IsLittleEndian); // should only be one or zero

				uint32 LocalNetworkVersion = FNetworkVersion::GetLocalNetworkVersion();
				
				FNetControlMessage<NMT_Hello>::Send(NetDriver->ServerConnection, IsLittleEndian, LocalNetworkVersion);
				NetDriver->ServerConnection->FlushNet();

				bSuccess = true;
			}
			else
			{
				// error initializing the network stack...
				UE_LOG(LogBeacon, Log, TEXT("AOnlineBeaconClient::InitClient failed"));
				SetConnectionState(EBeaconConnectionState::Invalid);
				OnFailure();
			}
		}
	}

	return bSuccess;
}
Example #13
0
bool UDemoNetDriver::InitListen( FNetworkNotify* InNotify, FURL& ListenURL, bool bReuseAddressAndPort, FString& Error )
{
	if ( !InitBase( false, InNotify, ListenURL, bReuseAddressAndPort, Error ) )
	{
		return false;
	}

	check( World != NULL );

	class AWorldSettings * WorldSettings = World->GetWorldSettings();

	if ( !WorldSettings )
	{
		Error = TEXT( "No WorldSettings!!" );
		return false;
	}

	// Recording, local machine is server, demo stream acts "as if" it's a client.
	UDemoNetConnection* Connection = ConstructObject<UDemoNetConnection>( UDemoNetConnection::StaticClass() );
	Connection->InitConnection( this, USOCK_Open, ListenURL, 1000000 );
	Connection->InitSendBuffer();

	FileAr = IFileManager::Get().CreateFileWriter( *DemoFilename );
	ClientConnections.Add( Connection );

	if( !FileAr )
	{
		Error = FString::Printf( TEXT("Couldn't open demo file %s for writing"), *DemoFilename );//@todo demorec: localize
		return false;
	}

	// use the same byte format regardless of platform so that the demos are cross platform
	//@note: swap on non console platforms as the console archives have byte swapping compiled out by default
	//FileAr->SetByteSwapping(true);

	FNetworkDemoHeader DemoHeader;

	// NOTE - This must be the SAME string we write when we close the demo or it will throw the header off
	DemoHeader.LevelName = World->GetCurrentLevel()->GetOutermost()->GetName();

	// Write the initial header (a lot of the fields will be placeholder until we fill them in later)
	(*FileAr) << DemoHeader;

	// Spawn the demo recording spectator.
	SpawnDemoRecSpectator( Connection );

	return true;
}
Example #14
0
BOOLEAN BASE_init(void)
{
  devInit();
  rwibase_handlers = CreateHandlerList(BASE_NUMBER_EVENTS);
  if(InitDevice()) {
    InitBase();
    BASE_Halt();
    //    BASE_TranslateVelocity(init_trans_speed);
    //    BASE_RotateVelocity(init_rot_speed);
    BASE_reset();
    BASE_EnableStopWhenBump();
    return TRUE;
  }
  else
    return FALSE;
}
Example #15
0
bool UIpNetDriver::InitConnect( FNetworkNotify* InNotify, const FURL& ConnectURL, FString& Error )
{
	if( !InitBase( true, InNotify, ConnectURL, false, Error ) )
	{
		return false;
	}

	// Create new connection.
	ServerConnection = ConstructObject<UNetConnection>(NetConnectionClass);
	ServerConnection->InitLocalConnection( this, Socket, ConnectURL, USOCK_Pending);
	UE_LOG(LogNet, Log, TEXT("Game client on port %i, rate %i"), ConnectURL.Port, ServerConnection->CurrentNetSpeed );

	// Create channel zero.
	GetServerConnection()->CreateChannel( CHTYPE_Control, 1, 0 );

	return true;
}
Example #16
0
bool CScript::Open( LPCTSTR pszFilename, UINT wFlags )
{
	ADDTOCALLSTACK("CScript::Open");
	// If we are in read mode and we have no script file.
	// ARGS: wFlags = OF_READ, OF_NONCRIT etc
	// RETURN: true = success.

	InitBase();

	if ( pszFilename == NULL )
	{
		pszFilename = GetFilePath();
	}
	else
	{
		SetFilePath( pszFilename );
	}

	LPCTSTR pszTitle = GetFileTitle();
	if ( pszTitle == NULL || pszTitle[0] == '\0' )
		return( false );

	LPCTSTR pszExt = GetFilesExt( GetFilePath() ); 
	if ( pszExt == NULL )
	{
		TCHAR szTemp[ _MAX_PATH ];
		strcpy( szTemp, GetFilePath() );
		strcat( szTemp, GRAY_SCRIPT );
		SetFilePath( szTemp );
		wFlags |= OF_TEXT;
	}

	if ( !PhysicalScriptFile::Open( GetFilePath(), wFlags ))
	{
		if ( ! ( wFlags & OF_NONCRIT ))
		{
			g_Log.Event(LOGL_WARN, "'%s' not found...\n", static_cast<LPCTSTR>(GetFilePath()));
		}
		return( false );
	}

	return( true );
}
int CRoleDBThread::Initialize(bool bResume, const int iThreadIdx)
{
	int iRt = 0;

	//初始化线程id
	m_iThreadIdx = iThreadIdx;	

	iRt = InitBase();
	if (iRt != 0)
	{
		return -1;
	}

	//init codequeue
	iRt = InitCodeQueue(bResume, iThreadIdx);
	if (iRt != 0)
	{
		return -4;
	}

	iRt = m_stProtocolEngine.Initialize(iThreadIdx);
	if (iRt != 0)
	{
		return -6;
	}

	iRt = m_stRoleDBHandlerSet.Initialize(iThreadIdx);
	if (iRt != 0)
	{
		return -9;
	}

	//create thread
	iRt = CreateThread();
	if (iRt != 0)
	{
		return -12;
	}
		
	return 0;
}
Example #18
0
WidgetEditor::WidgetEditor(int w, int h, const char* rootpath)
	: GApp<GEngine_SDL>(w, h, rootpath)
	, m_pRootWin(NULL)
	, m_pMainWin(NULL)
	, m_pEditWin(NULL)
	, m_bEditMode(false)
	, m_pNearestSide(NULL)
	, m_pHoverWidget(NULL)
	, m_pSelectedWidget(NULL)
{
	m_pEngine->SetPrintFont("Arial.ttf", 14);

	m_pRootWin = new Widget(*m_pEngine, Widget::Desc(), 0, "root");

	m_pMainWin = new WBackground(*m_pRootWin, WBackground::Desc("bg.png"), 0, "main");
	m_pRootWin->InsertChild(m_pMainWin);
	//m_pMainWin = new WDebug(m_oGEngine, WDebug::Desc(), 0, "main");
	//m_pMainWin->SetOrigX(50);
	//m_pMainWin->SetOrigY(50);

	m_pMainWin->SetSideProp(SideEnum::Left,		WidgetSide::ParentRef(0.f, 10));
	m_pMainWin->SetSideProp(SideEnum::Right,	WidgetSide::BrotherRef(1, 0.f, 0));
	m_pMainWin->SetSideProp(SideEnum::Top,		WidgetSide::ParentRef(0.f, 10));
	m_pMainWin->SetSideProp(SideEnum::Bottom,	WidgetSide::ParentRef(1.f, -10));

	WBackground* pEditBack = new WBackground(*m_pRootWin, WBackground::Desc("bg.png"), 1, "editback");
	m_pRootWin->InsertChild(pEditBack);
	pEditBack->SetSideProp(SideEnum::Left,		WidgetSide::ParentRef(1.f, -200));
	pEditBack->SetSideProp(SideEnum::Right,		WidgetSide::ParentRef(1.f, -10));
	pEditBack->SetSideProp(SideEnum::Top,		WidgetSide::ParentRef(0.f, 10));
	pEditBack->SetSideProp(SideEnum::Bottom,	WidgetSide::ParentRef(1.f, -10));

	m_pEditWin = pEditBack->AddNewChild<EWSimpleWindow>(EWSimpleWindow::Desc("window.png", 12), 0, "edit");
	m_pEditWin->SetSideProp(SideEnum::Left,		WidgetSide::ParentRef(0.f, 0));
	m_pEditWin->SetSideProp(SideEnum::Right,	WidgetSide::ParentRef(1.f, 0));
	m_pEditWin->SetSideProp(SideEnum::Top,		WidgetSide::ParentRef(0.f, 0));
	m_pEditWin->SetSideProp(SideEnum::Bottom,	WidgetSide::ParentRef(1.f, 0));

	InitBase();
}
void Python::init()
{
    static bool isinit = false;
    if (isinit)
        return;
    isinit = true;
//initialize python library
    Py_NoSiteFlag = 1;

// These functions add these modules to the builtin package
    InitVS();
    InitBriefing();
    InitBase();
    InitDirector();

// Now we can do python things about them and initialize them
    Py_Initialize();
    initpaths();

#if BOOST_VERSION != 102800
    boost::python::converter::registry::insert( Vector_convertible, QVector_construct, boost::python::type_id< QVector > () );
    boost::python::converter::registry::insert( Vector_convertible, Vector_construct, boost::python::type_id< Vector > () );
#endif
#if (PY_VERSION_HEX < 0x03000000)
    InitBriefing2();
    InitVS2();
#endif
    VSFileSystem::vs_fprintf( stderr, "testing VS random" );
    std::string changepath( "import sys\nprint(sys.path)\n" );
    VSFileSystem::vs_fprintf( stderr, "running %s", changepath.c_str() );
    char *temppython = strdup( changepath.c_str() );
    PyRun_SimpleString( temppython );
    Python::reseterrors();
    free( temppython );
#if (PY_VERSION_HEX < 0x03000000)
    InitDirector2();
    InitBase2();
#endif
}
void UIpConnection::InitRemoteConnection(UNetDriver* InDriver, class FSocket* InSocket, const FURL& InURL, const class FInternetAddr& InRemoteAddr, EConnectionState InState, int32 InMaxPacket, int32 InPacketOverhead)
{
	InitBase(InDriver, InSocket, InURL, InState, 
		// Use the default packet size/overhead unless overridden by a child class
		(InMaxPacket == 0 || InMaxPacket > MAX_PACKET_SIZE) ? MAX_PACKET_SIZE : InMaxPacket,
		InPacketOverhead == 0 ? UDP_HEADER_SIZE : InPacketOverhead);

	// Copy the remote IPAddress passed in
	bool bIsValid = false;
	FString IpAddrStr = InRemoteAddr.ToString(false);
	RemoteAddr = InDriver->GetSocketSubsystem()->CreateInternetAddr();
	RemoteAddr->SetIp(*IpAddrStr, bIsValid);
	RemoteAddr->SetPort(InRemoteAddr.GetPort());

	URL.Host = RemoteAddr->ToString(false);

	// Initialize our send bunch
	InitSendBuffer();

	// This is for a client that needs to log in, setup ClientLoginState and ExpectedClientLoginMsgType to reflect that
	SetClientLoginState( EClientLoginState::LoggingIn );
	SetExpectedClientLoginMsgType( NMT_Hello );
}
bool AOnlineBeaconHost::InitHost()
{
    FURL URL(NULL, TEXT(""), TRAVEL_Absolute);

    // Allow the command line to override the default port
    int32 PortOverride;
    if (FParse::Value(FCommandLine::Get(), TEXT("BeaconPort="), PortOverride) && PortOverride != 0)
    {
        ListenPort = PortOverride;
    }

    URL.Port = ListenPort;
    if(URL.Valid)
    {
        if (InitBase() && NetDriver)
        {
            FString Error;
            if (NetDriver->InitListen(this, URL, false, Error))
            {
                ListenPort = URL.Port;
                NetDriver->SetWorld(GetWorld());
                NetDriver->Notify = this;
                NetDriver->InitialConnectTimeout = BEACON_CONNECTION_TIMEOUT;
                NetDriver->ConnectionTimeout = BEACON_CONNECTION_TIMEOUT;
                return true;
            }
            else
            {
                // error initializing the network stack...
                UE_LOG(LogNet, Log, TEXT("AOnlineBeaconHost::InitHost failed"));
                OnFailure();
            }
        }
    }

    return false;
}
Example #22
0
bool UDemoNetDriver::InitListen( FNetworkNotify* InNotify, FURL& ListenURL, bool bReuseAddressAndPort, FString& Error )
{
	if ( !InitBase( false, InNotify, ListenURL, bReuseAddressAndPort, Error ) )
	{
		return false;
	}

	check( World != NULL );

	class AWorldSettings * WorldSettings = World->GetWorldSettings();

	if ( !WorldSettings )
	{
		Error = TEXT( "No WorldSettings!!" );
		return false;
	}

	// Recording, local machine is server, demo stream acts "as if" it's a client.
	UDemoNetConnection* Connection = ConstructObject<UDemoNetConnection>( UDemoNetConnection::StaticClass() );
	Connection->InitConnection( this, USOCK_Open, ListenURL, 1000000 );
	Connection->InitSendBuffer();

	FileAr = IFileManager::Get().CreateFileWriter( *DemoFilename );
	ClientConnections.Add( Connection );

	if( !FileAr )
	{
		Error = FString::Printf( TEXT("Couldn't open demo file %s for writing"), *DemoFilename );//@todo demorec: localize
		return false;
	}

	// use the same byte format regardless of platform so that the demos are cross platform
	//@note: swap on non console platforms as the console archives have byte swapping compiled out by default
	//FileAr->SetByteSwapping(true);

	// write engine version info
	int32 EngineVersion = GEngineNetVersion;
	(*FileAr) << EngineVersion;

	// write placeholder for total frames - will be updated when the demo is stopped
	PlaybackTotalFrames = 0;
	(*FileAr) << PlaybackTotalFrames;

#if 0
	// Create the control channel.
	Connection->CreateChannel( CHTYPE_Control, 1, 0 );

	// Send initial message.
	uint8 IsLittleEndian = uint8( PLATFORM_LITTLE_ENDIAN );
	check( IsLittleEndian == !!IsLittleEndian ); // should only be one or zero
	FNetControlMessage<NMT_Hello>::Send( Connection, IsLittleEndian, GEngineMinNetVersion, GEngineNetVersion, Cast<UGeneralProjectSettings>(UGeneralProjectSettings::StaticClass()->GetDefaultObject())->ProjectID );
	Connection->FlushNet();

	// WelcomePlayer will send the needed map name
	World->WelcomePlayer( Connection );
#else
	// Bypass UDemoPendingNetLevel
	FString LevelName = World->GetCurrentLevel()->GetOutermost()->GetName();
	(*FileAr) << LevelName;
#endif

	// Save out any levels that are in the streamed level list
	// This needs some work, but for now, to try and get games that use heavy streaming working
	int32 NumStreamingLevels = 0;

	for ( int32 i = 0; i < World->StreamingLevels.Num(); ++i )
	{
		if ( World->StreamingLevels[i] != NULL )
		{
			NumStreamingLevels++;
		}
	}

	(*FileAr) << NumStreamingLevels;

	for ( int32 i = 0; i < World->StreamingLevels.Num(); ++i )
	{
		if ( World->StreamingLevels[i] != NULL )
		{
			FString PackageName = World->StreamingLevels[i]->GetWorldAssetPackageName();
			FString PackageNameToLoad = World->StreamingLevels[i]->PackageNameToLoad.ToString();

			UE_LOG( LogDemo, Log, TEXT( "  StreamingLevel: %s, %s" ), *PackageName, *PackageNameToLoad );

			(*FileAr) << PackageName;
			(*FileAr) << PackageNameToLoad;
			(*FileAr) << World->StreamingLevels[i]->LevelTransform;
		}
	}

	// Spawn the demo recording spectator.
	SpawnDemoRecSpectator( Connection );

	DemoDeltaTime = 0;
	LastRecordTime = 0;

	return true;
}
Example #23
0
VOID InitCopyFolderOper(PCopyFolderOper cpOper, PCallback cb, LPVOID ctx) {
	// uma vez que se trata de uma operação composta, que não lida
	// directamente com devices, não tem device nem complete action associadas
	InitBase(&cpOper->base, NULL, cb, ctx, NULL);
	cpOper->remainingFiles = 1;
}
/**
* Update cycle
*
* Checks for keypresses:
*   - Esc - Quits the game
*   - Left - Rotates ship left
*   - Right - Rotates ship right
*   - Up - Accelerates the ship
*   - Down - Deccelerates the ship
*
* Also calls Update() on all the ships in the universe
*/
bool Application::Update()
{
	float timedelta = hge_->Timer_GetDelta();
	if (bulletShootTimer < S_BULLET_SHOOT_INTERVAL)
	{
		bulletShootTimer += timedelta;
	}
	if (missileShootTimer < S_MISSILE_SHOOT_INTERVAL)
	{
		missileShootTimer += timedelta;
	}

	ships_.at(0)->SetAngularVelocity(0.0f);

	// Lab 13 Task 4 : Add a key to shoot missiles
	/*if (hge_->Input_GetKeyState(HGEK_ENTER))
	{
		if (!keydown_enter)
		{
			CreateMissile(ships_.at(0)->GetX(), ships_.at(0)->GetY(), ships_.at(0)->GetW(), ships_.at(0)->GetID());
			keydown_enter = true;
		}
	}
	else
	{
		if (keydown_enter)
		{
			keydown_enter = false;
		}
	}*/

	static const float MAX_ENTER_TIMER = 0.5f;
	static float enterTimer;

	if (enterTimer < MAX_ENTER_TIMER)
	{
		enterTimer += timedelta;
	}

	// Chat
	if (chatMode)
	{
		char input = hge_->Input_GetKey();

		if (input == HGEK_ESCAPE)
		{
			chatMode = false;
			typingMsg = "";
		}
		else if (input == HGEK_ENTER && enterTimer >= MAX_ENTER_TIMER)
		{
			// Send
			if (typingMsg != "")
			{
				RakNet::BitStream chatBS;
				chatBS.Write((unsigned char)ID_CHAT_SEND);
				chatBS.Write(typingMsg.c_str());
				rakpeer_->Send(&chatBS, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
				chatList.push_back(typingMsg);
			}

			// Reset
			chatMode = false;
			typingMsg = "";
			enterTimer = 0.f;
			chatShowTimer = 5.f;
		}
		else if (input >= 32 && input <= 126)
		{
			typingMsg += input;
		}
	}
	else
	{
		if (chatShowTimer > 0.f)
		{
			chatShowTimer -= timedelta;
		}

		if (hge_->Input_GetKeyState(HGEK_ENTER) && enterTimer >= MAX_ENTER_TIMER)
		{
			chatMode = true;
			enterTimer = 0.f;
		}

		// Ship controls
		if (hge_->Input_GetKeyState(HGEK_LEFT))
		{
			ships_.at(0)->SetAngularVelocity(ships_.at(0)->GetAngularVelocity() - DEFAULT_ANGULAR_VELOCITY);
		}

		if (hge_->Input_GetKeyState(HGEK_RIGHT))
		{
			ships_.at(0)->SetAngularVelocity(ships_.at(0)->GetAngularVelocity() + DEFAULT_ANGULAR_VELOCITY);
		}

		if (hge_->Input_GetKeyState(HGEK_UP))
		{
			ships_.at(0)->Accelerate(DEFAULT_ACCELERATION, timedelta);
		}

		if (hge_->Input_GetKeyState(HGEK_DOWN))
		{
			ships_.at(0)->Accelerate(-DEFAULT_ACCELERATION, timedelta);
		}

		// Shooting
		if (hge_->Input_GetKeyState(HGEK_1))
		{
			if (missileShootTimer >= S_MISSILE_SHOOT_INTERVAL)
			{
				Shoot(Projectile::PROJ_SEEKING_MISSLE);
			}
		}
		if (hge_->Input_GetKeyState(HGEK_2))
		{
			if (bulletShootTimer >= S_BULLET_SHOOT_INTERVAL)
			{
				Shoot(Projectile::PROJ_BULLET);
			}
		}

		if (hge_->Input_GetKeyState(HGEK_ESCAPE))
		{
			return true;
		}
	}

	// Update all ships
	for (ShipList::iterator ship = ships_.begin();
	ship != ships_.end(); ship++)
	{
		(*ship)->Update(timedelta);

		//collisions
		/*if ((*ship) == ships_.at(0))
			checkCollisions((*ship));*/
	}

	// Lab 13 Task 5 : Updating the missile
	/*if (mymissile)
	{
		if (mymissile->Update(ships_, timedelta))
		{
			//havecollision
			delete mymissile;
			mymissile = 0;
		}
	}*/

	// Lab 13 Task 13 : Update network missiles
	/*for (MissileList::iterator missile = missiles_.begin(); missile != missiles_.end(); missile++)
	{
		if ((*missile)->Update(ships_, timedelta))
		{
			//havecollision
			delete*missile;
			missiles_.erase(missile);
			break;
		}
	}*/

	// Update enemies
	/*for (vector<Enemy*>::iterator it = enemyList.begin(); it != enemyList.end(); ++it)
	{
		Enemy* e = *it;
		if (e->GetActive())
		{
			bool reset = e->Update(timedelta);
			if (reset)
			{
				RakNet::BitStream bs;
				bs.Write((unsigned char)ID_DESTROY_ENEMY);
				bs.Write(e->GetID());
				rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
			}
		}
	}*/

	// Update projectile
	for (vector<Projectile*>::iterator it = projectileList.begin(); it != projectileList.end(); ++it)
	{
		Projectile* p = *it;
		if (/*p->GetOwner() == ships_.at(0) && */p->GetActive()) // Only update your own projectile
		{
			bool reset = p->Update(timedelta);
			RakNet::BitStream bs;
			if (reset)
			{
				DestroyProjectile(p);
				bs.Write((unsigned char)ID_DESTROY_PROJECTILE);
				bs.Write(p->GetID());
				rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
			}
			else
			{
				for (vector<Enemy*>::iterator it2 = enemyList.begin(); it2 != enemyList.end(); ++it2)
				{
					Enemy* e = *it2;
					if (e->GetActive())
					{
						bool collision = p->CollideWith(e);
						if (collision)
						{
							int newHP = e->Injure(p->GetDamage());
							if (newHP <= 0)
							{
								RakNet::BitStream bs;
								// Add score to player
								p->GetOwner()->AddScore(100);

								bs.Write((unsigned char)ID_UPDATE_SCORE);
								bs.Write(p->GetOwner()->GetID());
								bs.Write(p->GetOwner()->GetScore());
								rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);

								// Destroy enemy
								DestroyEnemy(e);

								// Send to server to destroy enemy
								bs.ResetWritePointer();
								bs.Write((unsigned char)ID_DESTROY_ENEMY);
								bs.Write(e->GetID());
								rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
							}
							else
							{
								// Send to server to injure enemy
								RakNet::BitStream bs;
								bs.ResetWritePointer();
								bs.Write((unsigned char)ID_INJURE_ENEMY);
								bs.Write(e->GetID());
								bs.Write(e->GetHP());
								rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
							}

							// Reset projectile
							DestroyProjectile(p);
							bs.ResetWritePointer();
							bs.Write((unsigned char)ID_DESTROY_PROJECTILE);
							bs.Write(p->GetID());
							rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
						}
					}
				}
				/*int max = projectileUpdateList.size();
				int count = 0;
				for (vector<Projectile*>::iterator it2 = projectileUpdateList.begin(); it2 != projectileUpdateList.end(); ++it2)
				{
					Projectile* p2 = *it2;
					if (p == p2)
					{
						break;
					}
					else
					{
						++count;
					}
				}
				if (count == max)
				{
					projectileUpdateList.push_back(p);
				}*/
				/*bs.Write((unsigned char)ID_UPDATE_PROJECTILE);
				bs.Write(p->GetID());
				bs.Write(p->GetActive());
				bs.Write(p->GetType());
				bs.Write(p->GetX());
				bs.Write(p->GetY());
				bs.Write(p->GetVelocityX());
				bs.Write(p->GetVelocityY());
				bs.Write(p->GetSpeed());
				bs.Write(p->GetDamage());
				bs.Write(p->GetOwner()->GetID());
				// Send target id if available
				if (p->GetTarget())
				{
					bs.Write(p->GetTarget()->GetID());
				}
				else
				{
					bs.Write(-1);
				}
				rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);*/
			}
		}
	}

	// Update explosions
	for (vector<Explosion*>::iterator it = explosionList.begin(); it != explosionList.end(); ++it)
	{
		Explosion* e = *it;
		if ( e->isActive())
		{
			e->Update(timedelta);
		}
	}

	// Update boom
	for (vector<Boom*>::iterator it = boomList.begin(); it != boomList.end(); ++it)
	{
		Boom* b = *it;
		if (b->isActive())
		{
			b->Update(timedelta);
		}
	}

	// Packet receive
	if (Packet* packet = rakpeer_->Receive())
	{
		RakNet::BitStream bs(packet->data, packet->length, false);
		
		unsigned char msgid = 0;
		RakNetTime timestamp = 0;

		bs.Read(msgid);

		if (msgid == ID_TIMESTAMP)
		{
			bs.Read(timestamp);
			bs.Read(msgid);
		}

		switch(msgid)
		{
		case ID_CONNECTION_REQUEST_ACCEPTED:
			{
				std::cout << "Connected to Server" << std::endl;
				SendScreenSize();
				InitEnemyList();
				InitExplosionList();
				InitBoomList();
				InitProjectileList();
				InitBackground();
				InitBase();
				InitScore();
				chatMsg = new hgeFont("font1.fnt");
				chatMsg->SetScale(1);
				
			}
			break;

		case ID_NO_FREE_INCOMING_CONNECTIONS:
		case ID_CONNECTION_LOST:
		case ID_DISCONNECTION_NOTIFICATION:
			std::cout << "Lost Connection to Server" << std::endl;
			rakpeer_->DeallocatePacket(packet);
			return true;

		case ID_WELCOME:
			{
				unsigned int shipcount, id;
				float x_, y_;
				int type_;
				std::string temp;
				char chartemp[5];

				bs.Read(id);
				ships_.at(0)->setID( id );
				bs.Read(shipcount);

				for (unsigned int i = 0; i < shipcount; ++ i)
				{
					bs.Read(id);
					bs.Read(x_);
					bs.Read(y_);
					bs.Read(type_);
					std::cout << "New Ship pos" << x_ << " " << y_ << std::endl;
					Ship* ship = new Ship(type_, x_, y_ ); 
					temp = "Ship ";
					temp += _itoa(id, chartemp, 10);
					ship->SetName(temp.c_str());
					ship->setID( id );
					ships_.push_back(ship);
				}

				for (vector<Enemy*>::iterator it = enemyList.begin(); it != enemyList.end(); ++it)
				{
					int id, hp;
					bool active;
					Enemy::ENEMY_TYPE type;
					float x, y, vel_x, vel_y, speed;
					bs.Read(id);
					bs.Read(active);
					bs.Read(type);
					bs.Read(x);
					bs.Read(y);
					bs.Read(vel_x);
					bs.Read(vel_y);
					bs.Read(speed);
					bs.Read(hp);
					Enemy* e = FindEnemyByID(id);
					if (e)
					{
						float w = CalcW(Vector2(vel_x, vel_y));
						/*if (speed != 0)
						{
							w = acosf(vel_x / speed);
						}
						else
						{
							w = 0.f;
						}*/
						e->Init(type, x, y, w, active);
						e->SetVelocityX(vel_x);
						e->SetVelocityY(vel_y);
						e->SetSpeed(speed);
						e->SetHP(hp);
					}
				}
				
				// Base hp
				bs.Read(base_hp);

				SendInitialPosition();
			}
			break;
		case ID_REJECT_PLAYER:
			{
				std::cout << "Rejected player" << std::endl;
				return true;
			}
			break;

		case ID_NEWSHIP:
			{
				unsigned int id;
				bs.Read(id);

				if( id == ships_.at(0)->GetID() )
				{
					// if it is me
					break;
				}
				else
				{
					float x_, y_;
					int type_;
					std::string temp;
					char chartemp[5];

					bs.Read( x_ );
					bs.Read( y_ );
					bs.Read( type_ );
					std::cout << "New Ship pos" << x_ << " " << y_ << std::endl;
					Ship* ship = new Ship(type_, x_, y_);
					temp = "Ship "; 
					temp += _itoa(id, chartemp, 10);
					ship->SetName(temp.c_str());
					ship->setID( id );
					ships_.push_back(ship);
				}

			}
			break;

		case ID_LOSTSHIP:
			{
				unsigned int shipid;
				bs.Read(shipid);
				for (ShipList::iterator itr = ships_.begin(); itr != ships_.end(); ++itr)
				{
					if ((*itr)->GetID() == shipid)
					{
						delete *itr;
						ships_.erase(itr);
						break;
					}
				}
			}
			break;

		case ID_INITIALPOS:
			break;

		case ID_MOVEMENT:
			{
				unsigned int shipid;
				float temp;
				float x,y,w;
				bs.Read(shipid);
				for (ShipList::iterator itr = ships_.begin(); itr != ships_.end(); ++itr)
				{
					if ((*itr)->GetID() == shipid)
					{
						// this portion needs to be changed for it to work
#ifdef INTERPOLATEMOVEMENT
						bs.Read(x);
						bs.Read(y);
						bs.Read(w);

						(*itr)->SetServerLocation( x, y, w ); 

						bs.Read(temp);
						(*itr)->SetServerVelocityX( temp );
						bs.Read(temp);
						(*itr)->SetServerVelocityY( temp );
						bs.Read(temp);
						(*itr)->SetAngularVelocity( temp );

						(*itr)->DoInterpolateUpdate();
#else
						bs.Read(x);
						bs.Read(y);
						bs.Read(w);
						(*itr)->setLocation( x, y, w ); 

						// Lab 7 Task 1 : Read Extrapolation Data velocity x, velocity y & angular velocity
						bs.Read(temp);
						(*itr)->SetVelocityX( temp );
						bs.Read(temp);
						(*itr)->SetVelocityY( temp );
						bs.Read(temp);
						(*itr)->SetAngularVelocity( temp );
#endif

						break;
					}
				}
			}
			break;

		case ID_COLLIDE:
			{
				unsigned int shipid;
				float x, y;
				bs.Read(shipid);
				
				if( shipid == ships_.at(0)->GetID() )
				{
					std::cout << "collided with someone!" << std::endl;
					bs.Read(x);
					bs.Read(y);
					ships_.at(0)->SetX( x );
					ships_.at(0)->SetY( y );
					bs.Read(x);
					bs.Read(y);
					ships_.at(0)->SetVelocityX( x );
					ships_.at(0)->SetVelocityY( y );
#ifdef INTERPOLATEMOVEMENT
					bs.Read(x);
					bs.Read(y);
					ships_.at(0)->SetServerVelocityX( x );
					ships_.at(0)->SetServerVelocityY( y );
#endif	
				}
			}
			break;


		// Lab 13 Task 10 : new cases to handle missile on application side
		case ID_NEWMISSILE:
			{
				float x, y, w;
				int id;
				bs.Read(id);
				bs.Read(x);
				bs.Read(y);
				bs.Read(w);
				missiles_.push_back(new Missile("missile.png", x, y, w, id));
			}
			break;
		case ID_UPDATEMISSILE:
			{
				float x, y, w;
				int id;
				char deleted;
				bs.Read(id);
				bs.Read(deleted);
				for (MissileList::iterator itr = missiles_.begin(); itr !=
					missiles_.end(); ++itr)
				{
					if ((*itr)->GetOwnerID() == id)
					{
						if (deleted == 1)
						{
							delete*itr;
							missiles_.erase(itr);
						}
						else
						{
							bs.Read(x);
							bs.Read(y);
							bs.Read(w);
							(*itr)->UpdateLoc(x, y, w);
							bs.Read(x);
							(*itr)->SetVelocityX(x);
							bs.Read(y);
							(*itr)->SetVelocityY(y);
						}
						break;
					}
				}
			}
			break;
		case ID_NEW_ENEMY:
			{
				int id, hp;
				Enemy::ENEMY_TYPE type;
				float x, y, vel_x, vel_y, speed;
				bs.Read(id);
				bs.Read(type);
				bs.Read(x);
				bs.Read(y);
				bs.Read(vel_x);
				bs.Read(vel_y);
				bs.Read(speed);
				bs.Read(hp);
				Enemy* e = FindEnemyByID(id);
				if (e)
				{
					float w = CalcW(Vector2(vel_x, vel_y));
					e->Init(type, x, y, w);
					e->SetVelocityX(vel_x);
					e->SetVelocityY(vel_y);
					e->SetSpeed(speed);
					e->SetHP(hp);
				}
			}
			break;
		case ID_UPDATE_ENEMY:
			{
				int id;
				bs.Read(id);
				Enemy* e = FindEnemyByID(id);
				if (e)
				{
					float x, y;
					bs.Read(x);
					bs.Read(y);
					e->SetX(x);
					e->SetY(y);
				}
			}
			break;
		case ID_INJURE_ENEMY:
			{
				int id, hp;
				bs.Read(id);
				Enemy* e = FindEnemyByID(id);
				if (e && e->GetActive())
				{
					bs.Read(hp);
					e->SetHP(hp);
				}
			}
			break;
		case ID_DESTROY_ENEMY:
			{
				int id;
				bs.Read(id);
				Enemy* e = FindEnemyByID(id);

				DestroyEnemy(e);
			}
			break;
		case ID_SHOOT:
			{
				int id, damage, owner, target;
				Projectile::PROJECTILE_TYPE type;
				float x, y, w, vel_x, vel_y, speed;
				bs.Read(id);

				Projectile* p = FindProjectileByID(id);
				if (p)
				{
					bs.Read(type);
					bs.Read(x);
					bs.Read(y);
					bs.Read(w);
					bs.Read(vel_x);
					bs.Read(vel_y);
					bs.Read(speed);
					bs.Read(damage);
					bs.Read(owner);
					bs.Read(target);
					
					Ship* sOwner = FindShipByID(owner);
					if (sOwner)
					{
						p->Init(sOwner, type, x, y, w);
						p->SetVelocityX(vel_x);
						p->SetVelocityY(vel_y);
						p->SetSpeed(speed);
						p->SetDamage(damage);
						if (target != -1)
						{
							Enemy* sTarget = FindEnemyByID(target);
							if (sTarget)
							{
								p->SetTarget(sTarget);
							}
						}
					}
				}
			}
			break;
		case ID_UPDATE_PROJECTILE:
			{
				int id, damage, owner, target;
				Projectile::PROJECTILE_TYPE type;
				float x, y, vel_x, vel_y, speed;
				bool active;
				bs.Read(id);

				Projectile* p = FindProjectileByID(id);
				if (p)
				{
					bs.Read(active);
					bs.Read(type);
					bs.Read(x);
					bs.Read(y);
					bs.Read(vel_x);
					bs.Read(vel_y);
					bs.Read(speed);
					bs.Read(damage);
					bs.Read(owner);
					bs.Read(target);

					Ship* sOwner = FindShipByID(owner);
					if (sOwner)
					{
						p->SetOwner(sOwner);
						p->SetType(type);
						p->SetX(x);
						p->SetY(y);
						p->SetActive(active);
						p->SetVelocityX(vel_x);
						p->SetVelocityY(vel_y);
						p->SetSpeed(speed);
						p->SetDamage(damage);
						if (target != -1)
						{
							Enemy* sTarget = FindEnemyByID(target);
							if (sTarget)
							{
								p->SetTarget(sTarget);
							}
						}
					}
				}
			}
			break;
		case ID_DESTROY_PROJECTILE:
			{
				int id;
				bs.Read(id);
				Projectile* p = FindProjectileByID(id);
				if (p && p->GetActive())
				{
					// Reset projectile
					//DestroyProjectile(p);
					p->Reset();
				}
			}
			break;
		case ID_UPDATE_BASE:
			{
				bs.Read(base_hp);
			}
			break;
		case ID_UPDATE_SCORE:
			{
				int id, score;
				bs.Read(id);
				Ship* s = FindShipByID(id);
				if (s)
				{
					bs.Read(score);
					s->SetScore(score);
				}
			}
			break;
		case ID_CHAT_SEND:
			{
				char cMsg[256];
				bs.Read(cMsg);
				chatList.push_back(cMsg);
				chatShowTimer = 5.f;
			}
			break;

		default:
			std::cout << "Unhandled Message Identifier: " << (int)msgid << std::endl;

		}
		rakpeer_->DeallocatePacket(packet);
	}

	if (base_hp <= 0)
	{
		return true;
	}

	// Send projectile updates
	/*static const int SYNCS_PER_SEC = 24;
	static const float TIME_PER_SYNC = 1 / SYNCS_PER_SEC;
	static float projSendTimer = TIME_PER_SYNC;
	if (projSendTimer < TIME_PER_SYNC)
	{
		projSendTimer += timedelta;
	}
	else
	{
		for (vector<Projectile*>::iterator it = projectileList.begin(); it != projectileList.end(); ++it)
		{
			Projectile* p = *it;
			if (p->GetActive() && p->GetOwner() == ships_.at(0))
			{
				RakNet::BitStream sendProj;
				sendProj.Write((unsigned char)ID_UPDATE_PROJECTILE);
				sendProj.Write(p->GetID());
				sendProj.Write(p->GetActive());
				sendProj.Write(p->GetType());
				sendProj.Write(p->GetX());
				sendProj.Write(p->GetY());
				sendProj.Write(p->GetVelocityX());
				sendProj.Write(p->GetVelocityY());
				sendProj.Write(p->GetSpeed());
				sendProj.Write(p->GetDamage());
				sendProj.Write(p->GetOwner()->GetID());
				// Send target id if available
				if (p->GetTarget())
				{
					sendProj.Write(p->GetTarget()->GetID());
				}
				else
				{
					sendProj.Write(-1);
				}
				rakpeer_->Send(&sendProj, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
				std::cout << p->GetX() << " | " << p->GetY() << std::endl;
			}
		}
		projSendTimer = 0.f;
	}*/

	// Send data
	float timeToSync = 1000 / 24; // Sync 24 times in a second (Millisecond)
	if (RakNet::GetTime() - timer_ > timeToSync)
	{
		timer_ = RakNet::GetTime(); // Store previous time
		RakNet::BitStream bs2;
		unsigned char msgid = ID_MOVEMENT;
		bs2.Write(msgid);

#ifdef INTERPOLATEMOVEMENT
		bs2.Write(ships_.at(0)->GetID());
		bs2.Write(ships_.at(0)->GetServerX());
		bs2.Write(ships_.at(0)->GetServerY());
		bs2.Write(ships_.at(0)->GetServerW());
		bs2.Write(ships_.at(0)->GetServerVelocityX());
		bs2.Write(ships_.at(0)->GetServerVelocityY());
		bs2.Write(ships_.at(0)->GetAngularVelocity());

#else
		bs2.Write(ships_.at(0)->GetID());
		bs2.Write(ships_.at(0)->GetX());
		bs2.Write(ships_.at(0)->GetY());
		bs2.Write(ships_.at(0)->GetW());
		// Lab 7 Task 1 : Add Extrapolation Data velocity x, velocity y & angular velocity
		bs2.Write(ships_.at(0)->GetVelocityX());
		bs2.Write(ships_.at(0)->GetVelocityY());
		bs2.Write(ships_.at(0)->GetAngularVelocity());
#endif

		rakpeer_->Send(&bs2, HIGH_PRIORITY, RELIABLE, 0, UNASSIGNED_SYSTEM_ADDRESS, true);


		// Lab 13 Task 11 : send missile update 
		/*if (mymissile)
		{
			RakNet::BitStream bs3;
			unsigned char msgid2 = ID_UPDATEMISSILE;
			unsigned char deleted = 0;
			bs3.Write(msgid2);
			bs3.Write(mymissile->GetOwnerID());
			bs3.Write(deleted);
			bs3.Write(mymissile->GetX());
			bs3.Write(mymissile->GetY());
			bs3.Write(mymissile->GetW());
			bs3.Write(mymissile->GetVelocityX());
			bs3.Write(mymissile->GetVelocityY());
			rakpeer_->Send(&bs3, HIGH_PRIORITY, UNRELIABLE_SEQUENCED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
		}*/

		// Send update projectile
		/*for (int i = 0; i < projectileUpdateList.size(); ++i)
		{
			Projectile* p = projectileList[i];
			if (p && p->GetActive())
			{
				RakNet::BitStream sendProj;
				sendProj.Write((unsigned char)ID_UPDATE_PROJECTILE);
				sendProj.Write(p->GetID());
				sendProj.Write(p->GetActive());
				sendProj.Write(p->GetType());
				sendProj.Write(p->GetX());
				sendProj.Write(p->GetY());
				sendProj.Write(p->GetVelocityX());
				sendProj.Write(p->GetVelocityY());
				sendProj.Write(p->GetSpeed());
				sendProj.Write(p->GetDamage());
				sendProj.Write(p->GetOwner()->GetID());
				// Send target id if available
				if (p->GetTarget())
				{
					sendProj.Write(p->GetTarget()->GetID());
				}
				else
				{
					sendProj.Write(-1);
				}
				rakpeer_->Send(&sendProj, HIGH_PRIORITY, RELIABLE_ORDERED, 0, UNASSIGNED_SYSTEM_ADDRESS, true);
			}
		}
		projectileUpdateList.clear();*/
	}

	return false;
}
Example #25
0
bool UDemoNetDriver::InitConnect( FNetworkNotify* InNotify, const FURL& ConnectURL, FString& Error )
{
	// handle default initialization
	if ( !InitBase( true, InNotify, ConnectURL, false, Error ) )
	{
		return false;
	}

	// open the pre-recorded demo file
	FileAr = IFileManager::Get().CreateFileReader( *DemoFilename );

	if ( !FileAr )
	{
		Error = FString::Printf( TEXT( "Couldn't open demo file %s for reading" ), *DemoFilename );
		UE_LOG( LogDemo, Error, TEXT( "UDemoNetDriver::InitConnect: %s" ), *Error );
		return false;
	}

	// Playback, local machine is a client, and the demo stream acts "as if" it's the server.
	ServerConnection = ConstructObject<UNetConnection>( UDemoNetConnection::StaticClass() );
	ServerConnection->InitConnection( this, USOCK_Pending, ConnectURL, 1000000 );

#if 1
	// Create fake control channel
	ServerConnection->CreateChannel( CHTYPE_Control, 1 );
#endif

	// use the same byte format regardless of platform so that the demos are cross platform
	// DEMO_FIXME: This is messing up for some reason, investigate
	//FileAr->SetByteSwapping( true );

	int32 EngineVersion = 0;
	(*FileAr) << EngineVersion;
	(*FileAr) << PlaybackTotalFrames;

	UE_LOG( LogDemo, Log, TEXT( "Starting demo playback with demo. Filename: %s, Frames: %i, Version %i" ), *DemoFilename, PlaybackTotalFrames, EngineVersion );

#if 1
	// Bypass UDemoPendingNetLevel
	FString LevelName;
	(*FileAr) << LevelName;

	FString LoadMapError;

	FURL DemoURL;
	DemoURL.Map = LevelName;

	FWorldContext * WorldContext = GEngine->GetWorldContextFromWorld( World );

	if ( WorldContext == NULL )
	{
		Error = FString::Printf( TEXT( "No world context" ), *DemoFilename );
		UE_LOG( LogDemo, Error, TEXT( "UDemoNetDriver::InitConnect: %s" ), *Error );
		return false;
	}

	World->DemoNetDriver = NULL;
	SetWorld( NULL );

	UDemoPendingNetGame * NewPendingNetGame = new UDemoPendingNetGame( FPostConstructInitializeProperties() );

	NewPendingNetGame->DemoNetDriver = this;

	WorldContext->PendingNetGame = NewPendingNetGame;

	if ( !GEngine->LoadMap( *WorldContext, DemoURL, NewPendingNetGame, LoadMapError ) )
	{
		Error = LoadMapError;
		UE_LOG( LogDemo, Error, TEXT( "UDemoNetDriver::InitConnect: LoadMap failed: failed: %s" ), *Error );
		return false;
	}

	SetWorld( WorldContext->World() );
	WorldContext->World()->DemoNetDriver = this;
	WorldContext->PendingNetGame = NULL;
#endif

	int32 NumStreamingLevels = 0;

	(*FileAr) << NumStreamingLevels;

	for ( int32 i = 0; i < NumStreamingLevels; ++i )
	{
		ULevelStreamingKismet* StreamingLevel = static_cast<ULevelStreamingKismet*>(StaticConstructObject(ULevelStreamingKismet::StaticClass(), GetWorld(), NAME_None, RF_NoFlags, NULL ) );

		StreamingLevel->bShouldBeLoaded		= true;
		StreamingLevel->bShouldBeVisible	= true;
		StreamingLevel->bShouldBlockOnLoad	= false;
		StreamingLevel->bInitiallyLoaded	= true;
		StreamingLevel->bInitiallyVisible	= true;

		FString PackageName;
		FString PackageNameToLoad;

		(*FileAr) << PackageName;
		(*FileAr) << PackageNameToLoad;
		(*FileAr) << StreamingLevel->LevelTransform;

		StreamingLevel->PackageNameToLoad = FName( *PackageNameToLoad );
		StreamingLevel->SetWorldAssetByPackageName( FName( *PackageName ) );

		GetWorld()->StreamingLevels.Add( StreamingLevel );

		UE_LOG( LogDemo, Log, TEXT( "  Loading streamingLevel: %s, %s" ), *PackageName, *PackageNameToLoad );
	}

	DemoDeltaTime = 0;

	return true;
}
Example #26
0
CScript::CScript()
{
	InitBase();
}
Example #27
0
CScript::CScript( LPCTSTR pszKey )
{
	InitBase();
	ParseKey(pszKey);
}
Example #28
0
CScript::CScript( LPCTSTR pszKey, LPCTSTR pszVal )
{
	InitBase();
	ParseKey( pszKey, pszVal );
}
Example #29
0
int ENGINEAPI EngineMain(TSTR *lp, int c)
{
    int exitcode=0;

    dwIconID = IDI_GAME;

    //ugh.
    //CoInitializeEx(NULL, 0);

    if(InitBase(TEXT("Game")))
    {
        DWORD newWidth, newHeight, newFreq;
        BOOL bUseFullscreen = AppConfig->GetInt(TEXT("Display"), TEXT("Fullscreen"));

        if(!bUseFullscreen)
        {
            DisplayMode currentMode;
            OSGetDisplaySettings(&currentMode);

            if(currentMode.dwBitsPerPixel != 32)
                ErrOut(TEXT("Your display settings must be set to 32bit mode."));
        }

        SS->SetEffectsVol(AppConfig->GetFloat(TEXT("Sound"), TEXT("EffectsVolume"), 1.0f));
        MM->SetVolume(AppConfig->GetFloat(TEXT("Sound"), TEXT("MusicVolume"), 1.0f));

        List<DisplayMode> DisplayModes;
        zero(&DisplayModes, 8);

        OSEnumDisplayModes(DisplayModes);

        newWidth  = AppConfig->GetInt(TEXT("Display"), TEXT("Width"));
        newHeight = AppConfig->GetInt(TEXT("Display"), TEXT("Height"));
        newFreq   = AppConfig->GetInt(TEXT("Display"), TEXT("Frequency"));

        BOOL bFoundDisplayMode = FALSE;
        DisplayMode mode;

        for(int i=0; i<DisplayModes.Num(); i++)
        {
            if( (DisplayModes[i].dwHeight == newHeight) &&
                (DisplayModes[i].dwWidth  == newWidth) )
            {
                if(DisplayModes[i].dwFrequency == newFreq)
                {
                    bFoundDisplayMode = TRUE;
                    mcpy(&mode, &DisplayModes[i], sizeof(DisplayMode));
                    break;
                }
            }
        }

        mode.dwBitsPerPixel = 32;

        if(!bFoundDisplayMode)
        {
            mode.dwFrequency = 60;
            mode.dwWidth     = 640;
            mode.dwHeight    = 480;
            Log(TEXT("Monitor does not support %dx%d resolution or doesn't support %d frequency"), newHeight, newWidth, newFreq);
        }

        SetResolution(mode, TRUE);

        if(bUseFullscreen)
            ToggleFullScreen();

        DisplayModes.Clear();

        float gamma      = AppConfig->GetFloat(TEXT("Display"), TEXT("Gamma"),      1.0f);
        float brightness = AppConfig->GetFloat(TEXT("Display"), TEXT("Brightness"), 1.0f);
        float contrast   = AppConfig->GetFloat(TEXT("Display"), TEXT("Contrast"),   1.0f);
        AdjustDisplayColors(gamma, brightness, contrast);

        GS->ClearColorBuffer();

        GameModule *module = (GameModule*)CreateFactoryObject(TEXT("MainGameModule"));
        if(!module)
            OSMessageBox(TEXT("Could not load the class 'MainGameModule'."));
        else
        {
            if(module->ModuleStartup(lp, c))
            {
                //loop
                exitcode = BaseLoop();

                module->ModuleExit();
            }

            DestroyObject(module);
        }

        TerminateBase();
    }

    //CoUninitialize();

    return 0;
}
Example #30
0
bool UDemoNetDriver::InitConnect( FNetworkNotify* InNotify, const FURL& ConnectURL, FString& Error )
{
	if ( GetWorld() == nullptr )
	{
		UE_LOG( LogDemo, Error, TEXT( "GetWorld() == nullptr" ) );
		return false;
	}

	if ( GetWorld()->GetGameInstance() == nullptr )
	{
		UE_LOG( LogDemo, Error, TEXT( "GetWorld()->GetGameInstance() == nullptr" ) );
		return false;
	}

	UGameInstance* GameInstance = GetWorld()->GetGameInstance();

	// handle default initialization
	if ( !InitBase( true, InNotify, ConnectURL, false, Error ) )
	{
		GameInstance->HandleDemoPlaybackFailure( EDemoPlayFailure::Generic, FString( TEXT( "InitBase FAILED" ) ) );
		return false;
	}

	ResetDemoState();

	// open the pre-recorded demo file
	FileAr = IFileManager::Get().CreateFileReader( *DemoFilename );

	if ( !FileAr )
	{
		Error = FString::Printf( TEXT( "Couldn't open demo file %s for reading" ), *DemoFilename );
		UE_LOG( LogDemo, Error, TEXT( "UDemoNetDriver::InitConnect: %s" ), *Error );
		GameInstance->HandleDemoPlaybackFailure( EDemoPlayFailure::DemoNotFound, FString( EDemoPlayFailure::ToString( EDemoPlayFailure::DemoNotFound ) ) );
		return false;
	}

	// Playback, local machine is a client, and the demo stream acts "as if" it's the server.
	ServerConnection = ConstructObject<UNetConnection>( UDemoNetConnection::StaticClass() );
	ServerConnection->InitConnection( this, USOCK_Pending, ConnectURL, 1000000 );

	// use the same byte format regardless of platform so that the demos are cross platform
	// DEMO_FIXME: This is messing up for some reason, investigate
	//FileAr->SetByteSwapping( true );

	FNetworkDemoHeader DemoHeader;

	(*FileAr) << DemoHeader;

	// Check magic value
	if ( DemoHeader.Magic != NETWORK_DEMO_MAGIC )
	{
		Error = FString( TEXT( "Demo file is corrupt" ) );
		UE_LOG( LogDemo, Error, TEXT( "UDemoNetDriver::InitConnect: %s" ), *Error );
		GameInstance->HandleDemoPlaybackFailure( EDemoPlayFailure::Corrupt, Error );
		return false;
	}

	// Check version
	if ( DemoHeader.Version != NETWORK_DEMO_VERSION )
	{
		Error = FString( TEXT( "Demo file version is incorrect" ) );
		UE_LOG( LogDemo, Error, TEXT( "UDemoNetDriver::InitConnect: %s" ), *Error );
		GameInstance->HandleDemoPlaybackFailure( EDemoPlayFailure::InvalidVersion, Error );
		return false;
	}

	// Create fake control channel
	ServerConnection->CreateChannel( CHTYPE_Control, 1 );

	DemoTotalFrames = DemoHeader.NumFrames;
	DemoTotalTime	= DemoHeader.TotalTime;

	UE_LOG( LogDemo, Log, TEXT( "Starting demo playback with demo. Filename: %s, Frames: %i, Version %i" ), *DemoFilename, DemoTotalFrames, DemoHeader.Version );

	// Bypass UDemoPendingNetLevel
	FString LoadMapError;

	FURL DemoURL;
	DemoURL.Map = DemoHeader.LevelName;

	FWorldContext * WorldContext = GEngine->GetWorldContextFromWorld( GetWorld() );

	if ( WorldContext == NULL )
	{
		Error = FString::Printf( TEXT( "No world context" ), *DemoFilename );
		UE_LOG( LogDemo, Error, TEXT( "UDemoNetDriver::InitConnect: %s" ), *Error );
		GameInstance->HandleDemoPlaybackFailure( EDemoPlayFailure::Generic, FString( TEXT( "No world context" ) ) );
		return false;
	}

	GetWorld()->DemoNetDriver = NULL;
	SetWorld( NULL );

	auto NewPendingNetGame = NewObject<UDemoPendingNetGame>();

	NewPendingNetGame->DemoNetDriver = this;

	WorldContext->PendingNetGame = NewPendingNetGame;

	if ( !GEngine->LoadMap( *WorldContext, DemoURL, NewPendingNetGame, LoadMapError ) )
	{
		Error = LoadMapError;
		UE_LOG( LogDemo, Error, TEXT( "UDemoNetDriver::InitConnect: LoadMap failed: failed: %s" ), *Error );
		GameInstance->HandleDemoPlaybackFailure( EDemoPlayFailure::Generic, FString( TEXT( "LoadMap failed" ) ) );
		return false;
	}

	SetWorld( WorldContext->World() );
	WorldContext->World()->DemoNetDriver = this;
	WorldContext->PendingNetGame = NULL;

	// Remember where we are
	const int32 OldPos = FileAr->Tell();

	// Jump to meta data
	FileAr->Seek( DemoHeader.MetaDataOffset );

	// Read meta data
	for ( int32 i = 0; i < DemoHeader.NumStreamingLevels; ++i )
	{
		ULevelStreamingKismet* StreamingLevel = static_cast<ULevelStreamingKismet*>(StaticConstructObject(ULevelStreamingKismet::StaticClass(), GetWorld(), NAME_None, RF_NoFlags, NULL ) );

		StreamingLevel->bShouldBeLoaded		= true;
		StreamingLevel->bShouldBeVisible	= true;
		StreamingLevel->bShouldBlockOnLoad	= false;
		StreamingLevel->bInitiallyLoaded	= true;
		StreamingLevel->bInitiallyVisible	= true;

		FString PackageName;
		FString PackageNameToLoad;

		(*FileAr) << PackageName;
		(*FileAr) << PackageNameToLoad;
		(*FileAr) << StreamingLevel->LevelTransform;

		StreamingLevel->PackageNameToLoad = FName( *PackageNameToLoad );
		StreamingLevel->SetWorldAssetByPackageName( FName( *PackageName ) );

		GetWorld()->StreamingLevels.Add( StreamingLevel );

		UE_LOG( LogDemo, Log, TEXT( "  Loading streamingLevel: %s, %s" ), *PackageName, *PackageNameToLoad );
	}

	// Jump back to start of stream
	FileAr->Seek( OldPos );

	// Remember where the meta data is, this is where we must stop reading the demo stream
	EndOfStreamOffset = DemoHeader.MetaDataOffset;

	return true;
}