Ejemplo n.º 1
0
void ChMatterSPH::AddCollisionModelsToSystem() {
    assert(GetSystem());
    SyncCollisionModels();
    for (unsigned int j = 0; j < nodes.size(); j++) {
        GetSystem()->GetCollisionSystem()->Add(nodes[j]->collision_model);
    }
}
Ejemplo n.º 2
0
	void Window::HandleInput(SDL_Event& event, float dt)
	{
		switch( event.type )
		{
			case SDL_MOUSEMOTION:
			{
				if( Input::GetInstance()->GetMouseButton(SDL_BUTTON_RIGHT) )
					GetSystem(Graphics)->UpdateCameraRotation((float)event.motion.xrel*0.3f, (float)event.motion.yrel*0.3f);				
				else if( Input::GetInstance()->GetMouseButton(SDL_BUTTON_LEFT) )
					GetSystem(Graphics)->UpdateLightPos((float)event.motion.xrel*0.3f, (float)event.motion.yrel*0.3f);	
			}
			break;

			case SDL_MOUSEBUTTONDOWN:
				Input::GetInstance()->MouseButtonEvent(event.button.button, true, event.button.x, event.button.y);
			break;

			case SDL_MOUSEBUTTONUP:
				Input::GetInstance()->MouseButtonEvent(event.button.button, false, event.button.x, event.button.y);
			break;

			case SDL_KEYDOWN:
				Input::GetInstance()->KeyboardEvent(event.key.keysym.sym, true);
			break;

			case SDL_KEYUP:
				Input::GetInstance()->KeyboardEvent(event.key.keysym.sym, false);
			break;

			default:
				break;
		}
	}
Ejemplo n.º 3
0
void CBeam::OnWriteToStream (IWriteStream *pStream)

//	OnWriteToStream
//
//	Write the object's data to stream
//
//	CString		CWeaponFireDesc UNID
//	DWORD		m_iBonus
//	DWORD		m_iCause
//	DWORD		m_iRotation
//	Vector		m_vPaintTo
//	DWORD		m_iTick
//	DWORD		m_iLifeLeft
//	DWORD		m_Source (CSpaceObject Ref)
//	DWORD		m_pSovereign (UNID)
//	DWORD		m_pHit (CSpaceObject Ref)
//	DWORD		m_iHitDir

{
    DWORD dwSave;
    m_pDesc->m_sUNID.WriteToStream(pStream);
    pStream->Write((char *)&m_iBonus, sizeof(DWORD));
    dwSave = m_iCause;
    pStream->Write((char *)&dwSave, sizeof(DWORD));
    pStream->Write((char *)&m_iRotation, sizeof(DWORD));
    pStream->Write((char *)&m_vPaintTo, sizeof(m_vPaintTo));
    pStream->Write((char *)&m_iTick, sizeof(DWORD));
    pStream->Write((char *)&m_iLifeLeft, sizeof(m_iLifeLeft));
    m_Source.WriteToStream(GetSystem(), pStream);
    GetSystem()->WriteSovereignRefToStream(m_pSovereign, pStream);
    WriteObjRefToStream(m_pHit, pStream);
    pStream->Write((char *)&m_iHitDir, sizeof(DWORD));
}
Ejemplo n.º 4
0
double StarlaneEntranceOrbitalPosition(int from_system, int to_system) {
    TemporaryPtr<const System> system_1 = GetSystem(from_system);
    TemporaryPtr<const System> system_2 = GetSystem(to_system);
    if (!system_1 || !system_2) {
        Logger().errorStream() << "StarlaneEntranceOrbitalPosition passed invalid system id";
        return 0.0;
    }
    return std::atan2(system_2->Y() - system_1->Y(), system_2->X() - system_1->X());
}
//--------------------------------------------------------------------------------
void CSystemMonitorHandlerThread::DoLoad(LPCTSTR pFilename)
	{
	CString sTemp(pFilename);

	if(! sTemp.IsEmpty())
		GetSystem()->SetLicenseFilename(sTemp);
	if(GetSystem()->GetDBSubSystem()->LoadFromFile())
		sTemp = "file loaded ok\r\n";
	else
		sTemp = "error while loading file\r\n";

	m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK);
	}
Ejemplo n.º 6
0
void CParticleDamage::OnWriteToStream (IWriteStream *pStream)

