コード例 #1
0
ファイル: HumanClientFSM.cpp プロジェクト: anarsky/freeorion
ResolvingCombat::~ResolvingCombat() {
    if (TRACE_EXECUTION) Logger().debugStream() << "(HumanClientFSM) ~ResolvingCombat";
    Client().m_ui->GetMapWnd()->Show();
    FreeCombatData(m_previous_combat_data.get());
    FreeCombatData(m_combat_data.get());
}
コード例 #2
0
ファイル: Clock.cpp プロジェクト: LCartwright/gameboy
Clock::Clock() {
	// TODO Auto-generated constructor stub
	logger = Logger();
}
コード例 #3
0
ファイル: fileReader.cpp プロジェクト: Cimera42/2DGame
bool File::ReadDataBlock(std::string block, DataBlock* datablock)
{
    blockSize = block.size();
    int currentPos = 0;
    bool optionalToken = 0;
    int elementIndex = 0;
    int propertyIndex = 0;
    for(int i = 0; i <= 4; i++)//Why this is in a for loop I will never know
    {
        if(i == 0)
        {
            datablock->elements.push_back(new DataElement());
            //element token
            int extractPos1 = block.find_first_of('{', currentPos)-currentPos;
            int extractPos2 = block.find_first_of('"', currentPos)-currentPos;
            checkExtractPos(&extractPos1);
            checkExtractPos(&extractPos2);
            if(extractPos1<extractPos2)
            {
                std::string elementToken = block.substr(currentPos, extractPos1);
                if(!checkToken(elementToken))
                {
                    Logger()<<"Element contains incorrect syntax: \n"<<elementToken<<"\n"<<std::endl; //syntax error
                    return false;
                }
                datablock->elements[elementIndex]->elementName = elementToken;
                currentPos += extractPos1+1;
                optionalToken = false;
            }
            else if(extractPos2<extractPos1)
            {
                std::string elementToken = block.substr(currentPos, extractPos2);
                if(!checkToken(elementToken))
                {
                    Logger()<<"Element contains incorrect syntax: \n"<<elementToken<<"\n"<<std::endl; //syntax error
                    return false;
                }
                datablock->elements[elementIndex]->elementName = elementToken;
                currentPos += extractPos2+1;
                optionalToken = true;
            }
            else
            {
                Logger()<<"Element doesn't contain properties OR no terminating comment: \n"
                        <<datablock->elements[elementIndex]->elementName<<" '"
                        <<datablock->elements[elementIndex]->elementIdentifier<<"'\n"<<std::endl; //error
                return false;
            }
        }
        if(i == 1)
        {
            //check for optional
            if(optionalToken)
            {
                int extractPos1 = block.find_first_of('"', currentPos)-currentPos;
                //int extractPos2 = block.find_first_of('{', currentPos)-currentPos;
                //first do the "
                std::string optionalTokenStr = block.substr(currentPos, extractPos1);
                if(!checkToken(optionalTokenStr))
                {
                    Logger()<<"Optional Identifier contains incorrect syntax: \n"
                            <<datablock->elements[elementIndex]->elementName<<" "<<optionalTokenStr<<"\n"<<std::endl; //syntax error
                    return false;
                }
                datablock->elements[elementIndex]->elementIdentifier = optionalTokenStr;
                currentPos += extractPos1+1;
                //then check if { is next, if not we have an issue
                if(block[currentPos] == '{')
                    currentPos++;
                else
                {
                    Logger()<<"Element doesn't contain properties (are you missing an '{' ?): \n"
                            <<datablock->elements[elementIndex]->elementName<<" '"
                            <<datablock->elements[elementIndex]->elementIdentifier<<"'\n"<<std::endl;
                    return false;
                }
            }
        }
        if(i == 2)
        {
            //break the properties section
            //int first = currentPos;
            int last = block.find_first_of('}', currentPos);
            while(currentPos < last)//loop through all the properties
            {
                //create a new property
                datablock->elements[elementIndex]->properties.push_back(new DataProperty());
                int extractPos1 = block.find_first_of(':', currentPos)-currentPos;
                //do the propertyToken:
                std::string propertyToken = block.substr(currentPos, extractPos1);
                if(!checkToken(propertyToken))
                {
                    Logger()<<"Property contains incorrect syntax: \n"
                            <<datablock->elements[elementIndex]->elementName<<" '"
                            <<datablock->elements[elementIndex]->elementIdentifier<<"': \n"<<propertyToken<<"\n"<<std::endl; //syntax error
                    return false;
                }
                datablock->elements[elementIndex]->properties[propertyIndex]->propertyName = propertyToken;
                currentPos += extractPos1+1;
                //do the valueToken
                int innerLast = block.find_first_of(';', currentPos);
                while(currentPos < innerLast) //loop through all the values for a specific property
                {
                    //create a new value for a property
                    extractPos1 = block.find_first_of(',', currentPos)-currentPos;
                    int extractPos2 = block.find_first_of(';', currentPos)-currentPos;
                    checkExtractPos(&extractPos1);
                    if(extractPos1<extractPos2)
                    {
                        std::string valueToken = block.substr(currentPos, extractPos1);
                        if(!checkToken(valueToken))
                        {
                            Logger()<<"Value contains incorrect syntax: \n"
                                    <<datablock->elements[elementIndex]->elementName<<" '"
                                    <<datablock->elements[elementIndex]->elementIdentifier<<"': \n"
                                    <<datablock->elements[elementIndex]->properties[propertyIndex]->propertyName<<": "<<valueToken<<"\n"<<std::endl; //syntax error;
                            return false;
                        }
                        datablock->elements[elementIndex]->properties[propertyIndex]->values.push_back(valueToken);
                        currentPos += extractPos1+1;
                    }
                    else if(extractPos2<extractPos1)
                    {
                        std::string valueToken = block.substr(currentPos, extractPos2);
                        if(!checkToken(valueToken))
                        {
                            Logger()<<"Value contains incorrect syntax: \n"
                                    <<datablock->elements[elementIndex]->elementName<<" '"
                                    <<datablock->elements[elementIndex]->elementIdentifier<<"': \n"
                                    <<datablock->elements[elementIndex]->properties[propertyIndex]->propertyName<<": "<<valueToken<<"\n"<<std::endl; //syntax error;
                            return false;
                        }
                        datablock->elements[elementIndex]->properties[propertyIndex]->values.push_back(valueToken);
                        currentPos += extractPos2+1;
                    }
                    else
                        return false;
                }
                propertyIndex++;
            }
            currentPos+=1;
            elementIndex++;
        }
        if(i == 3)
        {
            if(currentPos >= (int) block.size())
                continue;
            else
            {
                propertyIndex = 0;
                i = -1;
            }
        }
    }
    return true;
}
コード例 #4
0
ファイル: dmain.cpp プロジェクト: Ablu/freeorion
int main(int argc, char* argv[]) {
    InitDirs(argv[0]);
    std::vector<std::string> args;
    for (int i = 0; i < argc; ++i)
        args.push_back(argv[i]);

#else
int wmain(int argc, wchar_t* argv[], wchar_t* envp[]) {
    // copy UTF-16 command line arguments to UTF-8 vector
    std::vector<std::string> args;
    for (int i = 0; i < argc; ++i) {
        std::wstring argi16(argv[i]);
        std::string argi8;
        utf8::utf16to8(argi16.begin(), argi16.end(), std::back_inserter(argi8));
        args.push_back(argi8);
    }
    InitDirs((args.empty() ? "" : *args.begin()));
#endif

    try {
        GetOptionsDB().AddFlag('h', "help", "Print this help message.");

        // read config.xml and set options entries from it, if present
        XMLDoc doc;
        {
            boost::filesystem::ifstream ifs(GetConfigPath());
            if (ifs) {
                doc.ReadDoc(ifs);
                GetOptionsDB().SetFromXML(doc);
            }
        }

        GetOptionsDB().SetFromCommandLine(args);

        if (GetOptionsDB().Get<bool>("help")) {
            GetOptionsDB().GetUsage(std::cerr);
            return 0;
        }

        parse::init();

        ServerApp g_app;
        g_app(); // Calls ServerApp::Run() to run app (intialization and main process loop)

    } catch (const std::invalid_argument& e) {
        Logger().errorStream() << "main() caught exception(std::invalid_arg): " << e.what();
        std::cerr << "main() caught exception(std::invalid_arg): " << e.what() << std::endl;
        return 1;
    } catch (const std::runtime_error& e) {
        Logger().errorStream() << "main() caught exception(std::runtime_error): " << e.what();
        std::cerr << "main() caught exception(std::runtime_error): " << e.what() << std::endl;
        return 1;
    } catch (const std::exception& e) {
        Logger().errorStream() << "main() caught exception(std::exception): " << e.what();
        std::cerr << "main() caught exception(std::exception): " << e.what() << std::endl;
        return 1;
    } catch (...) {
        Logger().errorStream() << "main() caught unknown exception.";
        std::cerr << "main() caught unknown exception." << std::endl;
        return 1;
    }

    return 0;
}
コード例 #5
0
ファイル: Ship.cpp プロジェクト: fatman2021/FreeOrion
Ship::Ship(int empire_id, int design_id, const std::string& species_name,
           int produced_by_empire_id/* = ALL_EMPIRES*/) :
    m_design_id(design_id),
    m_fleet_id(INVALID_OBJECT_ID),
    m_ordered_scrapped(false),
    m_ordered_colonize_planet_id(INVALID_OBJECT_ID),
    m_ordered_invade_planet_id(INVALID_OBJECT_ID),
    m_ordered_bombard_planet_id(INVALID_OBJECT_ID),
    m_last_turn_active_in_combat(INVALID_GAME_TURN),
    m_species_name(species_name),
    m_produced_by_empire_id(produced_by_empire_id)
{
    if (!GetShipDesign(design_id))
        throw std::invalid_argument("Attempted to construct a Ship with an invalid design id");

    if (!m_species_name.empty() && !GetSpecies(m_species_name))
        Logger().debugStream() << "Ship created with invalid species name: " << m_species_name;

    SetOwner(empire_id);

    UniverseObject::Init();

    AddMeter(METER_FUEL);
    AddMeter(METER_MAX_FUEL);
    AddMeter(METER_SHIELD);
    AddMeter(METER_MAX_SHIELD);
    AddMeter(METER_DETECTION);
    AddMeter(METER_STRUCTURE);
    AddMeter(METER_MAX_STRUCTURE);
    AddMeter(METER_BATTLE_SPEED);
    AddMeter(METER_STARLANE_SPEED);

    const std::vector<std::string>& part_names = Design()->Parts();
    for (std::size_t i = 0; i < part_names.size(); ++i) {
        if (part_names[i] != "") {
            const PartType* part = GetPartType(part_names[i]);
            if (!part) {
                Logger().errorStream() << "Ship::Ship couldn't get part with name " << part_names[i];
                continue;
            }

            switch (part->Class()) {
            case PC_SHORT_RANGE:
            case PC_POINT_DEFENSE: {
                m_part_meters[std::make_pair(METER_DAMAGE,              part->Name())];
                m_part_meters[std::make_pair(METER_ROF,                 part->Name())];
                m_part_meters[std::make_pair(METER_RANGE,               part->Name())];
                break;
            }
            case PC_MISSILES: {
                std::pair<std::size_t, std::size_t>& part_missiles =
                    m_missiles[part_names[i]];
                ++part_missiles.first;
                part_missiles.second += boost::get<LRStats>(part->Stats()).m_capacity;
                m_part_meters[std::make_pair(METER_DAMAGE,              part->Name())];
                m_part_meters[std::make_pair(METER_ROF,                 part->Name())];
                m_part_meters[std::make_pair(METER_RANGE,               part->Name())];
                m_part_meters[std::make_pair(METER_SPEED,               part->Name())];
                m_part_meters[std::make_pair(METER_STEALTH,             part->Name())];
                m_part_meters[std::make_pair(METER_STRUCTURE,           part->Name())];
                m_part_meters[std::make_pair(METER_CAPACITY,            part->Name())];
                break;
            }
            case PC_FIGHTERS: {
                std::pair<std::size_t, std::size_t>& part_fighters =
                    m_fighters[part_names[i]];
                ++part_fighters.first;
                part_fighters.second += boost::get<FighterStats>(part->Stats()).m_capacity;
                m_part_meters[std::make_pair(METER_ANTI_SHIP_DAMAGE,    part->Name())];
                m_part_meters[std::make_pair(METER_ANTI_FIGHTER_DAMAGE, part->Name())];
                m_part_meters[std::make_pair(METER_LAUNCH_RATE,         part->Name())];
                m_part_meters[std::make_pair(METER_FIGHTER_WEAPON_RANGE,part->Name())];
                m_part_meters[std::make_pair(METER_SPEED,               part->Name())];
                m_part_meters[std::make_pair(METER_STEALTH,             part->Name())];
                m_part_meters[std::make_pair(METER_STRUCTURE,           part->Name())];
                m_part_meters[std::make_pair(METER_DETECTION,           part->Name())];
                m_part_meters[std::make_pair(METER_CAPACITY,            part->Name())];
                break;
            }
            default:
                break;
            }
        }
    }
}
コード例 #6
0
ファイル: AIInterface.cpp プロジェクト: Nagilum23/freeorion-1
 void ErrorOutput(const std::string& error_text) {
     Logger().errorStream() << error_text;
 }
コード例 #7
0
TVerdict CEntryStatusStep::doTestStepL()
	{
	// don't continue if previous phases have aborted
	if (TestStepResult() != EPass)
		{
		return TestStepResult();
		}

	// Delay briefly to ensure that any update entry steps in concurrent tests can
	// check first (which sets the state to EAwaitingApproval.)
	User::After(KStateCheckDelay);

	_LIT(KCancelMessage, "Cancelling...");

	// Cancel if set to do so before checking state.
	if (iCancelPoint == EAfterOpen)
		{
		Logger().Write(KCancelMessage);
		Session().Cancel();
		}

	iState = Session().GetStateL();
	
	// log the action
	_LIT(KMessageFmt, "State of cache entry for certificate '%S' is %d.");
	Logger().WriteFormat(KMessageFmt, SubjectLC(), iState);
	CleanupStack::PopAndDestroy(1); // subject

	if (iCancelPoint == EAfterGetState)
		{
		Logger().Write(KCancelMessage);
		Session().Cancel();
		iState = Session().GetStateL();
		Logger().WriteFormat(KMessageFmt, SubjectLC(), iState);
		CleanupStack::PopAndDestroy(1); // subject
		}
	else if (iRequestChangeNotify)
		{
		if (iState == EEntryAwaitingApproval || !iRequirePendingApproval)
			{
			TRequestStatus status;
			Session().RequestNotify(status);
			if (iCancelPoint == EAfterChangeNotify)
				{
				Logger().Write(KCancelMessage);
				Session().Cancel();
				}

			User::WaitForRequest(status);

			User::LeaveIfError(status.Int());

			iState = Session().GetStateL();

			// log the action
			_LIT(KMessageFormat, "Got cache change notify for certificate '%S', state = %d.");
			Logger().WriteFormat(KMessageFormat, SubjectLC(), iState);
			CleanupStack::PopAndDestroy(1); // certificate status
			}
		else
			{
			// log the action
			_LIT(KMessageFormat, "Cannot wait for change notify, entry state is not %d (EEntryAwaitingApproval.)");
			Logger().WriteFormat(KMessageFormat, EEntryAwaitingApproval);
			SetTestStepResult(EFail)		;
			}
		}
	
	return TestStepResult();
	
	}
コード例 #8
0
ファイル: CoinChangeTest.cpp プロジェクト: PeterGH/Test
void CoinChangeTest::Init(void)
{
	Add("1", [&](){
		vector<unsigned int> denoms { 1, 3, 4};
		map<unsigned int, unsigned int> changes;
		unsigned int amount = 6;
		Test::CoinChange::ComputeSolution(amount, denoms, changes);
		map<unsigned int, unsigned int>::iterator it;
		Logger().WriteInformation("For amount %d, changes are :\n", amount);
		for (it = changes.begin(); it != changes.end(); it++) {
			Logger().WriteInformation("\tcoint %d, count %d\n", it->first, it->second);
		}

		ASSERT1(changes.size() == 1);
		ASSERT1(changes[3] == 2);
	});

	Add("2", [&](){
		vector<unsigned int> denoms { 1, 5, 10, 25};
		for (int i = 0; i < 100; i ++) {
			unsigned int amount = Test::Random::Next(1, 1000);
			map<unsigned int, unsigned int> changes1;
			map<unsigned int, unsigned int> changes2;
			Test::CoinChange::ComputeSolution(amount, denoms, changes1);
			Test::CoinChange::GreedySolution(amount, denoms, changes2);

			ASSERT1(changes1.size() == changes2.size());

			map<unsigned int, unsigned int>::iterator it;
			Logger().WriteInformation("Run %d, amount %d, changes are :\n", i, amount);
			for (it = changes1.begin(); it != changes1.end(); it++) {
				Logger().WriteInformation("\tcoint %d, count %d\n", it->first, it->second);
				ASSERT1(it->second == changes2[it->first]);
			}
		}
	});

	Add("AllSolutions", [&](){
		auto check = [&](unsigned int sum, vector<unsigned int> & denoms, unsigned int count) {
			vector<map<unsigned int, unsigned int>> solutions;
			Test::CoinChange::ComputeAllSolutions(sum, denoms, solutions);
			Logger().WriteInformation("Sum %d numbers:", sum);
			for_each (denoms.begin(), denoms.end(), [&](unsigned int d){
				Logger().WriteInformation("  %d", d);
			});
			Logger().WriteInformation("\n");
			for_each (solutions.begin(), solutions.end(), [&](map<unsigned int, unsigned int> & m){
				Logger().WriteInformation("  %d = ", sum);
				int i = 0;
				for_each (m.begin(), m.end(), [&](pair<unsigned int, unsigned int> p) {
					if (i != 0) {
						Logger().WriteInformation(" + ");
					}
					Logger().WriteInformation("%d x %d", p.second, p.first);
					i++;
				});
				Logger().WriteInformation("\n");
			});
			ASSERT1(solutions.size() == count);
		};

		vector<unsigned int> denoms { 2, 3, 6, 7 };
		check(7, denoms, 2);
	});

	Add("SubSetSolutions", [&](){
		auto check = [&](unsigned int sum, vector<unsigned int> & denoms, unsigned int count) {
			vector<map<unsigned int, unsigned int>> solutions;
			Test::CoinChange::ComputeSubSetSolutions(sum, denoms, solutions);
			Logger().WriteInformation("Sum %d numbers:", sum);
			for_each (denoms.begin(), denoms.end(), [&](unsigned int d){
				Logger().WriteInformation("  %d", d);
			});
			Logger().WriteInformation("\n");
			for_each (solutions.begin(), solutions.end(), [&](map<unsigned int, unsigned int> & m){
				Logger().WriteInformation("  %d = ", sum);
				int i = 0;
				for_each (m.begin(), m.end(), [&](pair<unsigned int, unsigned int> p) {
					if (i != 0) {
						Logger().WriteInformation(" + ");
					}
					Logger().WriteInformation("%d x %d", p.second, p.first);
					i++;
				});
				Logger().WriteInformation("\n");
			});
			ASSERT1(solutions.size() == count);
		};

		vector<unsigned int> denoms { 2, 3, 6, 7 };
		check(7, denoms, 1);
	});
}
コード例 #9
0
bool DeviceDirect3D::create()
{
	HMODULE libD3D11 = LoadLibrary("d3d11.dll");
	if(!libD3D11)
	{
		Logger() << "Could not load d3d11.dll, you probably do not have DirectX 11 installed.";
		return false;
	}

	HMODULE libCompiler43 = LoadLibrary("d3dcompiler_43.dll");
	if(!libCompiler43)
	{
		Logger() << "Could not load d3dcompiler_43.dll, try updating your DirectX";
		return false;
	}

	//Release handles
	FreeLibrary(libD3D11);
	FreeLibrary(libCompiler43);

	std::vector<IDXGIAdapter1*> adapters;
	if(!getAdapterHandle(&adapters))
	{
		return false;
	}

	UINT createDeviceFlags = 0;
#if defined(_DEBUG)
    createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

	const D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0 /*, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0*/ };
	DXGI_SWAP_CHAIN_DESC sd;
	
	ZeroMemory(&sd,sizeof(sd));
	
	const WindowSettings& ws = getWindow()->getWindowSettings();

	sd.BufferCount = 1;	
	sd.BufferDesc.Width = (UINT)ws.width;
	sd.BufferDesc.Height = (UINT)ws.height;
	sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; //_SRGB;
	sd.BufferDesc.RefreshRate.Numerator = 60;	
	sd.BufferDesc.RefreshRate.Denominator = 1;	
	sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_UNORDERED_ACCESS;
	sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	sd.OutputWindow = static_cast<WindowWinAPI*>(getWindow())->getHandle();
	sd.SampleDesc.Count = 1;
	sd.SampleDesc.Quality = 0;
	sd.Windowed = ws.fullscreen ? FALSE : TRUE;
	
	int selectedAdapterId = ws.gpu;
	IDXGIAdapter* selectedAdapter = nullptr;
	if(selectedAdapterId >= 0) 
	{
		if(selectedAdapterId < (int)adapters.size())
		{
			selectedAdapter = adapters[selectedAdapterId];
		} else {
			LOGFUNCERROR("Selected graphics card " << selectedAdapterId << " does not exist");
		}
	}

	HRESULT result = D3D11CreateDeviceAndSwapChain(selectedAdapter, selectedAdapter ? D3D_DRIVER_TYPE_UNKNOWN : D3D_DRIVER_TYPE_HARDWARE, 0, createDeviceFlags, featureLevels,
                        _countof(featureLevels), D3D11_SDK_VERSION, &sd, &swapChain, &device, &featureLevel, &context);

	if(result != S_OK)
	{
		if(result == DXGI_ERROR_UNSUPPORTED)
		{
			LOGFUNCERROR("Your videocard does not appear to support DirectX 11");
		} else {
			LOGERROR(result, "D3D11CreateDeviceAndSwapChain");
		}
		return false;
	}

	//D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;	
	/*result = device->CreateShaderResourceView(swapBackBuffer, 0, &swapBackBufferSRV);

	if(result != S_OK){
		LOGERROR(result, "ID3D11Device::CreateShaderResourceView");
		return false;
	}*/

	D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS dxHwOpt;
	result = device->CheckFeatureSupport(D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS, &dxHwOpt, sizeof(dxHwOpt));
	if(FAILED(result))
	{
		LOGERROR(result, "CheckFeatureSupport");
		return false;
	}
	if(!dxHwOpt.ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x)
	{
		Logger() << "ComputeShaders are not supported on this device";
		return false;
	}
	
	//Get the buffer from the swapchain
	result = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&swapBackBuffer);
	if(result != S_OK)
    {
		LOGERROR(result, "IDXGISwapChain::GetBuffer");
        return false;
    }

	//Create trace result texture/RT
	swapStaging = static_cast<TextureDirect3D*>(createTexture());
	swapStaging->create(TextureDimensions::Texture2D, TextureFormat::R8G8B8A8_UNORM, sd.BufferDesc.Width, sd.BufferDesc.Height, nullptr, TextureBinding::Staging, CPUAccess::Read);
	/*result = device->CreateRenderTargetView(traceResultTexture->getResource(), nullptr, &traceResultRT);
	if(FAILED(result))
	{
		LOGERROR(result, "CreateRenderTargetView");
		return false;
	}*/

	//Create the UAV for the trace result
	D3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc;
	ZeroMemory(&uavDesc, sizeof(uavDesc));
	uavDesc.Format = sd.BufferDesc.Format;
	uavDesc.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D;
	uavDesc.Buffer.FirstElement = 0; 
	uavDesc.Buffer.NumElements = sd.BufferDesc.Width * sd.BufferDesc.Height;

	result = device->CreateUnorderedAccessView(swapBackBuffer, &uavDesc, &uavSwapBuffer);
	if(FAILED(result))
	{
		LOGERROR(result, "CreateUnorderedAccessView");
		return false;
	}

	//Setup sampler
	D3D11_SAMPLER_DESC samplerDesc;
	ZeroMemory(&samplerDesc, sizeof(samplerDesc));
	samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; //D3D11_FILTER_ANISOTROPIC;
	samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.MinLOD = 0;
	samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
	samplerDesc.MipLODBias = 0.0f;
	samplerDesc.MaxAnisotropy = 0;
	samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;

	ID3D11SamplerState* sampler;
	device->CreateSamplerState(&samplerDesc, &sampler);
	context->CSSetSamplers(0, 1, &sampler);
	sampler->Release();

	return true;
}
コード例 #10
0
enum TVerdict CEsockTest11_3::easyTestStepL()
	{
	TInetAddr addrLocal, addrRemote;
	TRequestStatus wstat, wstat2, wstat3, rstat;
	TInt sockIndex1, sockIndex2, sockIndex3;
	
	const TInt KBufSize = 4024;
	// Constructs an empty 8 bit modifiable buffer descriptor. It contains no data.
	typedef TBuf8<KBufSize> TBuffer;
	
	// get local ip address
	TESTL(GetIpAddressFromConfig(_L("Test_11.3"), _L("ipAddressLocal"), addrLocal));
	
	// get ip address to connect to (usually loopback)
	TESTL(GetIpAddressFromConfig(_L("Test_11.3"), _L("ipAddressRemote"), addrRemote));
	
	// open socket and listen for connect requests
	TESTL(KErrNone == OpenListeningSocketL(addrLocal, sockIndex1));
	
	// open active socket and make connect request
	TESTL(KErrNone == OpenActiveSocketL(addrRemote, sockIndex2));
	
	// accept connect request
	TESTL(KErrNone == AcceptConnectionL(sockIndex3, sockIndex1));
	
	TBuffer* wtemp=new (ELeave) TBuffer;
	CleanupStack::PushL(wtemp);
	TBuffer& wbuf=*wtemp;
	
	TBuffer* rtemp=new (ELeave) TBuffer;
	CleanupStack::PushL(rtemp);
	TBuffer& rbuf=*rtemp;
	
	wbuf.SetMax();
	StripeDes(wbuf, 0, wbuf.Length(), '@', 'Z');
	
	iEsockSuite->GetSocketHandle(sockIndex2).Send(wbuf, 0, wstat);
	iEsockSuite->GetSocketHandle(sockIndex2).Send(wbuf, 0, wstat2);
	iEsockSuite->GetSocketHandle(sockIndex2).Send(wbuf, 0, wstat3);
	iEsockSuite->GetSocketHandle(sockIndex2).CancelAll();
	User::WaitForRequest(wstat);
	User::WaitForRequest(wstat2);
	User::WaitForRequest(wstat3);
	TESTEL(wstat==KErrNone || wstat==KErrCancel, wstat.Int());
	TESTEL(wstat2==KErrNone || wstat2==KErrCancel, wstat2.Int());
	TESTEL(wstat3==KErrNone || wstat3==KErrCancel, wstat3.Int());
	
	Logger().WriteFormat(_L("stat1 %d stat2 %d stat3 %d"),wstat.Int(), wstat2.Int(), wstat3.Int());
	
	iEsockSuite->GetSocketHandle(sockIndex3).Recv(rbuf, 0, rstat);
	iEsockSuite->GetSocketHandle(sockIndex3).CancelAll();
	User::WaitForRequest(rstat);
	TESTEL(rstat==KErrNone || rstat==KErrCancel, rstat.Int());
	
	iEsockSuite->GetSocketHandle(sockIndex2).Shutdown(RSocket::ENormal, wstat);
	iEsockSuite->GetSocketHandle(sockIndex3).Shutdown(RSocket::ENormal, rstat);
	iEsockSuite->GetSocketHandle(sockIndex2).CancelAll();
	iEsockSuite->GetSocketHandle(sockIndex3).CancelAll();
	User::WaitForRequest(wstat);
	User::WaitForRequest(rstat);
	TESTEL(wstat == KErrNone, wstat.Int());
	TESTEL(rstat == KErrNone, rstat.Int());

	CleanupStack::PopAndDestroy(2, wtemp);
	
	// shutdown the client socket - do not wait for completion
	CloseSockets(2);
	return EPass;
	}