//	OnWriteToStream
//
//	Write out to stream
//
//	CString			CWeaponFireDesc UNID
//	DWORD			m_iLifeLeft
//	DWORD			m_Source (CSpaceObject ref)
//	DWORD			m_pSovereign (CSovereign ref)
//	DWORD			m_iTick
//	DWORD			m_iDamage
//
//	CVector			m_vEmitSourcePos
//	CVector			m_vEmitSourceVel
//	DWORD			m_iEmitDirection
//	DWORD			m_iEmitTime
//	DWORD			m_iParticleCount
//	IEffectPainter
//	CParticleArray
//
//	CSpaceObject	m_pTarget
//
//	CItemEnhancementStack	m_pEnhancements

	{
	DWORD dwSave;
	m_pDesc->m_sUNID.WriteToStream(pStream);
	dwSave = m_iCause;
	pStream->Write((char *)&dwSave, sizeof(DWORD));
	pStream->Write((char *)&m_iLifeLeft, sizeof(m_iLifeLeft));
	m_Source.WriteToStream(GetSystem(), pStream);
	GetSystem()->WriteSovereignRefToStream(m_pSovereign, pStream);
	pStream->Write((char *)&m_iTick, sizeof(m_iTick));
	pStream->Write((char *)&m_iDamage, sizeof(m_iDamage));
	pStream->Write((char *)&m_vEmitSourcePos, sizeof(CVector));
	pStream->Write((char *)&m_vEmitSourceVel, sizeof(CVector));
	pStream->Write((char *)&m_iEmitDirection, sizeof(DWORD));
	pStream->Write((char *)&m_iEmitTime, sizeof(DWORD));
	pStream->Write((char *)&m_iParticleCount, sizeof(DWORD));

	CEffectCreator::WritePainterToStream(pStream, m_pPainter);

	m_Particles.WriteToStream(pStream);

	WriteObjRefToStream(m_pTarget, pStream);

	//	Enhancements

	CItemEnhancementStack::WriteToStream(m_pEnhancements, pStream);
	}
Ejemplo n.º 7
0
void Moderator::AddStarlane::Execute() const {
    TemporaryPtr<System> sys1 = GetSystem(m_id_1);
    if (!sys1) {
        Logger().errorStream() << "Moderator::AddStarlane::Execute couldn't get system with id: " << m_id_1;
        return;
    }
    TemporaryPtr<System> sys2 = GetSystem(m_id_2);
    if (!sys2) {
        Logger().errorStream() << "Moderator::AddStarlane::Execute couldn't get system with id: " << m_id_2;
        return;
    }
    sys1->AddStarlane(m_id_2);
    sys2->AddStarlane(m_id_1);
}
//--------------------------------------------------------------------------------
void CSystemMonitorHandlerThread::DoList()
	{
	if(m_sCurCmd.Find("all") != -1)
		{
		DoListAll();
		return;
		}

	CDBTokenInfoMap* pDB = GetSystem()->GetDBSubSystem()->GetTokenInfoMap();
	CString sTemp;
	CReadLock lock(pDB, false);
	if(! lock.Lock(5000))
		{
		sTemp = "can't lock the database right now (probably a lot of activity)\r\n";
		m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK);
		return;
		}

	sTemp = "  Id         Name In Use  Count    Max\r\n";
	m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK);

	for(POSITION pos = pDB->GetStartPosition(); pos != NULL; )
		{
		DWORD nId;
		CDBTokenInfo* pInfo;

		pDB->GetNextAssoc(pos, nId, pInfo);
		if(! pInfo)
			continue;

		sTemp.Format("%4d %12s %6d %6d %6d\r\n",
			nId, pInfo->m_token.GetName(), pInfo->m_nInUse, pInfo->m_nCount, pInfo->m_nMax);

		m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK);
		}

	if(GetSystem()->IsBackupServer())
		sTemp.Format("%s%s\r\n", "Running as backup server", GetSystem()->IsServing() ? " currently serving" : "");
	else
		sTemp.Format("Backup SecurityServer is %s\r\n", GetSystem()->IsBackupRunning() ? "running" : "not running");

	m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK);

#ifdef _DEBUG
#pragma message("Don't forget to change the listed version for the next release!")
#endif

	sTemp.Format("This server is version " SECSERV_VERSION_STRING "\r\n");
	m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK);
	}
Ejemplo n.º 9
0
FleetMoveOrder::FleetMoveOrder(int empire, int fleet_id, int start_system_id, int dest_system_id, bool append) :
    Order(empire),
    m_fleet(fleet_id),
    m_start_system(start_system_id),
    m_dest_system(dest_system_id),
    m_append(append)
{
    // perform sanity checks
    TemporaryPtr<const Fleet> fleet = GetFleet(FleetID());
    if (!fleet) {
        ErrorLogger() << "Empire with id " << EmpireID() << " ordered fleet with id " << FleetID() << " to move, but no such fleet exists";
        return;
    }

    TemporaryPtr<const System> destination_system = GetSystem(DestinationSystemID());
    if (!destination_system) {
        ErrorLogger() << "Empire with id " << EmpireID() << " ordered fleet to move to system with id " << DestinationSystemID() << " but no such system exists / is known to exist";
        return;
    }

    // verify that empire specified in order owns specified fleet
    if (!fleet->OwnedBy(EmpireID()) ) {
        ErrorLogger() << "Empire with id " << EmpireID() << " order to move but does not own fleet with id " << FleetID();
        return;
    }

    std::pair<std::list<int>, double> short_path = GetUniverse().ShortestPath(m_start_system, m_dest_system, empire);

    m_route.clear();
    std::copy(short_path.first.begin(), short_path.first.end(), std::back_inserter(m_route));

    // ensure a zero-length (invalid) route is not requested / sent to a fleet
    if (m_route.empty())
        m_route.push_back(m_start_system);
}
TEST_F(TestDoubleClearIndoorShadeAir, Test1)
{
    SCOPED_TRACE("Begin Test: Indoor Shade - Air");

    auto aSystem = GetSystem();

    auto temperature = aSystem->getTemperatures();
    auto radiosity = aSystem->getRadiosities();

    std::vector<double> correctTemp = {
      258.2265788, 258.7403799, 276.1996405, 276.7134416, 288.1162677, 288.1193825};
    std::vector<double> correctJ = {
      250.2066021, 264.5687123, 319.49179, 340.4531177, 382.6512706, 397.0346045};

    EXPECT_EQ(correctTemp.size(), temperature.size());
    EXPECT_EQ(correctJ.size(), radiosity.size());

    for(size_t i = 0; i < temperature.size(); ++i)
    {
        EXPECT_NEAR(correctTemp[i], temperature[i], 1e-6);
        EXPECT_NEAR(correctJ[i], radiosity[i], 1e-6);
    }

    const auto numOfIter = aSystem->getNumberOfIterations();
    EXPECT_EQ(1, int(numOfIter));

    const auto ventilatedFlow = aSystem->getVentilationFlow(Tarcog::ISO15099::Environment::Indoor);
    EXPECT_NEAR(40.066868, ventilatedFlow, 1e-6);
}
Ejemplo n.º 11
0
bool HypoApp::OnInit()
{
    int x = 700;
    int y = 920; // 1100   // 850
    wxPoint pos;
    
    if(GetSystem() == Mac) {
        x = 685;
        pos.x = 50;
        pos.y = 23;    // 0;
    }
    else pos = wxDefaultPosition;
    
    OptionLoad();
    if(viewwidth < 400) viewwidth = 400;
    y = viewheight;
    x = viewwidth;
    
    wxSize screensize = wxGetDisplaySize();
    if(x > screensize.GetX()) x = screensize.GetX() - 50;
    if(y > screensize.GetY()) y = screensize.GetY() - 50;
    
    //MainFrame *mainwin = new MainFrame("Hypo Net Model", wxPoint(50, 10), wxSize(700, y));   // 850   // 920
    HypoMain *mainwin = new HypoMain("HypoMod", pos, wxSize(x, y));   // 850   // 920
    //HypoMain *mainwin = new HypoMain("HypoMod", wxDefaultPosition, wxSize(400, 500));
    mainwin->Show(TRUE);
    SetTopWindow(mainwin);
    return TRUE;
}
Ejemplo n.º 12
0
MainFrame::MainFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
: wxFrame((wxFrame *)NULL, -1, title, pos, size)
{
	ostype = GetSystem();
	mainwin = this;
	statusbar = CreateStatusBar();
	diagbox = NULL;                // Protect diagbox self reference for toolpanel
	gridbox = NULL;
	neurobox = NULL;

    diagbox = new DiagBox(this, "Diagnostic", wxPoint(0, 0), wxSize(400, 500));
	diagbox->Write("Diagnostic Box OK\n\n");

	graphbox = NULL;
	plotbox = NULL;

	colourpen[0].Set("#000000");       // 0 black
	colourpen[1].Set("#F50000");       // 1 red
	colourpen[2].Set("#00F500");       // 2 green
	colourpen[3].Set("#0000F5");       // 3 blue
	colourpen[4].Set("#F5F500");       // 4 yellow
	colourpen[5].Set("#F500F5");       // 5 purple
	colourpen[6].Set("#FF8080");       // 6 light red
	colourpen[7].Set("#80FF80");       // 7 light green
	colourpen[8].Set("#8080FF");       // 8 light blue
	colourpen[9].Set("#000000");       // 9 custom

	toolset = new ToolSet();
	toolset->AddBox(diagbox, true);
}
Ejemplo n.º 13
0
void Fleet::AddShip(int ship_id) {
    if (this->Contains(ship_id)) {
        Logger().debugStream() << "Fleet::AddShip this fleet '" << this->Name() << "' already contained ship '" << ship_id << "'";
        return;
    }

    Ship* ship = GetShip(ship_id);
    if (!ship) {
        Logger().errorStream() << "Fleet::AddShips() : Attempted to add an id (" << ship_id << ") of a non-ship object to a fleet.";
        return;
    }

    //Logger().debugStream() << "Fleet '" << this->Name() << "' adding ship: " << ship_id;

    // remove ship from old fleet
    if (Fleet* old_fleet = GetFleet(ship->FleetID()))
        old_fleet->RemoveShip(ship_id);

    // ensure ship is in same system as this fleet
    int ship_system_id = ship->SystemID();
    int this_fleet_system_id = this->SystemID();
    if (ship_system_id != this_fleet_system_id)
        if (System* system = GetSystem(this_fleet_system_id))
            system->Insert(ship);   // sets ship's system, remove from old system (if any) and moves ship to system's location (if necessary)

    // add ship to this fleet, and set its internal fleet record

    ship->SetFleetID(ID());
    m_ships.insert(ship_id);

    RecalculateFleetSpeed();
    StateChangedSignal();
}
Ejemplo n.º 14
0
	void Window::Update(float dt)
	{
		//Event polling
		while (SDL_PollEvent(&e))
		{
			switch( e.type )
			{
				//If user closes the window
				case SDL_QUIT:
					Core::GetInstance()->SetState(-1);
					break;

				case SDL_WINDOWEVENT:	
				{
					if( e.window.event == SDL_WINDOWEVENT_RESIZED )
					{
						WINDOW_W = e.window.data1;
						WINDOW_H = e.window.data2;
						GetSystem(Graphics)->UpdateScreenDims(WINDOW_X, WINDOW_Y, WINDOW_W, WINDOW_H);
						break;
					}
				}
				
				default:
					HandleInput(e, dt);
					break;
			};
		}


		//SDL_RenderClear(renderer);
		//SDL_RenderPresent(renderer);
	}