コード例 #11
0
enum TVerdict CEsockTest11_4::easyTestStepL()
	{
	//
	// Out Of Memory Test on open() RSocket //
	//

	TVerdict verdict = EPass;
	
	Logger().WriteFormat(_L("TE_ESock: test 11.4"));
	Logger().WriteFormat(_L("RSocket Open"));

#if defined (_DEBUG_SOCKET_FUNCTIONS)

	RSocketServ socketHelper;
	CleanupClosePushL(socketHelper);
	TInt ret = socketHelper.Connect();
	TESTEL(KErrNone == ret, ret);

	// Create a socket on the helper to get the DND up & running
	RSocket sockHelper;
	CleanupClosePushL(sockHelper);
	ret = sockHelper.Open(socketHelper, KAfInet, KSockStream, KProtocolInetTcp);
	TESTEL(KErrNone == ret, ret);
	// Short wait for DND settle down
    User::After(5000000);
	socketHelper.__DbgMarkHeap();

	RSocketServ socketServer;
	CleanupClosePushL(socketServer);
	ret = socketServer.Connect();
	TESTEL(KErrNone == ret, ret);
	
	// See if we can crash the server:
	RSocket sock;
	CleanupClosePushL(sock);
	TInt failure = 0;

	verdict = EInconclusive;
	TInt prevResult = KErrNoMemory;
	TInt prevOccurs = 0;
	while (EInconclusive == verdict)
		{
		socketServer.__DbgFailNext(failure++);
		ret = sock.Open(socketServer, KAfInet, KSockStream, KProtocolInetTcp);
		
		if ((prevResult != ret) || (++prevOccurs >= 1000))
			{
			Logger().WriteFormat(_L("%d loop(s), open socket returned %d"), prevOccurs, prevResult);
			if (KErrNone == ret)
				{
				verdict = EPass;
				}
			else if (KErrServerTerminated == ret)
				{
				verdict = EFail;
				}
			else if (prevResult != ret)
				{
				prevResult = ret;
				prevOccurs = 1;
				}
			else
				{
				prevOccurs = 0;
				}
			}
		};
	
	socketServer.__DbgFailNext(-1);
	// wait for protocol families to unload - it's via an async callback and dependent upon the IP stack, which
	// may also be killing off DND. So a big delay is needed. If it proves unreliable in future then the really
	// strong approach would be shutting down ESOCK - it'll panic if it has allocations outstanding
    User::After(5000000);
	socketHelper.__DbgMarkEnd(0);
	CleanupStack::PopAndDestroy(4, &socketHelper);

#else
	Logger().WriteFormat(_L("Test disabled on release build."));
#endif
	
	return verdict;
	}