TEST_F(TestDoubleClearSingleSystemNoSun, Test1)
{
    SCOPED_TRACE("Begin Test: Double Clear Single System - Surface temperatures");

    auto aSystem = GetSystem();
    ASSERT_TRUE(aSystem != nullptr);

    auto Temperature = aSystem->getTemperatures();
    std::vector<double> correctTemperature = {258.756688, 259.359226, 279.178510, 279.781048};
    ASSERT_EQ(correctTemperature.size(), Temperature.size());

    for(auto i = 0u; i < correctTemperature.size(); ++i)
    {
        EXPECT_NEAR(correctTemperature[i], Temperature[i], 1e-5);
    }

    auto Radiosity = aSystem->getRadiosities();
    std::vector<double> correctRadiosity = {251.950834, 268.667346, 332.299338, 359.731700};
    ASSERT_EQ(correctRadiosity.size(), Radiosity.size());

    for(auto i = 0u; i < correctRadiosity.size(); ++i)
    {
        EXPECT_NEAR(correctRadiosity[i], Radiosity[i], 1e-5);
    }

    auto heatFlow = aSystem->getHeatFlow(Tarcog::ISO15099::Environment::Indoor);
    EXPECT_NEAR(105.431019, heatFlow, 1e-5);

    auto Uvalue = aSystem->getUValue();
    EXPECT_NEAR(2.703359, Uvalue, 1e-5);

    auto numOfIter = aSystem->getNumberOfIterations();
    EXPECT_EQ(20u, numOfIter);
}
Ejemplo n.º 16
0
ParamText::ParamText(wxPanel *panel, wxString pname, wxString labelname, wxString initval, int labelwid, int textwid)
{
	wxControl::Create(panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxBORDER_NONE);
	name = pname;
	labelwidth = labelwid;
	textwidth = textwid;
	buttonwidth = 0;
	ostype = GetSystem();
    textfont = wxFont(wxFontInfo(8).FaceName("Tahoma"));
	//textfont = wxFont(8, wxFONTFAMILY_SWISS, wxNORMAL, wxNORMAL, false, "Tahoma");
    if(ostype == Mac) textfont = wxFont(wxFontInfo(11).FaceName("Tahoma"));
    
	confont = textfont;

	sizer = new wxBoxSizer(wxHORIZONTAL);
	label = new wxStaticText(this, wxID_STATIC, labelname, wxDefaultPosition, wxSize(labelwidth, -1), wxALIGN_CENTRE);
	textbox = new wxTextCtrl(this, wxID_ANY, initval, wxDefaultPosition, wxSize(textwidth, -1), wxTE_PROCESS_ENTER);

	label->SetFont(textfont);
	textbox->SetFont(textfont);

	SetInitialSize(wxDefaultSize);
	Move(wxDefaultPosition);

	sizer->Add(label, 0, wxALIGN_CENTER_VERTICAL|wxRIGHT, 2);
	sizer->Add(textbox, 0, wxALIGN_CENTER_VERTICAL|wxRIGHT, 2);
	SetSizer(sizer);
	Layout();
}
Ejemplo n.º 17
0
ParamNum::ParamNum(wxPanel *panel, wxString pname, wxString labelname, double initval, int places)
{
    int numheight = -1;
    
	wxControl::Create(panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxBORDER_NONE);
	name = pname;
	decimals = places;
	ostype = GetSystem();
    textfont = wxFont(wxFontInfo(8).FaceName("Tahoma"));
    //textfont = wxFont(wxFontInfo(8).FaceName("Tahoma"));
    
	//textfont = wxFont(8, wxFONTFAMILY_SWISS, wxNORMAL, wxNORMAL, false, wxT("Tahoma"));
    if(ostype == Mac) {
        textfont = wxFont(wxFontInfo(11).FaceName("Tahoma"));
        //textfont = wxFont(11, wxFONTFAMILY_SWISS, wxNORMAL, wxNORMAL, false, wxT("Tahoma"));
        numheight = 20;
    }

	sizer = new wxBoxSizer(wxHORIZONTAL);
	snum = numstring(initval, places);
	label = new wxStaticText(this, wxID_STATIC, labelname, wxDefaultPosition, wxSize(65, -1), wxALIGN_CENTRE);
	numbox = new wxTextCtrl(this, wxID_ANY, snum, wxDefaultPosition, wxSize(40, numheight), wxTE_PROCESS_ENTER);

	label->SetFont(textfont);
	numbox->SetFont(textfont);

	SetInitialSize(wxDefaultSize);
	Move(wxDefaultPosition);

	sizer->Add(label, 0, wxALIGN_CENTER_VERTICAL|wxRIGHT, 2);
	sizer->Add(numbox, 0, wxALIGN_CENTER_VERTICAL|wxRIGHT, 2);
	SetSizer(sizer);
	Layout();
}
//--------------------------------------------------------------------------------
void CSystemMonitorHandlerThread::DoRevoke()
	{
	int nIndex = m_sCurCmd.ReverseFind(' ');
	if(nIndex == -1)
		return;

	if(nIndex == (m_sCurCmd.GetLength() - 1))
		return;

	CString sTemp(m_sCurCmd.Mid(nIndex + 1));

	if(sTemp == "all")
		{
		DoRevokeAll();
		return;
		}

	if(sTemp.Find('.') != -1)
		{
		DoRevokeByIP(sTemp);
		return;
		}

	DWORD nId = (DWORD) atol(sTemp);

	if(! GetSystem()->GetDBSubSystem()->ReleaseCertificate(nId))
		sTemp.Format("certificate %d not found\n\r", nId);
	else
		sTemp.Format("certificate %d revoked\r\n", nId);

	m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK);
	}
Ejemplo n.º 19
0
    int IssueGiveObjectToEmpireOrder(int object_id, int recipient_id) {
        int empire_id = AIClientApp::GetApp()->EmpireID();

        if (Empires().Lookup(recipient_id) == 0) {
            Logger().errorStream() << "AIInterface::IssueGiveObjectToEmpireOrder : given invalid recipient empire id";
            return 0;
        }

        if (Empires().GetDiplomaticStatus(empire_id, recipient_id) != DIPLO_PEACE) {
            Logger().errorStream() << "AIInterface::IssueGiveObjectToEmpireOrder : attempting to give to empire not at peace";
            return 0;
        }

        TemporaryPtr<UniverseObject> obj = GetUniverseObject(object_id);
        if (!obj) {
            Logger().errorStream() << "AIInterface::IssueGiveObjectToEmpireOrder : passed invalid object id";
            return 0;
        }

        if (!obj->OwnedBy(empire_id)) {
            Logger().errorStream() << "AIInterface::IssueGiveObjectToEmpireOrder : passed object not owned by player";
            return 0;
        }

        if (obj->ObjectType() != OBJ_FLEET && obj->ObjectType() != OBJ_PLANET) {
            Logger().errorStream() << "AIInterface::IssueGiveObjectToEmpireOrder : passed object that is not a fleet or planet";
            return 0;
        }

        TemporaryPtr<System> system = GetSystem(obj->SystemID());
        if (!system) {
            Logger().errorStream() << "AIInterface::IssueGiveObjectToEmpireOrder : couldn't get system of object";
            return 0;
        }

        // can only give to empires with something present to receive the gift
        bool recipient_has_something_here = false;
        std::vector<TemporaryPtr<const UniverseObject> > system_objects =
            Objects().FindObjects<const UniverseObject>(system->ObjectIDs());
        for (std::vector<TemporaryPtr<const UniverseObject> >::const_iterator it = system_objects.begin();
                it != system_objects.end(); ++it)
        {
            TemporaryPtr<const UniverseObject> obj = *it;
            if (obj->Owner() == recipient_id) {
                recipient_has_something_here = true;
                break;
            }
        }
        if (!recipient_has_something_here) {
            Logger().errorStream() << "AIInterface::IssueGiveObjectToEmpireOrder : recipient empire has nothing in system";
            return 0;
        }

        AIClientApp::GetApp()->Orders().IssueOrder(OrderPtr(
            new GiveObjectToEmpireOrder(empire_id, object_id, recipient_id)));

        return 1;
    }
Ejemplo n.º 20
0
CSpaceObject::DamageResults CMissile::Damage (CSpaceObject *pCause, const CVector &vHitPos, int iDirection, const DamageDesc &Damage)