コード例 #12
0
ファイル: HumanClientFSM.cpp プロジェクト: anarsky/freeorion
boost::statechart::result IntroMenu::react(const JoinMPGameRequested& a) {
    if (TRACE_EXECUTION) Logger().debugStream() << "(HumanClientFSM) IntroMenu.JoinMPGameRequested";
    return transit<WaitingForMPJoinAck>();
}
コード例 #13
0
ファイル: HumanClientFSM.cpp プロジェクト: anarsky/freeorion
boost::statechart::result IntroMenu::react(const HostSPGameRequested& a) {
    if (TRACE_EXECUTION) Logger().debugStream() << "(HumanClientFSM) IntroMenu.HostSPGameRequested";
    context<HumanClientFSM>().m_next_waiting_for_data_mode = a.m_waiting_for_data_mode;
    return transit<WaitingForSPHostAck>();
}
コード例 #14
0
ファイル: HumanClientFSM.cpp プロジェクト: anarsky/freeorion
boost::statechart::result ResolvingCombat::react(const CombatEnd& msg) {
    if (TRACE_EXECUTION) Logger().debugStream() << "(HumanClientFSM) ResolvingCombat.CombatEnd";
    return transit<WaitingForTurnDataIdle>();
}
コード例 #15
0
ファイル: AIInterface.cpp プロジェクト: Nagilum23/freeorion-1
 void DoneCombatTurn() {
     Logger().debugStream() << "AIInterface::DoneCombatTurn()";
     AIClientApp::GetApp()->StartCombatTurn(); // encodes combat order sets and sends combat turn orders message.  "done" the combat turn for the client, but "starts" the combat turn for the server
 }
コード例 #16
0
ファイル: CombatSystem.cpp プロジェクト: e-h-j/freeorion
CombatInfo::CombatInfo(int system_id_, int turn_) :
    turn(turn_),
    system_id(system_id_)
{
    TemporaryPtr<System> system = ::GetSystem(system_id);
    if (!system) {
        Logger().errorStream() << "CombatInfo constructed with invalid system id: " << system_id;
        return;
    }

    // add system to full / complete objects in combat - NOTE: changed from copy of system
    objects.Insert(system);


    // find ships and their owners in system
    std::vector<TemporaryPtr<Ship> > ships =
        Objects().FindObjects<Ship>(system->ShipIDs());

    for (std::vector<TemporaryPtr<Ship> >::const_iterator ship_it = ships.begin();
         ship_it != ships.end(); ++ship_it)
    {
        TemporaryPtr<Ship> ship = *ship_it;
        // add owner to empires that have assets in this battle
        empire_ids.insert(ship->Owner());

        objects.Insert(ship);
    }

    // find planets and their owners in system
    std::vector<TemporaryPtr<Planet> > planets =
        Objects().FindObjects<Planet>(system->PlanetIDs());

    for (std::vector<TemporaryPtr<Planet> >::const_iterator planet_it = planets.begin();
         planet_it != planets.end(); ++planet_it)
    {
        TemporaryPtr<Planet> planet = *planet_it;
        // if planet is populated, add owner to empires that have assets in this battle
        if (planet->CurrentMeterValue(METER_POPULATION) > 0.0)
            empire_ids.insert(planet->Owner());

        objects.Insert(planet);
    }

    // TODO: should buildings be considered separately?

    // now that all participants in the battle have been found, loop through
    // objects again to assemble each participant empire's latest
    // known information about all objects in this battle

    // system
    for (std::set<int>::const_iterator empire_it = empire_ids.begin();
         empire_it != empire_ids.end(); ++empire_it)
    {
        int empire_id = *empire_it;
        if (empire_id == ALL_EMPIRES)
            continue;
        empire_known_objects[empire_id].Insert(GetEmpireKnownSystem(system->ID(), empire_id));
    }

    // ships
    for (std::vector<TemporaryPtr<Ship> >::const_iterator it = ships.begin();
         it != ships.end(); ++it)
    {
        TemporaryPtr<Ship> ship = *it;
        int ship_id = ship->ID();
        TemporaryPtr<const Fleet> fleet = GetFleet(ship->FleetID());
        if (!fleet) {
            Logger().errorStream() << "CombatInfo::CombatInfo couldn't get fleet with id "
                                   << ship->FleetID() << " in system " << system->Name() << " (" << system_id << ")";
            continue;
        }

        for (std::set<int>::const_iterator empire_it = empire_ids.begin();
             empire_it != empire_ids.end(); ++empire_it)
        {
            int empire_id = *empire_it;
            if (empire_id == ALL_EMPIRES)
                continue;
            if (GetUniverse().GetObjectVisibilityByEmpire(ship_id, empire_id) >= VIS_BASIC_VISIBILITY ||
                   (fleet->Aggressive() &&
                       (empire_id == ALL_EMPIRES ||
                        fleet->Unowned() ||
                        Empires().GetDiplomaticStatus(empire_id, fleet->Owner()) == DIPLO_WAR)))
            { empire_known_objects[empire_id].Insert(GetEmpireKnownShip(ship->ID(), empire_id));}
        }
    }

    // planets
    for (std::vector<TemporaryPtr<Planet> >::const_iterator it = planets.begin();
         it != planets.end(); ++it)
    {
        TemporaryPtr<Planet> planet = *it;
        int planet_id = planet->ID();

        for (std::set<int>::const_iterator empire_it = empire_ids.begin(); empire_it != empire_ids.end(); ++empire_it) {
            int empire_id = *empire_it;
            if (empire_id == ALL_EMPIRES)
                continue;
            if (GetUniverse().GetObjectVisibilityByEmpire(planet_id, empire_id) >= VIS_BASIC_VISIBILITY) {
                empire_known_objects[empire_id].Insert(GetEmpireKnownPlanet(planet->ID(), empire_id));
            }
        }
    }

    // after battle is simulated, any changes to latest known or actual objects
    // will be copied back to the main Universe's ObjectMap and the Universe's
    // empire latest known objects ObjectMap - NOTE: Using the real thing now
}
コード例 #17
0
ファイル: AIInterface.cpp プロジェクト: Nagilum23/freeorion-1
 void LogOutput(const std::string& log_text) {
     Logger().debugStream() << log_text;
 }