//	Damage
//
//	Object takes damage from the given source

	{
	CSpaceObject *pAttacker = pCause->GetDamageCause();

	//	Compute damage

	bool bDestroy = false;
	int iDamage = Damage.RollDamage();
	if (iDamage == 0)
		return damageNoDamage;

	//	If this is a momentum attack then we are pushed

	int iMomentum;
	if (iMomentum = Damage.GetMomentumDamage())
		{
		CVector vAccel = PolarToVector(iDirection, -10 * iMomentum * iMomentum);
		Accelerate(vAccel, g_MomentumConstant);
		ClipSpeed(GetMaxSpeed());
		}

	//	Create a hit effect

	CEffectCreator *pEffect = g_pUniverse->FindEffectType(g_HitEffectUNID);
	if (pEffect)
		pEffect->CreateEffect(GetSystem(),
				this,
				vHitPos,
				GetVel());

	//	Take damage

	if (iDamage < m_iHitPoints)
		{
		m_iHitPoints -= iDamage;
		return damageArmorHit;
		}

	//	We are destroyed

	m_iHitPoints = 0;
	if (m_pDesc->m_iVaporTrailLength)
		{
		m_fDestroyed = true;
		m_iLifeLeft = m_pDesc->m_iVaporTrailLength;
		}
	else
		Destroy(killedByDamage, pAttacker);

	//	A missile might be able to pass through after hitting us

	return damagePassthrough;
	}
Ejemplo n.º 21
0
EDamageResults CMissile::OnDamage (SDamageCtx &Ctx)

//	Damage
//
//	Object takes damage from the given source

{
    Ctx.iSectHit = -1;

    //	Compute damage

    bool bDestroy = false;
    Ctx.iDamage = Ctx.Damage.RollDamage();
    if (Ctx.iDamage == 0)
        return damageNoDamage;

    //	If this is a momentum attack then we are pushed

    int iMomentum;
    if (iMomentum = Ctx.Damage.GetMomentumDamage())
    {
        CVector vAccel = PolarToVector(Ctx.iDirection, -10 * iMomentum * iMomentum);
        Accelerate(vAccel, g_MomentumConstant);
        ClipSpeed(GetMaxSpeed());
    }

    //	Create a hit effect

    Ctx.pDesc->CreateHitEffect(GetSystem(), Ctx);

    //	Check for passthrough. If we pass through then we don't take any damage.

    if (mathRandom(1, 100) <= m_pDesc->GetPassthrough())
        return damageArmorHit;

    //	Take damage

    if (Ctx.iDamage < m_iHitPoints)
    {
        m_iHitPoints -= Ctx.iDamage;
        return damageArmorHit;
    }

    //	We are destroyed

    m_iHitPoints = 0;
    if (m_pDesc->GetVaporTrailLength())
    {
        m_fDestroyed = true;
        m_iLifeLeft = m_pDesc->GetVaporTrailLength();
        return damagePassthrough;
    }
    else
    {
        Destroy(killedByDamage, Ctx.Attacker);
        return damagePassthroughDestroyed;
    }
}
Ejemplo n.º 22
0
std::string UniverseObject::Dump() const {
    TemporaryPtr<const System> system = GetSystem(this->SystemID());

    std::stringstream os;

    os << boost::lexical_cast<std::string>(this->ObjectType()) << " "
       << this->ID() << ": "
       << this->Name();
    if (system) {
        const std::string& sys_name = system->Name();
        if (sys_name.empty())
            os << "  at: (System " << system->ID() << ")";
        else
            os << "  at: " << sys_name;
    } else {
        os << "  at: (" << this->X() << ", " << this->Y() << ")";
        int near_id = GetUniverse().NearestSystemTo(this->X(), this->Y());
        TemporaryPtr<const System> system = GetSystem(near_id);
        if (system) {
            const std::string& sys_name = system->Name();
            if (sys_name.empty())
                os << " nearest (System " << system->ID() << ")";
            else
                os << " nearest " << system->Name();
        }
    }
    if (Unowned()) {
        os << " owner: (Unowned) ";
    } else {
        std::string empire_name = Empires().GetEmpireName(m_owner_empire_id);
        if (!empire_name.empty())
            os << " owner: " << empire_name;
        else
            os << " owner: (Unknown Empire)";
    }
    os << " created on turn: " << m_created_on_turn
       << " specials: ";
    for (std::map<std::string, std::pair<int, float> >::const_iterator it = m_specials.begin(); it != m_specials.end(); ++it)
        os << "(" << it->first << ", " << it->second.first << ", " << it->second.second << ") ";
    os << "  Meters: ";
    for (std::map<MeterType, Meter>::const_iterator it = m_meters.begin(); it != m_meters.end(); ++it)
        os << UserString(EnumToString(it->first))
           << ": " << it->second.Dump() << "  ";
    return os.str();
}
Ejemplo n.º 23
0
void CMissile::CreateFragments (const CVector &vPos)

//	CreateFragments
//
//	Create fragments

{
    //	If there is an event, then let it handle the fragmentation

    if (m_pDesc->FireOnFragment(m_Source, this, vPos, m_pHit, m_pTarget))
        return;

    //	NOTE: Missile fragments don't inherit the velocity of the missile
    //	(otherwise, fragmentation weapons explode too late to do much damage)

    if (m_pDesc->HasFragments())
        GetSystem()->CreateWeaponFragments(m_pDesc,
                                           m_iBonus,
                                           m_iCause,
                                           m_Source,
                                           m_pTarget,
                                           vPos,
                                           CVector(),
                                           this);

    //	Create the hit effect

    SDamageCtx Ctx;
    Ctx.pObj = NULL;
    Ctx.pDesc = m_pDesc;
    Ctx.Damage = m_pDesc->m_Damage;
    Ctx.Damage.AddBonus(m_iBonus);
    Ctx.Damage.SetCause(m_iCause);
    if (IsAutomatedWeapon())
        Ctx.Damage.SetAutomatedWeapon();
    Ctx.iDirection = mathRandom(0, 359);
    Ctx.vHitPos = vPos;
    Ctx.pCause = this;
    Ctx.Attacker = m_Source;

    m_pDesc->CreateHitEffect(GetSystem(), Ctx);
}
Ejemplo n.º 24
0
// collision stuff
void ChMatterSPH::SetCollide(bool mcoll) {
    if (mcoll == do_collide)
        return;

    if (mcoll) {
        do_collide = true;
        if (GetSystem()) {
            for (unsigned int j = 0; j < nodes.size(); j++) {
                GetSystem()->GetCollisionSystem()->Add(nodes[j]->collision_model);
            }
        }
    } else {
        do_collide = false;
        if (GetSystem()) {
            for (unsigned int j = 0; j < nodes.size(); j++) {
                GetSystem()->GetCollisionSystem()->Remove(nodes[j]->collision_model);
            }
        }
    }
}
Ejemplo n.º 25
0
void CombatLogWnd::CombatLogWndImpl::SetLog(int log_id) {
    if (!CombatLogAvailable(log_id)) {
        ErrorLogger() << "Couldn't find combat log with id: " << log_id;
        return;
    }

    m_wnd.DeleteChildren();
    GG::Layout* layout = new GG::Layout(m_wnd.UpperLeft().x, m_wnd.UpperLeft().y
                                        , m_wnd.Width(), m_wnd.Height()
                                        , 1, 1 ///< numrows, numcols
                                        , 0, 0 ///< wnd margin, cell margin
                                       );
    m_wnd.SetLayout(layout);

    const CombatLog& log = GetCombatLog(log_id);
    int client_empire_id = HumanClientApp::GetApp()->EmpireID();

    // Write Header text
    DebugLogger() << "Setting log with " << log.combat_events.size() << " events";

    TemporaryPtr<const System> system = GetSystem(log.system_id);
    const std::string& sys_name = (system ? system->PublicName(client_empire_id) : UserString("ERROR"));

    AddRow(DecorateLinkText(str(FlexibleFormat(UserString("ENC_COMBAT_LOG_DESCRIPTION_STR"))
                                % LinkTaggedIDText(VarText::SYSTEM_ID_TAG, log.system_id, sys_name)
                                % log.turn) + "\n"
                           ));
    AddRow(DecorateLinkText(UserString("COMBAT_INITIAL_FORCES")));
    AddRow(DecorateLinkText(CountsToText(CountByOwner(log.empire_ids, log.object_ids))));

    std::stringstream summary_text;
    summary_text << std::endl << UserString("COMBAT_SUMMARY_DESTROYED")
                 << std::endl << CountsToText(CountByOwner(log.empire_ids, log.destroyed_object_ids));
    AddRow(DecorateLinkText(summary_text.str()));

    // Write Logs
    for (std::vector<CombatEventPtr>::const_iterator it = log.combat_events.begin();
         it != log.combat_events.end(); ++it) {
        DebugLogger() << "event debug info: " << it->get()->DebugString();

        std::vector<GG::Wnd *> flat_logs =
            MakeCombatLogPanel(m_font->SpaceWidth()*10, client_empire_id, *it);
        for (std::vector<GG::Wnd *>::iterator log_it = flat_logs.begin();
             log_it != flat_logs.end(); ++log_it) {
            AddRow(*log_it);
        }
    }

    // Add a dummy row that the layout manager can use to add space.
    AddRow(DecorateLinkText(""));
    layout->SetRowStretch(layout->Rows() - 1, 1);

    HandleWndChanged();
}
Ejemplo n.º 26
0
void CParticleDamage::OnUpdate (SUpdateCtx &Ctx, Metric rSecondsPerTick)

//	OnUpdate
//
//	Update

	{
	m_iTick++;

	//	Update the single particle painter

	if (m_pPainter)
		m_pPainter->OnUpdate();

	//	Set up context block for particle array update

	SEffectUpdateCtx EffectCtx;
	EffectCtx.pSystem = GetSystem();
	EffectCtx.pObj = this;

	EffectCtx.pDamageDesc = m_pDesc;
	EffectCtx.iTotalParticleCount = m_iParticleCount;
	EffectCtx.pEnhancements = m_pEnhancements;
	EffectCtx.iCause = m_iCause;
	EffectCtx.bAutomatedWeapon = IsAutomatedWeapon();
	EffectCtx.Attacker = m_Source;

	//	Update (includes doing damage)

	m_Particles.Update(EffectCtx);

	//	If we're tracking, change velocity to follow target

	if (m_pTarget && m_pDesc->IsTrackingTime(m_iTick))
		m_Particles.UpdateTrackTarget(m_pTarget, m_pDesc->GetManeuverRate(), m_pDesc->GetRatedSpeed());

	//	Expired?

	if (--m_iLifeLeft <= 0)
		{
		Destroy(removedFromSystem, CDamageSource());
		return;
		}

	//	Emit new particles

	if (m_iTick < m_iEmitTime && !m_Source.IsEmpty())
		{
		InitParticles(m_pDesc->GetParticleCount(),
				m_vEmitSourcePos - GetPos(),
				GetVel(),
				m_iEmitDirection);
		}
	}