コード例 #18
0
ファイル: CombatSystem.cpp プロジェクト: e-h-j/freeorion
void AutoResolveCombat(CombatInfo& combat_info) {
    if (combat_info.objects.Empty())
        return;

    TemporaryPtr<const System> system = combat_info.objects.Object<System>(combat_info.system_id);
    if (!system)
        Logger().errorStream() << "AutoResolveCombat couldn't get system with id " << combat_info.system_id;
    else
        Logger().debugStream() << "AutoResolveCombat at " << system->Name();

    if (GetOptionsDB().Get<bool>("verbose-logging")) {
        Logger().debugStream() << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%";
        Logger().debugStream() << "AutoResolveCombat objects before resolution: " << combat_info.objects.Dump();
    }

    // reasonably unpredictable but reproducible random seeding
    const int base_seed = combat_info.objects.begin()->ID() + CurrentTurn();


    // compile list of valid objects to attack or be attacked in this combat
    std::set<int> valid_target_object_ids;                          // all objects that can be attacked
    std::set<int> valid_attacker_object_ids;                        // all objects that can attack
    std::map<int, std::set<int> > empire_valid_attacker_object_ids; // objects that can attack that each empire owns
    float monster_detection = 0.0;

    for (ObjectMap::iterator<> it = combat_info.objects.begin(); it != combat_info.objects.end(); ++it) {
        TemporaryPtr<const UniverseObject> obj = *it;
        //Logger().debugStream() << "Considerting object " << obj->Name() << " owned by " << obj->Owner();
        if (ObjectCanAttack(obj)) {
            //Logger().debugStream() << "... can attack";
            valid_attacker_object_ids.insert(it->ID());
            empire_valid_attacker_object_ids[obj->Owner()].insert(it->ID());
        }
        if (ObjectCanBeAttacked(obj)) {
            //Logger().debugStream() << "... can be attacked";
            valid_target_object_ids.insert(it->ID());
        }
        if (obj->Unowned() && obj->ObjectType() == OBJ_SHIP)
            monster_detection = std::max(monster_detection, obj->CurrentMeterValue(METER_DETECTION));
    }


    // map from empire to set of IDs of objects that empire's objects
    // could potentially target.
    std::map<int, std::set<int> > empire_valid_target_object_ids;   // objects that each empire can attack
    for (std::set<int>::const_iterator target_it = valid_target_object_ids.begin();
         target_it != valid_target_object_ids.end(); ++target_it)
    {
        int object_id = *target_it;
        TemporaryPtr<const UniverseObject> obj = combat_info.objects.Object(object_id);
        //Logger().debugStream() << "Considering attackability of object " << obj->Name() << " owned by " << obj->Owner();

        // for all empires, can they attack this object?
        for (std::set<int>::const_iterator empire_it = combat_info.empire_ids.begin();
             empire_it != combat_info.empire_ids.end(); ++empire_it)
        {
            int attacking_empire_id = *empire_it;
            if (attacking_empire_id == ALL_EMPIRES) {
                if (ObjectAttackableByMonsters(obj, monster_detection)) {
                    //Logger().debugStream() << "object: " << obj->Name() << " attackable by monsters";
                    empire_valid_target_object_ids[ALL_EMPIRES].insert(object_id);
                }

            } else {
                // call function to find if empires can attack objects...
                if (ObjectAttackableByEmpire(obj, attacking_empire_id)) {
                    //Logger().debugStream() << "object: " << obj->Name() << " attackable by empire " << attacking_empire_id;
                    empire_valid_target_object_ids[attacking_empire_id].insert(object_id);
                }
            }
        }
    }


    // Each combat "round" a randomly-selected object in the battle attacks
    // something, if it is able to do so.  The number of rounds scales with the
    // number of objects, so the total actions per object is independent of
    // number of objects in the battle
    const int NUM_COMBAT_ROUNDS = 3*valid_attacker_object_ids.size();

    for (int round = 1; round <= NUM_COMBAT_ROUNDS; ++round) {
        Seed(base_seed + round);    // ensure each combat round produces different results

        // ensure something can attack and something can be attacked
        if (valid_attacker_object_ids.empty()) {
            if (GetOptionsDB().Get<bool>("verbose-logging"))
                Logger().debugStream() << "Nothing left can attack; combat over";
            break;
        }
        if (empire_valid_target_object_ids.empty()) {
            if (GetOptionsDB().Get<bool>("verbose-logging"))
                Logger().debugStream() << "Nothing left can be attacked; combat over";
            break;
        }
        // empires may have valid targets, but nothing to attack with.  If all
        // empires have no attackers or no valid targers, combat is over
        bool someone_can_attack_something = false;
        for (std::map<int, std::set<int> >::const_iterator attacker_it = empire_valid_attacker_object_ids.begin();
             attacker_it != empire_valid_attacker_object_ids.end(); ++attacker_it)
        {
            if (empire_valid_target_object_ids.find(attacker_it->first) != empire_valid_target_object_ids.end()) {
                someone_can_attack_something = true;
                break;
            }
        }
        if (!someone_can_attack_something) {
            if (GetOptionsDB().Get<bool>("verbose-logging"))
                Logger().debugStream() << "No empire has valid targets and something to attack with; combat over.";
            break;
        }

        if (GetOptionsDB().Get<bool>("verbose-logging"))
            Logger().debugStream() << "Combat at " << system->Name() << " (" << combat_info.system_id << ") Round " << round;

        // select attacking object in battle
        int attacker_idx = RandInt(0, valid_attacker_object_ids.size() - 1);
        if (GetOptionsDB().Get<bool>("verbose-logging"))
            Logger().debugStream() << "Battle round " << round << " attacker index: " << attacker_idx << " of " << valid_attacker_object_ids.size() - 1;
        std::set<int>::const_iterator attacker_it = valid_attacker_object_ids.begin();
        std::advance(attacker_it, attacker_idx);
        assert(attacker_it != valid_attacker_object_ids.end());
        int attacker_id = *attacker_it;

        TemporaryPtr<UniverseObject> attacker = combat_info.objects.Object(attacker_id);
        if (!attacker) {
            Logger().errorStream() << "AutoResolveCombat couldn't get object with id " << attacker_id;
            continue;
        }
        if (GetOptionsDB().Get<bool>("verbose-logging"))
            Logger().debugStream() << "Attacker: " << attacker->Name();


        TemporaryPtr<Ship> attack_ship = boost::dynamic_pointer_cast<Ship>(attacker);
        TemporaryPtr<Planet> attack_planet = boost::dynamic_pointer_cast<Planet>(attacker);

        // loop over weapons of attacking object.  each gets a shot at a
        // randomly selected target object
        std::vector<PartAttackInfo> weapons;

        if (attack_ship) {
            weapons = ShipWeaponsStrengths(attack_ship);
            for (std::vector<PartAttackInfo>::const_iterator part_it = weapons.begin();
                 part_it != weapons.end(); ++part_it)
            {
                if (GetOptionsDB().Get<bool>("verbose-logging")) {
                    Logger().debugStream() << "weapon: " << part_it->part_type_name
                                           << " attack: " << part_it->part_attack;
                }
            }
        } else if (attack_planet) { // treat planet defenses as short range
            weapons.push_back(PartAttackInfo(PC_SHORT_RANGE, "", attack_planet->CurrentMeterValue(METER_DEFENSE)));
        }

        if (weapons.empty()) {
            if (GetOptionsDB().Get<bool>("verbose-logging"))
                Logger().debugStream() << "no weapons' can't attack";
            continue;   // no ability to attack!
        }

        for (std::vector<PartAttackInfo>::const_iterator weapon_it = weapons.begin();
             weapon_it != weapons.end(); ++weapon_it)
        {
            // select object from valid targets for this object's owner   TODO: with this weapon...
            if (GetOptionsDB().Get<bool>("verbose-logging"))
                Logger().debugStream() << "Attacking with weapon " << weapon_it->part_type_name << " with power " << weapon_it->part_attack;

            // get valid targets set for attacker owner.  need to do this for
            // each weapon that is attacking, as the previous shot might have
            // destroyed something
            int attacker_owner_id = attacker->Owner();

            std::map<int, std::set<int> >::iterator target_vec_it = empire_valid_target_object_ids.find(attacker_owner_id);
            if (target_vec_it == empire_valid_target_object_ids.end() || target_vec_it->second.empty()) {
                if (GetOptionsDB().Get<bool>("verbose-logging"))
                    Logger().debugStream() << "No targets for attacker with id: " << attacker_owner_id;
                break;
            }

            const std::set<int>& valid_target_ids = target_vec_it->second;

            // DEBUG
            std::string id_list;
            for (std::set<int>::const_iterator target_it = valid_target_ids.begin();
                    target_it != valid_target_ids.end(); ++target_it)
            { id_list += boost::lexical_cast<std::string>(*target_it) + " "; }

            if (GetOptionsDB().Get<bool>("verbose-logging")) { 
                Logger().debugStream() << "Valid targets for attacker with id: " << attacker_owner_id
                                    << " owned by empire: " << attacker_owner_id
                                    << " :  " << id_list;
            }
            // END DEBUG


            // select target object
            int target_idx = RandInt(0, valid_target_ids.size() - 1);
            if (GetOptionsDB().Get<bool>("verbose-logging"))
                Logger().debugStream() << " ... target index: " << target_idx << " of " << valid_target_ids.size() - 1;
            std::set<int>::const_iterator target_it = valid_target_ids.begin();
            std::advance(target_it, target_idx);
            assert(target_it != valid_target_ids.end());
            int target_id = *target_it;

            TemporaryPtr<UniverseObject> target = combat_info.objects.Object(target_id);
            if (!target) {
                Logger().errorStream() << "AutoResolveCombat couldn't get target object with id " << target_id;
                continue;
            }
            if (GetOptionsDB().Get<bool>("verbose-logging"))
                Logger().debugStream() << "Target: " << target->Name();


            // do actual attacks, and mark attackers as valid targets for attacked object's owners
            if (attack_ship) {
                if (TemporaryPtr<Ship> target_ship = boost::dynamic_pointer_cast<Ship>(target)) {
                    AttackShipShip(attack_ship, weapon_it->part_attack, target_ship, combat_info, round);
                    empire_valid_target_object_ids[target_ship->Owner()].insert(attacker_id);
                } else if (TemporaryPtr<Planet> target_planet = boost::dynamic_pointer_cast<Planet>(target)) {
                    AttackShipPlanet(attack_ship, weapon_it->part_attack,  target_planet, combat_info, round);
                    empire_valid_target_object_ids[target_planet->Owner()].insert(attacker_id);
                }
            } else if (attack_planet) {
                if (TemporaryPtr<Ship> target_ship = boost::dynamic_pointer_cast<Ship>(target)) {
                    AttackPlanetShip(attack_planet, target_ship, combat_info, round);
                    empire_valid_target_object_ids[target_ship->Owner()].insert(attacker_id);
                } else if (TemporaryPtr<Planet> target_planet = boost::dynamic_pointer_cast<Planet>(target)) {
                    AttackPlanetPlanet(attack_planet, target_planet, combat_info, round);
                    empire_valid_target_object_ids[target_planet->Owner()].insert(attacker_id);
                }
            }


            // check for destruction of target object
            if (target->ObjectType() == OBJ_SHIP) {
                if (target->CurrentMeterValue(METER_STRUCTURE) <= 0.0) {
                    if (GetOptionsDB().Get<bool>("verbose-logging"))
                        Logger().debugStream() << "!! Target Ship is destroyed!";
                    // object id destroyed
                    combat_info.destroyed_object_ids.insert(target_id);
                    // all empires in battle know object was destroyed
                    for (std::set<int>::const_iterator it = combat_info.empire_ids.begin();
                         it != combat_info.empire_ids.end(); ++it)
                    {
                        int empire_id = *it;
                        if (empire_id != ALL_EMPIRES) {
                            if (GetOptionsDB().Get<bool>("verbose-logging"))
                                Logger().debugStream() << "Giving knowledge of destroyed object " << target_id << " to empire " << empire_id;
                            combat_info.destroyed_object_knowers[empire_id].insert(target_id);
                        }
                    }

                    // remove destroyed ship's ID from lists of valid attackers and targets
                    valid_attacker_object_ids.erase(target_id);
                    valid_target_object_ids.erase(target_id);   // probably not necessary as this set isn't used in this loop

                    for (target_vec_it = empire_valid_target_object_ids.begin();
                         target_vec_it != empire_valid_target_object_ids.end(); ++target_vec_it)
                    { target_vec_it->second.erase(target_id); }

                    for (target_vec_it = empire_valid_attacker_object_ids.begin();
                         target_vec_it != empire_valid_attacker_object_ids.end(); ++target_vec_it)
                    { target_vec_it->second.erase(target_id); } // TODO: only erase from owner's entry in this list
                }

            } else if (target->ObjectType() == OBJ_PLANET) {
                if (!ObjectCanAttack(target) && valid_attacker_object_ids.find(target_id)!=valid_attacker_object_ids.end()) {
                    if (GetOptionsDB().Get<bool>("verbose-logging"))
                        Logger().debugStream() << "!! Target Planet defenses knocked out, can no longer attack";
                    // remove disabled planet's ID from lists of valid attackers
                    valid_attacker_object_ids.erase(target_id);
                }
                if (target->CurrentMeterValue(METER_SHIELD) <= 0.0 &&
                    target->CurrentMeterValue(METER_DEFENSE) <= 0.0 &&
                    target->CurrentMeterValue(METER_CONSTRUCTION) <= 0.0)
                {
                    if (GetOptionsDB().Get<bool>("verbose-logging"))
                        Logger().debugStream() << "!! Target Planet is entirely knocked out of battle";

                    // remove disabled planet's ID from lists of valid targets
                    valid_target_object_ids.erase(target_id);   // probably not necessary as this set isn't used in this loop

                    for (target_vec_it = empire_valid_target_object_ids.begin();
                         target_vec_it != empire_valid_target_object_ids.end(); ++target_vec_it)
                    { target_vec_it->second.erase(target_id); }

                    for (target_vec_it = empire_valid_attacker_object_ids.begin();
                         target_vec_it != empire_valid_attacker_object_ids.end(); ++target_vec_it)
                    { target_vec_it->second.erase(target_id); } // TODO: only erase from owner's entry in this list
                }
            }

            // check if any empire has no remaining target or attacker objects.
            // If so, remove that empire's entry
            std::map<int, std::set<int> > temp = empire_valid_target_object_ids;
            for (target_vec_it = empire_valid_target_object_ids.begin();
                 target_vec_it != empire_valid_target_object_ids.end(); ++target_vec_it)
            {
                if (target_vec_it->second.empty()) {
                    temp.erase(target_vec_it->first);
                    if (GetOptionsDB().Get<bool>("verbose-logging"))
                        Logger().debugStream() << "No valid targets left for empire with id: " << target_vec_it->first;
                }
            }
            empire_valid_target_object_ids = temp;

            temp = empire_valid_attacker_object_ids;
            for (target_vec_it = empire_valid_attacker_object_ids.begin();
                 target_vec_it != empire_valid_attacker_object_ids.end(); ++target_vec_it)
            {
                if (target_vec_it->second.empty()) {
                    temp.erase(target_vec_it->first);
                    if (GetOptionsDB().Get<bool>("verbose-logging"))
                        Logger().debugStream() << "No valid attacking objects left for empire with id: " << target_vec_it->first;
                }
            }
            empire_valid_attacker_object_ids = temp;
        } // end for over weapons
    } // end for over combat arounds

    // ensure every participant knows what happened.
    // TODO: assemble list of objects to copy for each empire.  this should
    //       include objects the empire already knows about with standard
    //       visibility system, and also any objects the empire knows are
    //       destroyed during this combat...
    for (std::map<int, ObjectMap>::iterator it = combat_info.empire_known_objects.begin();
         it != combat_info.empire_known_objects.end(); ++it)
    { it->second.Copy(combat_info.objects); }

    if (GetOptionsDB().Get<bool>("verbose-logging")) {
        Logger().debugStream() << "AutoResolveCombat objects after resolution: " << combat_info.objects.Dump();

        Logger().debugStream() << "combat event log:";
        for (std::vector<AttackEvent>::const_iterator it = combat_info.combat_events.begin();
            it != combat_info.combat_events.end(); ++it)
        {
            Logger().debugStream() << "rnd: " << it->round << " : "
                                << it->attacker_id << " -> " << it->target_id << " : "
                                << it->damage
                                << (it->target_destroyed ? " (destroyed)" : "");
        }
    }
}
コード例 #19
0
void PlayerListWnd::PlayerRightClicked(GG::ListBox::iterator it, const GG::Pt& pt) {
    // check that a valid player was clicked and that it wasn't this client's own player
    int clicked_player_id = PlayerInRow(it);
    if (clicked_player_id == Networking::INVALID_PLAYER_ID)
        return;
    const ClientApp* app = ClientApp::GetApp();
    if (!app) {
        Logger().errorStream() << "PlayerListWnd::PlayerRightClicked couldn't get client app!";
        return;
    }
    int client_player_id = app->PlayerID();
    if (client_player_id == Networking::INVALID_PLAYER_ID)
        return;
    int client_empire_id = app->EmpireID();

    // get empire id of clicked player
    const std::map<int, PlayerInfo>& players = app->Players();
    std::map<int, PlayerInfo>::const_iterator clicked_player_it = players.find(clicked_player_id);
    if (clicked_player_it == players.end()) {
        Logger().errorStream() << "PlayerListWnd::PlayerRightClicked couldn't find player with id " << clicked_player_id;
        return;
    }
    const PlayerInfo& clicked_player_info = clicked_player_it->second;
    int clicked_empire_id = clicked_player_info.empire_id;

    if (!Empires().Lookup(clicked_empire_id)) {
        Logger().errorStream() << "PlayerListWnd::PlayerRightClicked tried to look up empire id "
                               << clicked_empire_id << " for player " << clicked_player_id
                               << " but couldn't find such an empire";
        return;
    }

    GG::MenuItem menu_contents;
    if (app->GetClientType() == Networking::CLIENT_TYPE_HUMAN_PLAYER) {
        // get diplomatic status between client and clicked empires
        DiplomaticStatus diplo_status = Empires().GetDiplomaticStatus(clicked_empire_id, client_empire_id);
        if (diplo_status == INVALID_DIPLOMATIC_STATUS && clicked_player_id != client_player_id) {
            Logger().errorStream() << "PlayerListWnd::PlayerRightClicked found invalid diplomatic status between client and clicked empires.";
            return;
        }
        DiplomaticMessage existing_message = Empires().GetDiplomaticMessage(clicked_empire_id, client_empire_id);

        // create popup menu with diplomacy options in it
        if ( client_empire_id != ALL_EMPIRES) {
            if (diplo_status == DIPLO_WAR) {
                if (existing_message.GetType() == DiplomaticMessage::PEACE_PROPOSAL) {
                    // who sent message?
                    if (existing_message.SenderEmpireID() == client_empire_id)
                        menu_contents.next_level.push_back(GG::MenuItem(UserString("PEACE_PROPOSAL_CANEL"), 4, false, false));
                    else if (existing_message.SenderEmpireID() == clicked_empire_id)
                        menu_contents.next_level.push_back(GG::MenuItem(UserString("PEACE_ACCEPT"),         3, false, false));

                } else if (existing_message.GetType() == DiplomaticMessage::INVALID_DIPLOMATIC_MESSAGE_TYPE) {
                    menu_contents.next_level.push_back(GG::MenuItem(UserString("PEACE_PROPOSAL"),           2, false, false));
                }

            } else if (diplo_status == DIPLO_PEACE) {
                if (existing_message.GetType() == DiplomaticMessage::INVALID_DIPLOMATIC_MESSAGE_TYPE)
                    menu_contents.next_level.push_back(GG::MenuItem(UserString("WAR_DECLARATION"),          1, false, false));
            }
        }
    }

    menu_contents.next_level.push_back(GG::MenuItem(str(FlexibleFormat(UserString("ENC_LOOKUP")) % Empires().Lookup(clicked_empire_id)->Name()), 5, false, false));

    ClientNetworking& net = HumanClientApp::GetApp()->Networking();

    GG::PopupMenu popup(pt.x, pt.y, ClientUI::GetFont(), menu_contents, ClientUI::TextColor(),
                        ClientUI::WndOuterBorderColor(), ClientUI::WndColor(), ClientUI::EditHiliteColor());
    if (popup.Run()) {
        switch (popup.MenuID()) {
        case 1: {   // WAR_DECLARATION
            net.SendMessage(DiplomacyMessage(client_player_id, clicked_player_id,
                                             WarDeclarationDiplomaticMessage(client_empire_id, clicked_empire_id)));
            break;
        }
        case 2: {   // PEACE_PROPOSAL
            net.SendMessage(DiplomacyMessage(client_player_id, clicked_player_id,
                                             PeaceProposalDiplomaticMessage(client_empire_id, clicked_empire_id)));
            break;
        }
        case 3: {   // PEACE_ACCEPT
            net.SendMessage(DiplomacyMessage(client_player_id, clicked_player_id,
                                             AcceptDiplomaticMessage(client_empire_id, clicked_empire_id)));
            break;
        }
        case 4: {   // PEACE_PROPOSAL_CANEL
            net.SendMessage(DiplomacyMessage(client_player_id, clicked_player_id,
                                             CancelDiplomaticMessage(client_empire_id, clicked_empire_id)));
            break;
        }
        case 5: { // Pedia lookup
            ClientUI::GetClientUI()->ZoomToEmpire(clicked_empire_id);
            break;
        }
        default:
            break;
        }
    }
}
コード例 #20
0
void AnnualEmploymentControl::run()
{
	DM::System * sys = this->getData("City");
	int numberOfJobs;

	DM::Component * city = sys->getAllComponentsInView(this->city)[0];
	numberOfJobs = (int)city->getAttribute("JOBS")->getDouble();

	QSqlDatabase db;
	db = QSqlDatabase::addDatabase("QMYSQL", QUuid::createUuid().toString());
	db.setHostName("127.0.0.1");
	db.setUserName("urbansim");
	db.setPassword("urbansim");

	bool ok = db.open();
	if( ok == false) {
		Logger(Error) << "Database failed";
		return;
	}

	// Setup the db and start using it somewhere after successfully connecting to the server..
	QString dbname = QString::fromStdString("urbansim");
	QString tablename = QString::fromStdString("annual_employment_control_totals");

	QSqlQuery query(db);
	bool sr;
	sr = query.exec("USE "+dbname);

	stringstream ss;

	ss << "CREATE TABLE IF NOT EXISTS ";
	ss << tablename.toStdString();
	ss << " (";
	ss << "year" << " "  << "INT";
	ss << ", ";
	ss << "sector_id" << " "  << "INT";
	ss << ", ";
	ss << "home_based_status" << " "  << "INT";
	ss << ", ";
	ss << "number_of_jobs" << " "  << "INT";
	ss << ")";


	Logger(Debug) << ss.str();
	sr = query.exec(QString::fromStdString(ss.str() ));

	if (!sr) {
		Logger(Error) << query.lastError().text().toStdString();

	}
	stringstream insertstream;
	insertstream << "INSERT INTO " << tablename.toStdString() << "(";
	insertstream << "year";
	insertstream << ", ";
	insertstream << "sector_id";
	insertstream << ", ";
	insertstream << "home_based_status";
	insertstream << ", ";
	insertstream << "number_of_jobs";
	insertstream  << ") " << " VALUES (";

	insertstream << "?";
	insertstream << ", ";
	insertstream << "?";
	insertstream << ", ";
	insertstream << "?" ;
	insertstream << ", ";
	insertstream << "?" ;
	insertstream  << ")";



	for (int y = startYear; y <= endYear; y++) {
		query.prepare(QString::fromStdString(insertstream.str()));
		query.addBindValue(y);
		query.addBindValue(1);
		query.addBindValue(0);
		numberOfJobs = (int) numberOfJobs * this->growthRate;
		query.addBindValue(numberOfJobs);
		if ( !query.exec() )
			Logger(Error) << query.lastError().text().toStdString();
	}

	db.close();

}
コード例 #21
0
TVerdict CEntryStatusStep::doTestStepPreambleL()
	{
	InitializeL();
	SetTestStepResult(EPass);

	_LIT(KRequestChangeNotify, "requestchangenotify");
	_LIT(KCertEntryState, "state");
	_LIT(KNewEntryString, "ENewEntry");
	_LIT(KEntryAwaitingApprovalString, "EEntryAwaitingApproval");
	_LIT(KEntryDeniedString, "EEntryDenied");
	_LIT(KEntryApprovedString, "EEntryApproved");
	_LIT(KCancelPoint, "cancelpoint");
	_LIT(KOpen, "Open");	
	_LIT(KGetState, "GetStateL");
	_LIT(KChangeNotify, "ChangeNotify");

	TPtrC cancelPoint;
	_LIT(KCancelMessageFmt, "This test step will call Cancel() on the cert cache session after %S()");
	if (!GetStringFromConfig(ConfigSection(), KCancelPoint, cancelPoint))
		{
		iCancelPoint = ENoCancel;
		}
	else if (cancelPoint.CompareF(KOpen) == 0)
		{
		iCancelPoint = EAfterOpen;
		Logger().WriteFormat(KCancelMessageFmt, &KOpen);
		}
	else if (cancelPoint.CompareF(KGetState) == 0)
		{
		iCancelPoint = EAfterGetState;
		Logger().WriteFormat(KCancelMessageFmt, &KGetState);
		}
	else if (cancelPoint.CompareF(KChangeNotify) == 0)
		{
		iCancelPoint = EAfterChangeNotify;
		Logger().WriteFormat(KCancelMessageFmt, &KChangeNotify);
		}
	
	// Check if this step should wait for change notification.
	if (!GetBoolFromConfig(ConfigSection(), KRequestChangeNotify, iRequestChangeNotify))
		{
		iRequestChangeNotify = EFalse;
		}
	else if (iRequestChangeNotify)
		{
		if (iCancelPoint == ENoCancel)
			{
			_LIT(KMessage, "This test step will wait for change notification.");
			Logger().Write(KMessage);
			}
		else if (iCancelPoint != EAfterChangeNotify)
			{
			_LIT(KErrorMessage, "Invalid test config, requesting notification but cancelling earlier.");
			Logger().Write(KErrorMessage);
			SetTestStepResult(EAbort);
			return EAbort;
			}

		_LIT(KRequirePendingApproval, "requirependingapproval");
		if (!GetBoolFromConfig(ConfigSection(), KRequirePendingApproval, iRequirePendingApproval))
			{
			iRequirePendingApproval = ETrue;
			}
		if (iRequirePendingApproval)
			{
			_LIT(KMessage2, "This step will fail if the state is not initially EEntryAwaitingApproval.");
			Logger().Write(KMessage2);		
			}
		else
			{
			_LIT(KMessage2, "Notification will be requested even if the state is not initially EEntryAwaitingApproval.");
			Logger().Write(KMessage2);		
			}
		}

	TPtrC expectedState;

	if (!GetStringFromConfig(ConfigSection(), KCertEntryState, expectedState))
		{
		_LIT(KMessage, "Could not read expected certificate approval state from INI, abort.");
		Logger().Write(KMessage);
		
		SetTestStepResult(EAbort);
		}
	else
		{
		_LIT(KMessageFmt, "Certificate state is expected to be %S.");
		if (expectedState.CompareF(KNewEntryString) == 0)
			{
			iExpectedState = ENewEntry;
			Logger().WriteFormat(KMessageFmt, &KNewEntryString);
			}
		else if (expectedState.CompareF(KEntryAwaitingApprovalString) == 0)
			{
			iExpectedState = EEntryAwaitingApproval;
			Logger().WriteFormat(KMessageFmt, &KEntryAwaitingApprovalString);
			}
		else if (expectedState.CompareF(KEntryApprovedString) == 0)
			{
			iExpectedState = EEntryApproved;
			Logger().WriteFormat(KMessageFmt, &KEntryApprovedString);
			}
		else if (expectedState.CompareF(KEntryDeniedString) == 0)
			{
			iExpectedState = EEntryDenied;
			Logger().WriteFormat(KMessageFmt, &KEntryDeniedString);
			}
		else
			{
			_LIT(KMessage, "Invalid expected certificate state, abort.");
			Logger().Write(KMessage);
			SetTestStepResult(EAbort);
			}
		}
	return TestStepResult();
	}
コード例 #22
0
ファイル: AIInterface.cpp プロジェクト: Nagilum23/freeorion-1
 int EmpirePlayerID(int empire_id) {
     int player_id = AIClientApp::GetApp()->EmpirePlayerID(empire_id);
     if (-1 == player_id)
         Logger().debugStream() << "AIInterface::EmpirePlayerID(" << boost::lexical_cast<std::string>(empire_id) << ") - passed an invalid empire_id";
     return player_id;
 }
コード例 #23
0
void SitRepPanel::Update() {
    Logger().debugStream() << "SitRepPanel::Update()";
    m_sitreps_lb->Clear();

    if (m_showing_turn == INVALID_GAME_TURN)
        this->SetName(UserString("SITREP_PANEL_TITLE"));
    else
        this->SetName(boost::io::str(FlexibleFormat(UserString("SITREP_PANEL_TITLE_TURN")) % m_showing_turn));


    // get sitrep entries for this client's player empire, or for all empires
    // if this client is an observer or moderator.
    // todo: double check that no-empire players are actually moderator or
    //       observers, instead of just passing the client empire id.
    std::list<SitRepEntry> currentTurnSitreps;
    GetTurnSitrepsFromEmpire(currentTurnSitreps, HumanClientApp::GetApp()->EmpireID());


    // order sitreps for display
    std::vector<SitRepEntry> orderedSitreps;
    std::vector<std::string> ordered_templates = OrderedSitrepTemplateStrings();
    for (std::vector<std::string>::const_iterator template_it = ordered_templates.begin();
         template_it != ordered_templates.end(); ++template_it)
    {
        for (std::list<SitRepEntry>::iterator sitrep_it = currentTurnSitreps.begin();
             sitrep_it != currentTurnSitreps.end(); sitrep_it++)
        {
            if (sitrep_it->GetTemplateString() == *template_it) {
                //Logger().debugStream() << "saving into orderedSitreps -  sitrep of template "<<*template_it<<" with full string "<< sitrep_it->GetText();
                orderedSitreps.push_back(*sitrep_it);
                //Logger().debugStream()<< "deleting above sitrep from currentTurnSitreps";
                sitrep_it = --currentTurnSitreps.erase(sitrep_it);
            }
        }
    }

    // copy remaining unordered sitreps
    for (std::list<SitRepEntry>::iterator sitrep_it = currentTurnSitreps.begin();
         sitrep_it != currentTurnSitreps.end(); sitrep_it++)
    { orderedSitreps.push_back(*sitrep_it); }

    // create UI rows for all sitrps
    GG::X width = m_sitreps_lb->Width() - 8;
    for (std::vector<SitRepEntry>::iterator sitrep_it = orderedSitreps.begin();
         sitrep_it != orderedSitreps.end(); sitrep_it++)
    { m_sitreps_lb->Insert(new SitRepRow(width, GG::Y(ClientUI::Pts()*2), *sitrep_it)); }

    // if at first turn, disable back button
    if (CurrentTurn() >= 1 && m_showing_turn > 1) {
        m_prev_turn_button->Disable(false);
    } else {
        m_prev_turn_button->Disable();
    }

    // if at current turn, disable forward button
    if (CurrentTurn() >= 1 && m_showing_turn < CurrentTurn()) {
        m_next_turn_button->Disable(false);
        m_last_turn_button->Disable(false);
    } else {
        m_next_turn_button->Disable();
        m_last_turn_button->Disable();
    }
}
コード例 #24
0
ファイル: AIInterface.cpp プロジェクト: Nagilum23/freeorion-1
    int IssueInvadeOrder(int ship_id, int planet_id) {
        int empire_id = AIClientApp::GetApp()->EmpireID();

        // make sure ship_id is a ship...
        TemporaryPtr<const Ship> ship = GetShip(ship_id);
        if (!ship) {
            Logger().errorStream() << "AIInterface::IssueInvadeOrder : passed an invalid ship_id";
            return 0;
        }

        // get fleet of ship
        TemporaryPtr<const Fleet> fleet = GetFleet(ship->FleetID());
        if (!fleet) {
            Logger().errorStream() << "AIInterface::IssueInvadeOrder : ship with passed ship_id has invalid fleet_id";
            return 0;
        }

        // make sure player owns ship and its fleet
        if (!fleet->OwnedBy(empire_id)) {
            Logger().errorStream() << "AIInterface::IssueInvadeOrder : empire does not own fleet of passed ship";
            return 0;
        }
        if (!ship->OwnedBy(empire_id)) {
            Logger().errorStream() << "AIInterface::IssueInvadeOrder : empire does not own passed ship";
            return 0;
        }

        // verify that planet exists and is occupied by another empire
        TemporaryPtr<const Planet> planet = GetPlanet(planet_id);
        if (!planet) {
            Logger().errorStream() << "AIInterface::IssueInvadeOrder : no planet with passed planet_id";
            return 0;
        }
        bool owned_by_invader = planet->OwnedBy(empire_id);
        bool unowned = planet->Unowned();
        bool populated = planet->CurrentMeterValue(METER_POPULATION) > 0.;
        bool visible = GetUniverse().GetObjectVisibilityByEmpire(planet_id, empire_id) >= VIS_PARTIAL_VISIBILITY;
        bool vulnerable = planet->CurrentMeterValue(METER_SHIELD) <= 0.;
        float shields = planet->CurrentMeterValue(METER_SHIELD);
        std::string thisSpecies = planet->SpeciesName();
        //bool being_invaded = planet->IsAboutToBeInvaded();
        bool invadable = !owned_by_invader && vulnerable && (populated || !unowned) && visible ;// && !being_invaded; a 'being_invaded' check prevents AI from invading with multiple ships at once, which is important
        if (!invadable) {
            Logger().errorStream() << "AIInterface::IssueInvadeOrder : planet with passed planet_id "<< planet_id <<" and species "<<thisSpecies<<" is  "
                                   << "not invadable due to one or more of: owned by invader empire, "
                                   << "not visible to invader empire, has shields above zero, "
                                   << "or is already being invaded.";
            if (!unowned) 
                Logger().errorStream() << "AIInterface::IssueInvadeOrder : planet (id " << planet_id << ") is not unowned";
            if (!visible)
                Logger().errorStream() << "AIInterface::IssueInvadeOrder : planet (id " << planet_id << ") is not visible";
            if (!vulnerable)
                Logger().errorStream() << "AIInterface::IssueInvadeOrder : planet (id " << planet_id << ") is not vulnerable, shields at "<<shields;
            return 0;
        }

        // verify that planet is in same system as the fleet
        if (planet->SystemID() != fleet->SystemID()) {
            Logger().errorStream() << "AIInterface::IssueInvadeOrder : fleet and planet are not in the same system";
            return 0;
        }
        if (ship->SystemID() == INVALID_OBJECT_ID) {
            Logger().errorStream() << "AIInterface::IssueInvadeOrder : ship is not in a system";
            return 0;
        }

        AIClientApp::GetApp()->Orders().IssueOrder(OrderPtr(new InvadeOrder(empire_id, ship_id, planet_id)));

        return 1;
    }