Ejemplo n.º 27
0
std::string Planet::CardinalSuffix() const {
    std::string retval = "";
    // Planets are grouped into asteroids, and non-asteroids
    // Asteroids receive a localized prefix
    if (Type() == PT_ASTEROIDS)
        retval.append(UserString("NEW_ASTEROIDS_SUFFIX") + " ");

    TemporaryPtr<System> cur_system = GetSystem(SystemID());
    if (cur_system) {
        if (cur_system->OrbitOfPlanet(ID()) < 0) {
            ErrorLogger() << "Planet " << Name() << "(" << ID() << ") "
                          << "has no current orbit";
            retval.append(RomanNumber(1));
            return retval;
        }
        int num_planets_lteq = 0;  // number of planets at this orbit or smaller
        int num_planets_total = 0;
        bool prior_current_planet = true;
        const std::vector<int>& sys_orbits = cur_system->PlanetIDsByOrbit();
        for (std::vector<int>::const_iterator it = sys_orbits.begin();
             it != sys_orbits.end(); ++it)
        {
            if (*it == INVALID_OBJECT_ID)
                continue;

            PlanetType other_planet_type = GetPlanet(*it)->Type();
            if (other_planet_type == INVALID_PLANET_TYPE)
                continue;

            if (Type() != PT_ASTEROIDS) {
                if (other_planet_type != PT_ASTEROIDS) {
                    ++num_planets_total;
                    if (prior_current_planet)
                        ++num_planets_lteq;
                }
            } else {
                if (other_planet_type == PT_ASTEROIDS) {
                    ++num_planets_total;
                    if (prior_current_planet)
                        ++num_planets_lteq;
                }
            }

            if (*it == ID())
                prior_current_planet =false;
        }
        // For asteroids: If no other asteroids in this system, suffix does not receive a number
        if (Type() != PT_ASTEROIDS || (Type() == PT_ASTEROIDS && num_planets_total > 1))
            retval.append(RomanNumber(num_planets_lteq));
    } else {
        ErrorLogger() << "Planet " << Name() << "(" << ID() << ") not assigned to a system";
    }
    return retval;
}
//--------------------------------------------------------------------------------
void CSystemMonitorHandlerThread::DoRevokeAll()
	{
	CString sTemp;

	if(! GetSystem()->GetDBSubSystem()->ReleaseAllCertificates())
		sTemp = "certificates not found\n\r";
	else
		sTemp = "all certificate revoked\r\n";

	m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK);
	}
//--------------------------------------------------------------------------------
void CSystemMonitorHandlerThread::DoRevokeByIP(const CString& sIP)
	{
	CString sTemp;

	if(! GetSystem()->GetDBSubSystem()->ReleaseCertificate(sIP))
		sTemp.Format("no certificates issued to %s\n\r", (LPCTSTR) sIP);
	else
		sTemp.Format("certificates issued to %s revoked\n\r", (LPCTSTR) sIP);

	m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK);
	}
Ejemplo n.º 30
0
//--------------------------------------------------------------------------------
bool CBackupThread::MainLoop()
	{
	bool bMainRunning = ConnectToMainServer();

	if(GetSystem()->IsServing())
		{
		if(bMainRunning)
			{
			GetSystem()->SetIsServing(false);
			CSSQuickMail* pMail = new CSSQuickMail;
			pMail->m_sSubject.Format("IMP: Main back %s", (LPCTSTR) CTime::GetCurrentTime().Format("%c"));
			pMail->m_sMsg = pMail->m_sSubject + "\r\nBackup returning to backup status\r\n";
			GetSystem()->GetIOSubSystem()->SendQuickMail(pMail);
			GetSystem()->GetDBSubSystem()->ReleaseAllCertificates();
			}
		}
	else
		{
		if(! bMainRunning)
			{
			// it did so we'll take over
			GetSystem()->SetIsServing(true);
			CSSQuickMail* pMail = new CSSQuickMail;
			pMail->m_sSubject.Format("IMP: Backup taking over %s", (LPCTSTR) CTime::GetCurrentTime().Format("%c"));
			pMail->m_sMsg = pMail->m_sSubject + "\r\n";
			GetSystem()->GetIOSubSystem()->SendQuickMail(pMail);
			}
		}

	return CThreadObject::MainLoop();
	}