コード例 #25
0
ファイル: Ship.cpp プロジェクト: fatman2021/FreeOrion
void Ship::SetSpecies(const std::string& species_name) {
    if (!GetSpecies(species_name))
        Logger().errorStream() << "Ship::SetSpecies couldn't get species with name " << species_name;
    m_species_name = species_name;
}
コード例 #26
0
ファイル: AIInterface.cpp プロジェクト: Nagilum23/freeorion-1
const std::string& AIBase::GetSaveStateString() {
    static std::string default_state_string("AIBase default save state string");
    Logger().debugStream() << "AIBase::GetSaveStateString() returning: " << default_state_string;
    return default_state_string;
}
コード例 #27
0
EReimportResult::Type UReimportFbxSceneFactory::Reimport(UObject* Obj)
{
	ReimportData = GetFbxSceneImportData(Obj);
	if (!ReimportData)
	{
		return EReimportResult::Failed;
	}

	//We will call other factory store the filename value since UFactory::CurrentFilename is static
	FbxImportFileName = ReimportData->SourceFbxFile;

	UnFbx::FFbxImporter* FbxImporter = UnFbx::FFbxImporter::GetInstance();
	UnFbx::FFbxLoggerSetter Logger(FbxImporter);
	GWarn->BeginSlowTask(NSLOCTEXT("FbxSceneReImportFactory", "BeginReImportingFbxSceneTask", "ReImporting FBX scene"), true);

	GlobalImportSettings = FbxImporter->GetImportOptions();

	//Fill the original options
	for (auto kvp : ReimportData->NameOptionsMap)
	{
		if (kvp.Key.Compare(DefaultOptionName) == 0)
		{
			SFbxSceneOptionWindow::CopyFbxOptionsToFbxOptions(kvp.Value, GlobalImportSettings);
			NameOptionsMap.Add(kvp.Key, GlobalImportSettings);
		}
		else
		{
			NameOptionsMap.Add(kvp.Key, kvp.Value);
		}
	}

	//Always convert the scene
	GlobalImportSettings->bConvertScene = true;
	GlobalImportSettings->bImportScene = ReimportData->bImportScene;

	//Read the fbx and store the hierarchy's information so we can reuse it after importing all the model in the fbx file
	if (!FbxImporter->ImportFromFile(*FbxImportFileName, FPaths::GetExtension(FbxImportFileName)))
	{
		// Log the error message and fail the import.
		GWarn->Log(ELogVerbosity::Error, FbxImporter->GetErrorMessage());
		FbxImporter->ReleaseScene();
		FbxImporter = nullptr;
		GWarn->EndSlowTask();
		return EReimportResult::Failed;
	}

	FString PackageName = "";
	Obj->GetOutermost()->GetName(PackageName);
	Path = FPaths::GetPath(PackageName);

	UnFbx::FbxSceneInfo SceneInfo;
	//Read the scene and found all instance with their scene information.
	FbxImporter->GetSceneInfo(FbxImportFileName, SceneInfo);

	//Convert old structure to the new scene export structure
	TSharedPtr<FFbxSceneInfo> SceneInfoPtr = ConvertSceneInfo(&SceneInfo);
	//Get import material info
	ExtractMaterialInfo(FbxImporter, SceneInfoPtr);

	if (!ReimportData->bCreateFolderHierarchy)
	{
		for (TSharedPtr<FFbxMeshInfo> MeshInfo : SceneInfoPtr->MeshInfo)
		{
			FString AssetName = Path + TEXT("/") + MeshInfo->Name;
			MeshInfo->SetOriginalImportPath(AssetName);
			FString OriginalFullImportName = PackageTools::SanitizePackageName(AssetName);
			OriginalFullImportName = OriginalFullImportName + TEXT(".") + PackageTools::SanitizePackageName(MeshInfo->Name);
			MeshInfo->SetOriginalFullImportName(OriginalFullImportName);
		}
	}
	else
	{
		TSet<uint64> AssetPathDone;
		FString AssetPath = Path;
		for (TSharedPtr<FFbxNodeInfo> NodeInfo : SceneInfoPtr->HierarchyInfo)
		{
			//Iterate the hierarchy and build the original path
			RecursivelyCreateOriginalPath(FbxImporter, NodeInfo, AssetPath, AssetPathDone);
		}
	}

	FillSceneHierarchyPath(SceneInfoPtr);

	FbxSceneReimportStatusMap MeshStatusMap;
	FbxSceneReimportStatusMap NodeStatusMap;
	bool bCanReimportHierarchy = ReimportData->HierarchyType == (int32)EFBXSceneOptionsCreateHierarchyType::FBXSOCHT_CreateBlueprint && !ReimportData->BluePrintFullName.IsEmpty();

	if (!GetFbxSceneReImportOptions(FbxImporter
		, SceneInfoPtr
		, ReimportData->SceneInfoSourceData
		, GlobalImportSettings
		, SceneImportOptions
		, SceneImportOptionsStaticMesh
		, NameOptionsMap
		, MeshStatusMap
		, NodeStatusMap
		, bCanReimportHierarchy
		, Path))
	{
		//User cancel the scene import
		FbxImporter->ReleaseScene();
		FbxImporter = nullptr;
		GlobalImportSettings = nullptr;
		GWarn->EndSlowTask();
		return EReimportResult::Cancelled;
	}
	
	GlobalImportSettingsReference = new UnFbx::FBXImportOptions();
	SFbxSceneOptionWindow::CopyFbxOptionsToFbxOptions(GlobalImportSettings, GlobalImportSettingsReference);

	//Overwrite the reimport asset data with the new data
	ReimportData->SceneInfoSourceData = SceneInfoPtr;
	ReimportData->SourceFbxFile = FPaths::ConvertRelativePathToFull(FbxImportFileName);
	ReimportData->bImportScene = GlobalImportSettingsReference->bImportScene;
	//Copy the options map
	ReimportData->NameOptionsMap.Reset();
	for (auto kvp : NameOptionsMap)
	{
		ReimportData->NameOptionsMap.Add(kvp.Key, kvp.Value);
	}

	FAssetRegistryModule& AssetRegistryModule = FModuleManager::LoadModuleChecked<FAssetRegistryModule>("AssetRegistry");
	TArray<FAssetData> AssetDataToDelete;
	for (TSharedPtr<FFbxMeshInfo> MeshInfo : SceneInfoPtr->MeshInfo)
	{
		//Delete all the delete asset
		if (!MeshStatusMap.Contains(MeshInfo->OriginalImportPath))
		{
			continue;
		}
		EFbxSceneReimportStatusFlags MeshStatus = *(MeshStatusMap.Find(MeshInfo->OriginalImportPath));
		if ((MeshStatus & EFbxSceneReimportStatusFlags::Removed) == EFbxSceneReimportStatusFlags::None || (MeshStatus & EFbxSceneReimportStatusFlags::ReimportAsset) == EFbxSceneReimportStatusFlags::None)
		{
			continue;
		}
		//Make sure we load all package that will be deleted
		UPackage* PkgExist = LoadPackage(nullptr, *(MeshInfo->GetImportPath()), LOAD_Verify | LOAD_NoWarn);
		if (PkgExist == nullptr)
		{
			continue;
		}
		PkgExist->FullyLoad();
		//Find the asset
		AssetDataToDelete.Add(AssetRegistryModule.Get().GetAssetByObjectPath(FName(*(MeshInfo->GetFullImportName()))));
	}

	AllNewAssets.Empty();
	AssetToSyncContentBrowser.Empty();
	EReimportResult::Type ReimportResult = EReimportResult::Succeeded;
	//Reimport and add asset
	for (TSharedPtr<FFbxMeshInfo> MeshInfo : SceneInfoPtr->MeshInfo)
	{
		if (!MeshStatusMap.Contains(MeshInfo->OriginalImportPath))
		{
			continue;
		}
		EFbxSceneReimportStatusFlags MeshStatus = *(MeshStatusMap.Find(MeshInfo->OriginalImportPath));
		
		//Set the import status for the next reimport
		MeshInfo->bImportAttribute = (MeshStatus & EFbxSceneReimportStatusFlags::ReimportAsset) != EFbxSceneReimportStatusFlags::None;
		
		if ((MeshStatus & EFbxSceneReimportStatusFlags::Removed) != EFbxSceneReimportStatusFlags::None ||
			(MeshStatus & EFbxSceneReimportStatusFlags::ReimportAsset) == EFbxSceneReimportStatusFlags::None)
		{
			continue;
		}

		if (((MeshStatus & EFbxSceneReimportStatusFlags::Same) != EFbxSceneReimportStatusFlags::None || (MeshStatus & EFbxSceneReimportStatusFlags::Added) != EFbxSceneReimportStatusFlags::None) &&
			(MeshStatus & EFbxSceneReimportStatusFlags::FoundContentBrowserAsset) != EFbxSceneReimportStatusFlags::None)
		{
			//Reimport over the old asset
			if (!MeshInfo->bIsSkelMesh)
			{
				ReimportResult = ReimportStaticMesh(FbxImporter, MeshInfo);
			}
			else
			{
				//TODO reimport skeletal mesh
			}
		}
		else if ((MeshStatus & EFbxSceneReimportStatusFlags::Added) != EFbxSceneReimportStatusFlags::None || (MeshStatus & EFbxSceneReimportStatusFlags::Same) != EFbxSceneReimportStatusFlags::None)
		{
			//Create a package for this node
			//Get Parent hierarchy name to create new package path
			ReimportResult = ImportStaticMesh(FbxImporter, MeshInfo, SceneInfoPtr);
		}
	}

	//Put back the default option in the static mesh import data, so next import will have those last import option
	SFbxSceneOptionWindow::CopyFbxOptionsToFbxOptions(GlobalImportSettingsReference, GlobalImportSettings);
	SFbxSceneOptionWindow::CopyFbxOptionsToStaticMeshOptions(GlobalImportSettingsReference, SceneImportOptionsStaticMesh);
	SceneImportOptionsStaticMesh->FillStaticMeshInmportData(StaticMeshImportData, SceneImportOptions);
	StaticMeshImportData->SaveConfig();

	//Update the blueprint
	UBlueprint *ReimportBlueprint = nullptr;
	if (bCanReimportHierarchy && GlobalImportSettingsReference->bImportScene)
	{
		ReimportBlueprint = UpdateOriginalBluePrint(ReimportData->BluePrintFullName, &NodeStatusMap, SceneInfoPtr, ReimportData->SceneInfoSourceData, AssetDataToDelete);
	}

	//Remove the deleted meshinfo node from the reimport data
	TArray<TSharedPtr<FFbxMeshInfo>> ToRemoveHierarchyNode;
	for (TSharedPtr<FFbxMeshInfo> MeshInfo : ReimportData->SceneInfoSourceData->MeshInfo)
	{
		EFbxSceneReimportStatusFlags MeshStatus = *(MeshStatusMap.Find(MeshInfo->OriginalImportPath));
		if ((MeshStatus & EFbxSceneReimportStatusFlags::Removed) != EFbxSceneReimportStatusFlags::None)
		{
			ToRemoveHierarchyNode.Add(MeshInfo);
		}
	}
	for (TSharedPtr<FFbxMeshInfo> MeshInfo : ToRemoveHierarchyNode)
	{
		ReimportData->SceneInfoSourceData->MeshInfo.Remove(MeshInfo);
	}
	ReimportData->Modify();
	ReimportData->PostEditChange();
	
	//Make sure the content browser is in sync before we delete
	FContentBrowserModule& ContentBrowserModule = FModuleManager::Get().LoadModuleChecked<FContentBrowserModule>("ContentBrowser");
	ContentBrowserModule.Get().SyncBrowserToAssets(AssetToSyncContentBrowser);

	if (AssetDataToDelete.Num() > 0)
	{
		bool AbortDelete = false;
		if (ReimportBlueprint != nullptr)
		{
			//Save the blueprint to avoid reference from the old blueprint
			FAssetData ReimportBlueprintAsset(ReimportBlueprint);
			TArray<UPackage*> Packages;
			Packages.Add(ReimportBlueprintAsset.GetPackage());
			FEditorFileUtils::PromptForCheckoutAndSave(Packages, false, false);

			//Make sure the Asset registry is up to date after the save
			TArray<FString> Paths;
			Paths.Add(ReimportBlueprintAsset.PackagePath.ToString());
			AssetRegistryModule.Get().ScanPathsSynchronous(Paths, true);
		}

		if (!AbortDelete)
		{
			//Delete the asset and use the normal dialog to make sure the user understand he will remove some content
			//The user can decide to cancel the delete or not. This will not interrupt the reimport process
			//The delete is done at the end because we want to remove the blueprint reference before deleting object
			ObjectTools::DeleteAssets(AssetDataToDelete, true);
		}
	}
	//Make sure the content browser is in sync
	ContentBrowserModule.Get().SyncBrowserToAssets(AssetToSyncContentBrowser);
	
	AllNewAssets.Empty();
	
	GlobalImportSettings = nullptr;
	GlobalImportSettingsReference = nullptr;

	FbxImporter->ReleaseScene();
	FbxImporter = nullptr;
	GWarn->EndSlowTask();
	return EReimportResult::Succeeded;
}
コード例 #28
0
ファイル: AIInterface.cpp プロジェクト: Nagilum23/freeorion-1
 void CombatSetup() {
     Logger().debugStream() << "AIInterface::CombatSetup()";
     AIClientApp::GetApp()->SendCombatSetup();
 }
コード例 #29
0
enum TVerdict CSocketTest7_2::InternalDoTestStepL( void )
	{
	TVerdict verdict = EPass;
	
	Logger().WriteFormat(_L("Test Purpose: Alloc Heaven during host resolver open"));
	
#if defined (_DEBUG_SOCKET_FUNCTIONS)
	
	// connect to esock
	Logger().WriteFormat(_L("Attempting to connect to socket server"));
    RSocketServ ss;
	TInt ret = OptimalConnect(ss);
	CleanupClosePushL(ss);
	Logger().WriteFormat(_L("Connect returned %S"), &EpocErrorToText(ret));
	TESTL(KErrNone == ret);
	
	// get a protocol
	Logger().WriteFormat(_L("Attempting to FindProtocol dummy protocol 1"));
	TProtocolDesc protoInfo;
	ret = ss.FindProtocol(_L("Dummy Protocol 1"), protoInfo);
	Logger().WriteFormat(_L("FindProtocol returned %S"), &EpocErrorToText(ret));
	TESTL(KErrNone == ret);
	
	// Stretch host resolver arrays in the  server.
	RHostResolver *hrs = new (ELeave) RHostResolver[KNumStretchOpens];
	CleanupArrayDeletePushL(hrs);
	
	Logger().WriteFormat(_L("Attempting to Open %d host resolvers"), KNumStretchOpens);
	TInt i;
	for (i=0; i<KNumStretchOpens; i++)
		{
		ret = hrs[i].Open(ss, protoInfo.iAddrFamily, protoInfo.iProtocol);
		if (KErrNone != ret)
			{
			Logger().WriteFormat(_L("Open returned %S for host resolver %d"), &EpocErrorToText(ret), i);
			TESTL(EFalse);
			}
		}
	
	Logger().WriteFormat(_L("Closing the first %d host resolvers"), KNumStretchOpens-1);
	for (i=0; i<KNumStretchOpens-1; i++)
		{
		hrs[i].Close();
		}
	
	RHostResolver hr;
	TInt failure = 0;
	ret = -1;
	Logger().WriteFormat(_L("Starting OOM Host Resolver Open Loop"));
	//	ss.__DbgMarkHeap();		// in ESOCKMT leak checking is best done by shutting down the server
	while (ret != KErrNone)
		{
		Logger().WriteFormat(_L("Failing after %d allocs"), failure);
		ss.__DbgFailNext(failure);
		ret = hr.Open(ss, protoInfo.iAddrFamily, protoInfo.iProtocol);
		//		if (ret != KErrNone)
		//			{
		//			ss.__DbgCheckHeap(0);
		//			}
		failure++;
		}
	Logger().WriteFormat(_L("Created Host Resolver OK"));
	
	hrs[KNumStretchOpens-1].Close();
	CleanupStack::PopAndDestroy(hrs);
	hr.Close();
	//	ss.__DbgMarkEnd(0);
	
	// Flush any FailNext there might be hanging around.
	ss.__DbgFailNext(-1);
	
	CleanupStack::Pop(&ss);
	ss.Close();
#else
	Logger().WriteFormat(_L("TestDisabled on release build."));
	verdict = EInconclusive;
#endif
	
	SetTestStepResult(verdict);
	return verdict;
	}
コード例 #30
0
ファイル: HumanClientFSM.cpp プロジェクト: anarsky/freeorion
boost::statechart::result PlayingTurn::react(const TurnEnded& msg) {
    if (TRACE_EXECUTION) Logger().debugStream() << "(HumanClientFSM) PlayingTurn.TurnEnded";
    return transit<WaitingForTurnData>();
}