示例#1
0
// CPopupMenu
HRESULT STDMETHODCALLTYPE CPopupMenu::Initialize(PCIDLIST_ABSOLUTE pidlFolder, IDataObject *pdtobj, HKEY hkeyProgID)
{
	FORMATETC fmt = {CF_HDROP,NULL,DVASPECT_CONTENT,-1,TYMED_HGLOBAL};
	STGMEDIUM stg = {TYMED_HGLOBAL};
	HDROP hDrop;

	if (FAILED(pdtobj->GetData(&fmt,&stg))){
		return E_INVALIDARG;
	}

	hDrop = (HDROP)GlobalLock (stg.hGlobal);

	if (NULL == hDrop){
		return E_INVALIDARG;
	}

	UINT uNumFiles = DragQueryFile (hDrop, 0xFFFFFFFF, NULL, 0);
	HRESULT hr = S_OK;

	if (0 == uNumFiles){
		GlobalUnlock (stg.hGlobal);
		ReleaseStgMedium (&stg);
		return E_INVALIDARG;
	}

	m_NumFiles = uNumFiles;
	char szFile[1024];
	for(int i = 0; i < uNumFiles; i++){
		memset(szFile, 0, sizeof(szFile));
		if (0 == DragQueryFile (hDrop, i, szFile, sizeof(szFile))){
			hr = E_INVALIDARG;
		}
		string sFile(szFile);
		m_Files.push_back(sFile);
	}

	GlobalUnlock (stg.hGlobal);
	ReleaseStgMedium (&stg);

	return hr;
}
bool ThreadSearchLoggerList::GetFileLineFromListEvent(wxListEvent& /*event*/, wxString& filepath, long &line)
{
    bool success = false;
    wxListItem listItem;

    do {
        // Finds selected item index
        long index = m_pListLog->GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED);
        if ( index == -1 ) break;

        // First, gets file dir
        wxString filedir;
        listItem.m_itemId = index;
        listItem.m_col    = 0;
        listItem.m_mask   = wxLIST_MASK_TEXT;

        if ( m_pListLog->GetItem(listItem) == false ) break;

        filedir = listItem.GetText();

        // Then build complete filename from dir and file
        listItem.m_col = 1;
        if ( m_pListLog->GetItem(listItem) == false ) break;

        wxFileName sFile(filedir, listItem.GetText());
        filepath = sFile.GetFullPath();

        // Then gets line number
        listItem.m_col = 2;
        if ( m_pListLog->GetItem(listItem) == false ) break;

        if ( listItem.GetText().ToLong(&line) == true )
        {
            success = true;
        }
    } while ( 0 );

    return success;
}
示例#3
0
void MonsterProperties::setValueFromFile(QString file, bool clearTarget)
{
	InternalOperation = true;
	if (clearTarget){
		targetSprite = NULL;
	}
	QFile sFile(file);
	QJsonObject obj = readFileGetQJsonObject(file);
	if (fileError){
		MyLogger::getInstance()->addWarning("MonsterProperties::setValueFromFile readTemplateFile error, filename " + file);
		InternalOperation = false;
		return;
	}
	templateFile = file;
	QJsonObject properties = obj["monsterProperties"].toObject();

	setCheckState(selectNameVec, properties);

	bool hasMonsterProperties = obj["hasMonsterProperties"].toBool();
	if (targetSprite){
		targetSprite->setHasMoveProperties(hasMonsterProperties);
	}
	if (!hasMonsterProperties){
		this->setVisible(false);
		setDefaultValue();
	}
	else{
		this->setVisible(true);
		hp->setText(QString::number(properties["hp"].toInt()));
		mp->setText(QString::number(properties["mp"].toInt()));
		attack->setText(QString::number(properties["attack"].toInt()));
		defense->setText(QString::number(properties["defense"].toInt()));
		magic_attack->setText(QString::number(properties["magic_attack"].toInt()));
		magic_defense->setText(QString::number(properties["magic_defense"].toInt()));
		speed->setText(QString::number(properties["speed"].toDouble()));
		hardFactor->setText(QString::number(properties["hardFactor"].toDouble()));
	}
	InternalOperation = false;
}
示例#4
0
void MainWindow::on_actionSave_triggered()
{
    if(m_file_name.isEmpty())
    {
        on_actionSave_as_triggered();
    }
    else
    {
        QFile sFile(m_file_name);
        if(sFile.open(QFile::WriteOnly | QFile::Text))
        {
            QTextStream out(&sFile);
            out.setCodec("UTF-8");

            out << m_ui->txtedit->toPlainText();
            m_saved = m_ui->txtedit->toPlainText();

            sFile.flush();
            sFile.close();
        }
    }
    UpdateStatusBar();
}
示例#5
0
	/* reads the .obj file specified in strFileName */
void GenericLoader::readModelFromFile(C3DModel *pModel,const char *strFileName)
{
	string sFile(strFileName);

	size_t pos = sFile.find(".");

	string sType = sFile.substr(pos);

	if(sType == ".obj")
	{
		ObjLoader Loader;
		Loader.readMultiMeshFromFile(pModel,strFileName);
	}//end if
	else if(sType == ".3DS" || sType ==".3ds")
	{
		C3DSLoader Loader;
		Loader.ReadModelFromFile(pModel,strFileName);
	}//end if
	else
	{
	}//end else

}//end ReadModelFromFile
示例#6
0
void Settings::init()
{
    QString hPath = "./config.ini";
    QString sPath = "../confs.ini";

    QFile hFile(hPath);
    if (hFile.open(QIODevice::ReadWrite))
        hFile.close();
    else {
        QMessageBox::critical(
                    NULL,
                    QObject::tr("File cannot be created"),
                    QObject::tr("Horus config file cannot be created."),
                    QObject::tr("Ok"),
                    0);
        exit(EXIT_FAILURE);
    }

    QFile sFile(sPath);
    if (sFile.open(QIODevice::ReadOnly))
        sFile.close();
    else {
        QMessageBox::critical(
                    NULL,
                    QObject::tr("File cannot be opened"),
                    QObject::tr("Server config file cannot be opened."),
                    QObject::tr("Ok"),
                    0);
        exit(EXIT_FAILURE);
    }

    settingsHorus = new QSettings(hPath, QSettings::IniFormat);
    settingsServer = new QSettings(sPath, QSettings::IniFormat);

    settingsHorus->setIniCodec("utf8");
    settingsServer->setIniCodec("utf8");
}
示例#7
0
/**
 * Gets the file content of a given file
 * @param file File
 * @return File content
 */
QString MainWindow::getFileContent(QString file)
{
    QStringList list = file.split( "/" );
    QString fileName = list.value(list.length() - 1 );
    QStringList list2 = fileName.split( "." );
    QString fileFormat = list2.value(list2.length() - 1);

    if ( !fileFormat.contains("sb") ) {
        QMessageBox::critical(this, tr("Error"), tr("There are only formats like 'sb' allowed."));
        qDebug() << "File content could not be loaded because the format is incorrect.";
        return ui->textEdit_mainWindow_surface->toHtml();
    }

    QString text = "";
    QFile sFile(file);
    if (sFile.open(QFile::ReadOnly | QFile::Text) )
    {
        fileName = file;
        QTextStream in(&sFile);
        text = in.readAll();
        sFile.close();
    }
    return text;
}
示例#8
0
void TestLockDocument::TestLockNonExistentAttachment()
{
	DocProviderWorker	objWorker;
	CStdString			sDocID(DocumentID::GetDocProviderId() + TEST_DIRECTORY + TEST_DOC _T(".doc") + _T("?attach.xdf"));
	CStdString			sLockFileName(TEST_DIRECTORY + TEST_DOC _T(".doc") _T("." TEST_DMS_EXT _T("\\Version 1\\attach.xdf_Bones.lock")));
	CStdString			sFile(_T("c:\\Not\\here.doc"));

	::DeleteFile(sFile.c_str());
	::DeleteFile(sLockFileName.c_str());

	WSDocNonCom			wsDoc;
	LockManager			docLock;
	const CStdString	sUsername(_T("Bones"));

	HRESULT hrLock = docLock.CreateLock(sDocID, sUsername);

	if(SUCCEEDED(hrLock))
		assertMessage(false,_T("Reported Succeeded in creating lock on non existent file"));

	if (_taccess(sLockFileName, 0) != -1 )
	{
		assertMessage(false, _T("Lock file exists for a non existent document"));
	}	
}
示例#9
0
DWORD FileMisc::Run(HWND hwnd, LPCTSTR lpFile, LPCTSTR lpDirectory, int nShowCmd)
{
	CString sFile(lpFile), sParams;
	int nHash = sFile.Find(_T('#'));

	if (nHash != -1)
	{
		sParams = sFile.Mid(nHash);
		sFile = sFile.Left(nHash);

		CString sExt;
		SplitPath(sFile, NULL, NULL, NULL, &sExt);

		CString sApp = CFileRegister::GetRegisteredAppPath(sExt);

		if (!sApp.IsEmpty())
		{
			sFile = sApp;
			sParams = lpFile;
		}
		else
		{
			sFile = lpFile;
			sParams.Empty();
		}
	}

	DWORD dwRes = (DWORD)ShellExecute(hwnd, NULL, sFile, sParams, lpDirectory, nShowCmd);

	if (dwRes <= 32) // failure
	{
		// try CreateProcess
		STARTUPINFO si;
		PROCESS_INFORMATION pi;

		ZeroMemory(&si, sizeof(si));
		si.cb = sizeof(si);
		si.wShowWindow = (WORD)nShowCmd;
		si.dwFlags = STARTF_USESHOWWINDOW;

		ZeroMemory(&pi, sizeof(pi));

		// Start the child process.
		if (CreateProcess(NULL,         // No module name (use command line).
			(TCHAR*)lpFile,              // Command line.
			NULL,                        // Process handle not inheritable.
			NULL,                        // Thread handle not inheritable.
			FALSE,                       // Set handle inheritance to FALSE.
			0,                           // No creation flags.
			NULL,                        // Use parent's environment block.
			lpDirectory,                 // starting directory.
			&si,                         // Pointer to STARTUPINFO structure.
			&pi))                        // Pointer to PROCESS_INFORMATION structure.
		{
			dwRes = 32; // success
		}

		// Close process and thread handles.
		CloseHandle(pi.hProcess);
		CloseHandle(pi.hThread);
	}
	return dwRes;
}
int main(int argc, char* argv[]) {
    int run_num = 0; 
    run_num = atoi(argv[1]); //read in the run number of this simulation

    int seed = 0;
    seed = atoi(argv[2]); //read in the seed for the random number generator of this simulation
	srand(seed);

    int arg = 0;

    int typeTest = 0;
    typeTest = atoi(argv[3]); //read the type of test this simulation is doing

    int tempTTTindex = 0;
    int temphysindex = 0;

    std::string folder = "";
    //case statement of the different simulation type with TTT and hys values
    //as well as the folder to output to
    switch(typeTest) {
        case 0:
            folder = "high";
            tempTTTindex = 15;
            temphysindex = 20;
            arg = 3;
            break;
        case 1:
            folder = "highhys";
            tempTTTindex = 3;
            temphysindex = 15;
            arg = 3;
            break;
        case 2:
            folder = "low";
            tempTTTindex = 0;
            temphysindex = 0;
            arg = 3;
            break;
        case 3:
            folder = "mid";
            tempTTTindex = 7;
            temphysindex = 10;
            arg = 3;
            break;
        case 4:
            folder = "opthigh";
            tempTTTindex = 15;
            temphysindex = 20;
            arg = 2;
            break;
        case 5:
            folder = "opthighhys";
            tempTTTindex = 3;
            temphysindex = 15;
            arg = 2;
            break;
        case 6:
            folder = "optlow";
            tempTTTindex = 0;
            temphysindex = 0;
            arg = 2;
            break;
        case 7:
            folder = "optmid";
            tempTTTindex = 7;
            temphysindex = 10;
            arg = 2;
            break;
        default:
            // program should not reach here
            break;
    }

	//set the TTTindex array to the correct values
    for(int j=0; j<NUM_BASESTATION; j++) {
        TTTindex[j] = tempTTTindex;
    }
    //set the hysindex array to the correct values
    for(int k=0; k<NUM_BASESTATION; k++) {
        hysindex[k] = temphysindex;
    }

	TTTmaxindex = 15;
	hysmaxindex = 20;

	TTTArray[0] = 0.0;
	TTTArray[1] = 0.04;
	TTTArray[2] = 0.064;
	TTTArray[3] = 0.08;
	TTTArray[4] = 0.1;
	TTTArray[5] = 0.128;
	TTTArray[6] = 0.16;
	TTTArray[7] = 0.256;
	TTTArray[8] = 0.32;
	TTTArray[9] = 0.48;
	TTTArray[10] = 0.512;
	TTTArray[11] = 0.64;
	TTTArray[12] = 1.024;
	TTTArray[13] = 1.280;
	TTTArray[14] = 2.56;
	TTTArray[15] = 5.12;

	hysArray[0] = 0.0;
	hysArray[1] = 0.5;
	hysArray[2] = 1.0;
	hysArray[3] = 1.5;
	hysArray[4] = 2.0;
	hysArray[5] = 2.5;
	hysArray[6] = 3.0;
	hysArray[7] = 3.5;
	hysArray[8] = 4.0;
	hysArray[9] = 4.5;
	hysArray[10] = 5.0;
	hysArray[11] = 5.5;
	hysArray[12] = 6.0;
	hysArray[13] = 6.5;
	hysArray[14] = 7.0;
	hysArray[15] = 7.5;
	hysArray[16] = 8.0;
	hysArray[17] = 8.5;
	hysArray[18] = 9.0;
	hysArray[19] = 9.5;
	hysArray[20] = 10.0;

	//set the TTT and hys arrays to the correct values
	for(int i=0; i<NUM_BASESTATION; i++) {
		TTT[i] = TTTArray[TTTindex[i]];
		hys[i] = hysArray[hysindex[i]];
	}

	// std::cout << "Enter what operation you would like to undertake.\n";
	// std::cout << "1 for generating / updating policy\n";
	// std::cout << "2 for using the policy\n";
	// std::cout << "3 for no learning\n";
	// std:: cout << "Please enter:\n";
    //
	// int arg;
	// std::cin >> arg;

	//this block set the function variable.
	//if all the code is commented in and the code above commented out then
	//the simulation can be run with user given parameters instead of parameters
	//given by the bash script.
	if(arg == 1) {
		// q-learning
		printf("Q-Learning started...\n");
		function = 1;
	} else if(arg == 2) {
		// use policy
		printf("Simulation started...\n");
        // printf("Enter index for TTT\n");
        // int tempTTTindex;
        // // std::cin >> tempTTTindex;
        // tempTTTindex = atoi(argv[4]);
        // for(int j=0; j<NUM_BASESTATION; j++) {
        //     TTT[j] = TTTArray[tempTTTindex];
        //     TTTindex[j] = tempTTTindex;
        // }
        // // printf("Enter index for hys\n");
        // int temphysindex;
        // // std::cin >> temphysindex;
        // temphysindex = atoi(argv[5]);
        // for(int k=0; k<NUM_BASESTATION; k++) {
        //     hys[k] = hysArray[temphysindex];
        //     hysindex[k] = temphysindex;
        // }
		function = 2;
	}  else if(arg == 3) {
		printf("No learning simulation...\n");
		// printf("Enter index for TTT\n");
		// int tempTTTindex;
		// // std::cin >> tempTTTindex;
        // tempTTTindex = atoi(argv[4]);
		// for(int j=0; j<NUM_BASESTATION; j++) {
		// 	TTT[j] = TTTArray[tempTTTindex];
		// 	TTTindex[j] = tempTTTindex;
		// }
		// // printf("Enter index for hys\n");
		// int temphysindex;
		// // std::cin >> temphysindex;
        // temphysindex = atoi(argv[5]);
		// for(int k=0; k<NUM_BASESTATION; k++) {
		// 	hys[k] = hysArray[temphysindex];
		// 	hysindex[k] = temphysindex;
		// }
		function = 4;
	}

	//instantiate the q-learning agents for the base stations
	q[0] = new q_learning(gs,0,TTTindex[0],hysindex[0]);
	q[1] = new q_learning(gs,1,TTTindex[1],hysindex[1]);
	q[2] = new q_learning(gs,2,TTTindex[2],hysindex[2]);
	q[3] = new q_learning(gs,3,TTTindex[3],hysindex[3]);
	q[4] = new q_learning(gs,4,TTTindex[4],hysindex[4]);
	q[5] = new q_learning(gs,5,TTTindex[5],hysindex[5]);
	q[6] = new q_learning(gs,6,TTTindex[6],hysindex[6]);
	q[7] = new q_learning(gs,7,TTTindex[7],hysindex[7]);
	q[8] = new q_learning(gs,8,TTTindex[8],hysindex[8]);

	gs->start(); //start the scheduler

	//this is where the simulation returns to when the schedulers is stopped by a mobile
	//print the results for the base stations on screen and save the q-vaules and policy
	//for the q-learning agents to external files
	for (int l=0; l<NUM_BASESTATION; l++)
	{
		bStations[l]->print();
		q[l]->saveQValues();
	}

	//This block of code writes the results out to text files in folders
	for(int m=0; m<NUM_BASESTATION; m++) {
		std::stringstream hString;
		hString << "results/longer/" << folder << run_num << "/basestation" << m << "/handover.txt";
		handoverString = hString.str();

		std::stringstream dString;
		dString<< "results/longer/" << folder << run_num << "/basestation" << m << "/drop.txt";
		dropString = dString.str();

		std::stringstream pString;
		pString << "results/longer/" << folder << run_num << "/basestation" << m << "/ping.txt";
		pingString = pString.str();

        std::stringstream fString;
        fString << "results/longer/" << folder << run_num << "/basestation" << m << "/failure.txt";
        failureString = fString.str();

		std::stringstream sString;
		sString << "results/longer/" << folder << run_num << "/basestation" << m << "/state.txt";
		stateString = sString.str();



		std::ofstream hFile (handoverString);
		if(hFile.is_open()) {
			for (std::vector<double>::iterator it=handover_total[m].begin() ; it!=handover_total[m].end(); it++) {
    		    hFile << *it << "\n";
    		}
    	}
    	hFile.close();

    	std::ofstream dFile (dropString);
		if(dFile.is_open()) {
			for (std::vector<double>::iterator it=drop_total[m].begin() ; it!=drop_total[m].end(); it++) {
    		    dFile << *it << "\n";
    		}
    	}
    	dFile.close();

    	std::ofstream pFile (pingString);
		if(pFile.is_open()) {
			for (std::vector<double>::iterator it=pingpong_total[m].begin() ; it!=pingpong_total[m].end(); it++) {
    		    pFile << *it << "\n";
    		}
    	}
    	pFile.close();

        std::ofstream fFile (failureString);
        if(fFile.is_open()) {
            for (std::vector<double>::iterator it=failure_total[m].begin() ; it!=failure_total[m].end(); it++) {
                fFile << *it << "\n";
            }
        }
        fFile.close();

    	std::ofstream sFile (stateString);
		if(sFile.is_open()) {
			for (std::vector<int>::iterator it=stateChanges[m].begin() ; it!=stateChanges[m].end(); it++) {
    		    sFile << *it << "\n";
    		}
    	}
    	sFile.close();
    }

	printf("end...\n");

	delete gs; //delete the scheduler to clean up

	return 0;
}
示例#11
0
void CModelConverter::SaveSIA(const tstring& sFilename)
{
	tstring sSIAFileName = tstring(GetDirectory(sFilename).c_str()) + _T("/") + GetFilename(sFilename).c_str() + _T(".sia");

	std::wofstream sFile(convertstring<tchar, char>(sSIAFileName).c_str());
	if (!sFile.is_open())
		return;

	sFile.precision(8);
	sFile.setf(std::ios::fixed, std::ios::floatfield);

	if (m_pWorkListener)
	{
		m_pWorkListener->BeginProgress();
		m_pWorkListener->SetAction(_T("Writing materials..."), 0);
	}

	sFile << _T("-Version 1.0") << std::endl;

	for (size_t i = 0; i < m_pScene->GetNumMaterials(); i++)
	{
		sFile << _T("-Mat") << std::endl;

		CConversionMaterial* pMaterial = m_pScene->GetMaterial(i);

		sFile << "-amb " << pMaterial->m_vecAmbient.x << _T(" ") << pMaterial->m_vecAmbient.y << _T(" ") << pMaterial->m_vecAmbient.z << _T(" 0") << std::endl;
		sFile << "-dif " << pMaterial->m_vecDiffuse.x << _T(" ") << pMaterial->m_vecDiffuse.y << _T(" ") << pMaterial->m_vecDiffuse.z << _T(" 0") << std::endl;
		sFile << "-spec " << pMaterial->m_vecSpecular.x << _T(" ") << pMaterial->m_vecSpecular.y << _T(" ") << pMaterial->m_vecSpecular.z << _T(" 0") << std::endl;
		sFile << "-emis " << pMaterial->m_vecEmissive.x << _T(" ") << pMaterial->m_vecEmissive.y << _T(" ") << pMaterial->m_vecEmissive.z << _T(" 0") << std::endl;
		sFile << "-shin " << pMaterial->m_flShininess << std::endl;
		sFile << "-name \"" << pMaterial->GetName().c_str() << _T("\"") << std::endl;
		if (pMaterial->GetDiffuseTexture().length() > 0)
			sFile << "-tex \"" << pMaterial->GetDiffuseTexture().c_str() << _T("\"") << std::endl;
		sFile << _T("-endMat") << std::endl;
	}

	for (size_t i = 0; i < m_pScene->GetNumMeshes(); i++)
	{
		CConversionMesh* pMesh = m_pScene->GetMesh(i);

		size_t iAddV = pMesh->GetNumVertices();
		size_t iAddE = pMesh->GetNumEdges();
		size_t iAddUV = pMesh->GetNumUVs();
		size_t iAddN = pMesh->GetNumNormals();

		// Find the default scene for this mesh.
		CConversionSceneNode* pScene = NULL;
		for (size_t j = 0; j < m_pScene->GetNumScenes(); j++)
		{
			if (m_pScene->GetScene(j)->GetName() == pMesh->GetName() + _T(".sia"))
			{
				pScene = m_pScene->GetScene(j);
				break;
			}
		}

		tstring sNodeName = pMesh->GetName();

		sFile << _T("-Shape") << std::endl;
		sFile << _T("-snam \"") << sNodeName.c_str() << _T("\"") << std::endl;
		sFile << _T("-shad 0") << std::endl;
		sFile << _T("-shadw 1") << std::endl;

		if (m_pWorkListener)
			m_pWorkListener->SetAction((tstring(_T("Writing ")) + sNodeName + _T(" vertices...")).c_str(), pMesh->GetNumVertices());

		for (size_t iVertices = 0; iVertices < pMesh->GetNumVertices(); iVertices++)
		{
			if (m_pWorkListener)
				m_pWorkListener->WorkProgress(iVertices);

			Vector vecVertex = pMesh->GetVertex(iVertices);
			sFile << _T("-vert ") << vecVertex.x << _T(" ") << vecVertex.y << _T(" ") << vecVertex.z << std::endl;
		}

		if (m_pWorkListener)
			m_pWorkListener->SetAction((tstring(_T("Writing ")) + sNodeName + _T(" edges...")).c_str(), pMesh->GetNumEdges());

		tstring sCreases;

		for (size_t iEdges = 0; iEdges < pMesh->GetNumEdges(); iEdges++)
		{
			if (m_pWorkListener)
				m_pWorkListener->WorkProgress(iEdges);

			CConversionEdge* pEdge = pMesh->GetEdge(iEdges);
			sFile << _T("-edge ") << pEdge->v1 << _T(" ") << pEdge->v2 << std::endl;

			if (pEdge->m_bCreased)
				sCreases += sprintf(tstring(" %d"), iEdges);
		}

		if (sCreases.length())
			sFile << _T("-creas") << sCreases.c_str() << std::endl;

		if (m_pWorkListener)
			m_pWorkListener->SetAction((tstring(_T("Writing ")) + sNodeName + _T(" faces...")).c_str(), pMesh->GetNumFaces());

		size_t iMaterial = 0;

		for (size_t iFaces = 0; iFaces < pMesh->GetNumFaces(); iFaces++)
		{
			if (m_pWorkListener)
				m_pWorkListener->WorkProgress(iFaces);

			CConversionFace* pFace = pMesh->GetFace(iFaces);

			if (iFaces == 0 || iMaterial != pFace->m)
			{
				iMaterial = pFace->m;

				if (iMaterial == ~0)
					sFile << _T("-setmat -1") << std::endl;
				else
				{
					CConversionSceneNode* pNode = m_pScene->GetDefaultSceneMeshInstance(pScene, pMesh, false);

					if (!pNode || pNode->GetNumMeshInstances() != 1)
						sFile << _T("-setmat -1") << std::endl;
					else
					{
						CConversionMaterialMap* pMap = pNode->GetMeshInstance(0)->GetMappedMaterial(iMaterial);
						if (pMap)
							sFile << _T("-setmat -1") << std::endl;
						else
							sFile << _T("-setmat ") << pMap->m_iMaterial << std::endl;
					}
				}
			}

			sFile << _T("-face ") << pFace->GetNumVertices();

			TAssert(pFace->GetNumEdges() == pFace->GetNumVertices());

			for (size_t iVertsInFace = 0; iVertsInFace < pFace->GetNumVertices(); iVertsInFace++)
			{
				CConversionVertex* pVertex = pFace->GetVertex(iVertsInFace);
				CConversionVertex* pNextVertex = pFace->GetVertex((iVertsInFace+1)%pFace->GetNumVertices());

				// Find the edge that heads in a counter-clockwise direction.
				size_t iEdge = ~0;
				for (size_t i = 0; i < pFace->GetNumEdges(); i++)
				{
					size_t iEdgeCandidate = pFace->GetEdge(i);
					CConversionEdge* pEdge = pMesh->GetEdge(iEdgeCandidate);
					if ((pEdge->v1 == pVertex->v && pEdge->v2 == pNextVertex->v) || (pEdge->v2 == pVertex->v && pEdge->v1 == pNextVertex->v))
					{
						iEdge = iEdgeCandidate;
						break;
					}
				}
				TAssert(iEdge != ~0);

				Vector vecUV = pMesh->GetUV(pVertex->vu);
				sFile << _T(" ") << pVertex->v << _T(" ") << iEdge << _T(" ") << vecUV.x << _T(" ") << vecUV.y;
			}

			sFile << std::endl;
		}

		sFile << _T("-axis 0 0.5 0 1 0 0 0 1 0 0 0 1") << std::endl;
		sFile << _T("-mirp 0 0 0 1 0 0") << std::endl;
		sFile << _T("-endShape") << std::endl;
	}

	if (m_pWorkListener)
		m_pWorkListener->EndProgress();
}
示例#12
0
void
#elif  __linux__
int 
#endif
main(int argc, char **argv)
{
   // Directory
   std::string sDir = argv[1];
#ifdef _WIN32
   HANDLE          hList;
   WIN32_FIND_DATA FileData;
   std::string sDirPattern;
#elif  __linux__
   // Directory pointer
   DIR *pDir;
   // pointer to the directory entry
   struct dirent *pEntry;
#endif

   // Language
   std::string sLanguage = argv[2];
   int iLanguage = initLanguage(sLanguage);

   // Verifying if the directory exist
   if (!isDir(sDir)) {
      exit(1);
   }

#ifdef __linux__
   // Open the directory
   if ((pDir = opendir(sDir.c_str())) == NULL) {
      std::cerr << __FILE__ << ":" << __LINE__ << " "
           << "Error in opendir() [" << sDir << "] " << std::endl
           << "errno (" << errno << ")" << std::endl;
      exit(1);
   }
#endif

#ifdef _WIN32
   sDirPattern = sDir;
   sDirPattern += "\\*";
   // Get the first file
   if ((hList = FindFirstFile(sDirPattern.c_str(), &FileData)) == INVALID_HANDLE_VALUE)
#elif  __linux__
   if ((pEntry = readdir(pDir)) == NULL)
#endif
   {
     std::cerr << __FILE__ << ":" << __LINE__ << " "
          << "No files found" << std::endl
          << "errno (" << errno << ")" << std::endl;
     exit(1);
   }
   // Directory: read entries
   do 
   {
#ifdef _WIN32
      char *pFileName = FileData.cFileName;
#elif  __linux__
      char *pFileName = pEntry->d_name;
#endif

      std::string sFileType;
      off_t st_size = 0;     // total size, in bytes
      // process the file entry
      if ((st_size = processEntryDirectoryName(sDir, pFileName, sFileType)) == -1) {
         continue;
      }

      // Obtaining the Long name of the book
      std::string sBook;
      getBookLongName(pFileName, sFileType.length(), sBook);
      std::cerr << "Book [" << sBook << "]" << std::endl;

      // create an instance of the book structure, and save it in the vector
      {
      stBooks b;
      std::string sFile(pFileName);
      b.sFile = sFile;
      b.sFileType = sFileType;
      b.sBook = sBook;
      b.st_size = st_size;

      vBooks.push_back(b);
      }
   }
#ifdef _WIN32
   while (FindNextFile(hList, &FileData));
#elif  __linux__
   while ((pEntry = readdir(pDir)) != NULL);
#endif

   if (vBooks.size()) {
      // Sort the vector
      std::stable_sort(vBooks.begin(), vBooks.end(), std::ptr_fun(byBook));
      // Print all the books
      printhtml(sDir, iLanguage);
   }
   exit(0);
}
示例#13
0
void
#elif  __linux__
int 
#endif
main(int argc, char **argv)
{
   // Directory
   std::string sDir = argv[1];
#ifdef _WIN32
   HANDLE          hList;
   WIN32_FIND_DATA FileData;
   std::string sDirPattern;
#elif  __linux__
   // Directory pointer
   DIR *pDir;
   // pointer to the directory entry
   struct dirent *pEntry;
#endif

   // Language
   std::string sLanguage = argv[2];
   int iLanguage = initLanguage(sLanguage);

   // Verifying if the directory exist
   if (!isDir(sDir)) {
      exit(1);
   }

#ifdef __linux__
   // Open the directory
   if ((pDir = opendir(sDir.c_str())) == NULL) {
      std::cerr << __FILE__ << ":" << __LINE__ << " "
           << "Error in opendir() [" << sDir << "] " << std::endl
           << "errno (" << errno << ")" << std::endl;
      exit(1);
   }
#endif

#ifdef _WIN32
   sDirPattern = sDir;
   sDirPattern += "\\*";
   // Get the first file
   if ((hList = FindFirstFile(sDirPattern.c_str(), &FileData)) == INVALID_HANDLE_VALUE)
#elif  __linux__
   if ((pEntry = readdir(pDir)) == NULL)
#endif
   {
     std::cerr << __FILE__ << ":" << __LINE__ << " "
          << "No files found" << std::endl
          << "errno (" << errno << ")" << std::endl;
     exit(1);
   }
   // Directory: read entries
   do 
   {
#ifdef _WIN32
      char *pFileName = FileData.cFileName;
#elif  __linux__
      char *pFileName = pEntry->d_name;
#endif

      std::string sFileType;
      off_t st_size = 0;     // total size, in bytes
      if ((st_size = processEntryDirectoryName(sDir, pFileName, sFileType)) == -1) {
         continue;
      }

      // Obtaining the short name of the book
      std::string sBook;
      getBookShortName(pFileName, sFileType.length(), sBook);
      std::cerr << "Book [" << sBook << "]" << std::endl;

      // Obtain the authors
      std::string sAuthors = "-";
      {
         const int N = strlen(pFileName);
         const int M = 1;
         char *token = "-";
         char *pszAuthors0= std::find_end(pFileName,
                                          pFileName + N,
                                          token, token + M);
         if (pszAuthors0 != (pFileName + N)) {
            while (*pszAuthors0== ' ' ||
                   *pszAuthors0== '-') {
               ++pszAuthors0;
            }
            const int L0 = strlen(pszAuthors0);
            const int L = L0 - sFileType.length() - 1;
            if (L > 3) {
               char *pszAuthors1 = new char[L0];
               memcpy(pszAuthors1, pszAuthors0, L);
               pszAuthors1[L] = 0;
               sAuthors = pszAuthors1;
            }
         }
      }
      std::cerr << "Authors [" << sAuthors << "]" << std::endl;

      // create an instance of the book structure, and save it in the vector
      {
      stBooks b;
      std::string sFile(pFileName);
      b.sFile = sFile;
      b.sFileType = sFileType;
      b.sBook = sBook;
      b.sAuthors = sAuthors;
      b.st_size = st_size;

      vBooks.push_back(b);
      }
   }
#ifdef _WIN32
   while (FindNextFile(hList, &FileData));
#elif  __linux__
   while ((pEntry = readdir(pDir)) != NULL);
#endif

   if (vBooks.size()) {
      // Sort the vector
      std::stable_sort(vBooks.begin(), vBooks.end(), std::ptr_fun(byBook));
      // Print all the books
      printhtml(sDir, iLanguage);
   }
   exit(0);
}
示例#14
0
/** Read the scaling information from a file (e.g. merlin_detector.sca) or from
 * the RAW file (.raw)
 *  @param scalingFile :: Name of scaling file .sca
 *  @param truepos :: V3D vector of actual positions as read from the file
 *  @return False if unable to open file, True otherwise
 */
bool SetScalingPSD::processScalingFile(const std::string &scalingFile,
                                       std::vector<Kernel::V3D> &truepos) {
  // Read the scaling information from a text file (.sca extension) or from a
  // raw file (.raw)
  // This is really corrected positions as (r,theta,phi) for each detector
  // Compare these with the instrument values to determine the change in
  // position and the scaling
  // which may be necessary for each pixel if in a tube.
  // movePos is used to updated positions
  std::map<int, Kernel::V3D> posMap;
  std::map<int, double> scaleMap;
  std::map<int, double>::iterator its;

  Instrument_const_sptr instrument = m_workspace->getInstrument();
  if (scalingFile.find(".sca") != std::string::npos ||
      scalingFile.find(".SCA") != std::string::npos) {
    // read a .sca text format file
    // format consists of a short header followed by one line per detector

    std::ifstream sFile(scalingFile.c_str());
    if (!sFile) {
      g_log.error() << "Unable to open scaling file " << scalingFile
                    << std::endl;
      return false;
    }
    std::string str;
    getline(sFile,
            str); // skip header line should be <filename> generated by <prog>
    int detectorCount;
    getline(sFile, str); // get detector count line
    std::istringstream istr(str);
    istr >> detectorCount;
    if (detectorCount < 1) {
      g_log.error("Bad detector count in scaling file");
      throw std::runtime_error("Bad detector count in scaling file");
    }
    truepos.reserve(detectorCount);
    getline(sFile, str); // skip title line
    int detIdLast = -10;
    Kernel::V3D truPosLast, detPosLast;

    Progress prog(this, 0.0, 0.5, detectorCount);
    // Now loop through lines, one for each detector/monitor. The latter are
    // ignored.

    while (getline(sFile, str)) {
      if (str.empty() || str[0] == '#')
        continue;
      std::istringstream istr(str);

      // read 6 values from the line to get the 3 (l2,theta,phi) of interest
      int detIndex, code;
      double l2, theta, phi, offset;
      istr >> detIndex >> offset >> l2 >> code >> theta >> phi;

      // sanity check on angles - l2 should be +ve but sample file has a few -ve
      // values
      // on monitors
      if (theta > 181.0 || theta < -1 || phi < -181 || phi > 181) {
        g_log.error("Position angle data out of range in .sca file");
        throw std::runtime_error(
            "Position angle data out of range in .sca file");
      }
      Kernel::V3D truPos;
      // use abs as correction file has -ve l2 for first few detectors
      truPos.spherical(fabs(l2), theta, phi);
      truepos.push_back(truPos);
      //
      Geometry::IDetector_const_sptr det;
      try {
        det = instrument->getDetector(detIndex);
      } catch (Kernel::Exception::NotFoundError &) {
        continue;
      }
      Kernel::V3D detPos = det->getPos();
      Kernel::V3D shift = truPos - detPos;

      // scaling applied to dets that are not monitors and have sequential IDs
      if (detIdLast == detIndex - 1 && !det->isMonitor()) {
        Kernel::V3D diffI = detPos - detPosLast;
        Kernel::V3D diffT = truPos - truPosLast;
        double scale = diffT.norm() / diffI.norm();
        Kernel::V3D scaleDir = diffT / diffT.norm();
        // Wish to store the scaling in a map, if we already have a scaling
        // for this detector (i.e. from the other side) we average the two
        // values. End of tube detectors only have one scaling estimate.
        scaleMap[detIndex] = scale;
        its = scaleMap.find(detIndex - 1);
        if (its == scaleMap.end())
          scaleMap[detIndex - 1] = scale;
        else
          its->second = 0.5 * (its->second + scale);
        // std::cout << detIndex << scale << scaleDir << std::endl;
      }
      detIdLast = detIndex;
      detPosLast = detPos;
      truPosLast = truPos;
      posMap[detIndex] = shift;
      //
      prog.report();
    }
  } else if (scalingFile.find(".raw") != std::string::npos ||
示例#15
0
BOOL COSMCtrlMapOperationsDlg::DownloadTiles(BOOL bSkipIfTileAlreadyExists)
{
  //Validate our parameters
  AFXASSUME(m_pOSMCtrl);

  //What will be the return value from this function (assume the best)
  BOOL bSuccess = TRUE;

  CSingleLock sl(&m_pOSMCtrl->m_csData, TRUE);
  IOSMCtrlTileProvider* pTileProvider = m_pOSMCtrl->GetTileProvider();
  CString sCacheDirectory(m_pOSMCtrl->m_sCacheDirectory);
  ASSERT(sCacheDirectory.GetLength());
  BOOL bUseIfModifiedSinceHeader(m_pOSMCtrl->m_bUseIfModifiedSinceHeader);
  sl.Unlock();

  //Next get the server to connect to
  CString sServer(pTileProvider->GetDownloadServer());

  //Accumulate how many tiles we have deleted and not deleted
  int nTilesDownloaded = 0;
  int nTilesNotDownloaded = 0;

  //Next create the Wininet session object
  ASSERT(m_hSession == NULL);
  HRESULT hr = m_pOSMCtrl->CreateSession(m_hSession);
  if (SUCCEEDED(hr))
  {
    //Now create the connection object from the session object
    HINTERNET hConnection = NULL;
    hr = m_pOSMCtrl->CreateConnection(m_hSession, sServer, 80, hConnection);
    if (SUCCEEDED(hr))
    {
      //Iterate across the array of tiles to download
      for (INT_PTR i=0; i<m_Tiles.GetSize() && bSuccess; i++)
      {
        //Pull out the next tile to download
        const COSMCtrlMapOperationsDlgTile& tile = m_Tiles.ElementAt(i);

        //Create the sub directories if we can
        CString sSubDirectory;
        sSubDirectory.Format(_T("%s\\%d"), sCacheDirectory.operator LPCTSTR(), tile.m_nZoom);
        CreateDirectory(sSubDirectory, NULL);
        sSubDirectory.Format(_T("%s\\%d\\%d"), sCacheDirectory.operator LPCTSTR(), tile.m_nZoom, tile.m_nTileX);
        CreateDirectory(sSubDirectory, NULL);

        //Form the name of the tile we will be downloading
        CString sObject(pTileProvider->GetDownloadObject(tile.m_nZoom, tile.m_nTileX, tile.m_nTileY));

        //Form the path to the tile we will be downloading to  and determine if we should do the download
        CString sFile(COSMCtrl::GetTileCachePath(sCacheDirectory, tile.m_nZoom, tile.m_nTileX, tile.m_nTileY, FALSE));
        BOOL bDownload = TRUE;
        if (bSkipIfTileAlreadyExists)
          bDownload = (GetFileAttributes(sFile) == INVALID_FILE_ATTRIBUTES);

        //Now download the specific tile to the cache if required
        COSMCtrlMapOperationsDlgEvent dlgEvent;
        dlgEvent.m_bSuccess = false;
        if (bDownload)
        {
          hr = m_pOSMCtrl->DownloadTile(hConnection, sObject, bUseIfModifiedSinceHeader, !bSkipIfTileAlreadyExists, tile.m_nZoom, tile.m_nTileX, tile.m_nTileY, sFile);
          if (FAILED(hr))
          {
            //report the error
            TRACE(_T("COSMCtrlMapOperationsDlg::DownloadTiles, Failed to download tile \"%s\", Error:%08X\n"), sFile.operator LPCTSTR(), hr);
            
            //Ensure any remants of a bad download file are nuked
            DeleteFile(sFile);
            
            //Update the stats
            ++nTilesNotDownloaded;
          }
          else
          {
            //Update the stats
            ++nTilesDownloaded;
            dlgEvent.m_bSuccess = true;
          }
        }
        else
        {
          //Update the stats
          ++nTilesNotDownloaded;
        }

        //Update the UI          
        dlgEvent.m_Event = COSMCtrlMapOperationsDlgEvent::SimpleStringStatus;
        dlgEvent.m_sString = sFile;
        dlgEvent.m_nItemData = i + 1;
        AddEvent(dlgEvent);

        //Check if we have been cancelled before we loop around
        bSuccess = (WaitForSingleObject(m_WorkerTerminateEvent, 0) == WAIT_TIMEOUT);
      }
      
      //Close the wininet connection
    #ifdef COSMCTRL_NOWINHTTP
      InternetCloseHandle(hConnection);
    #else
      WinHttpCloseHandle(hConnection);
    #endif
    }

    //Clean up the wininet session before we exit
  #ifdef COSMCTRL_NOWINHTTP
    InternetCloseHandle(m_hSession);
  #else
    WinHttpCloseHandle(m_hSession);
  #endif
    m_hSession = NULL;
  }

  //Finally add a event about how many items have been downloaded
  COSMCtrlMapOperationsDlgEvent dlgEvent;
  dlgEvent.m_Event = COSMCtrlMapOperationsDlgEvent::SimpleStringStatus;
  CString sTilesDownloaded;
  sTilesDownloaded.Format(_T("%d"), nTilesDownloaded);
  CString sTilesNotDownloaded;
  sTilesNotDownloaded.Format(_T("%d"), nTilesNotDownloaded);
  AfxFormatString2(dlgEvent.m_sString, IDS_OSMCTRL_DOWNLOAD_TILES_STATS, sTilesDownloaded, sTilesNotDownloaded);
  AddEvent(dlgEvent);

  return TRUE;
}
示例#16
0
BOOL COSMCtrlMapOperationsDlg::DownloadTiles(BOOL bSkipIfTileAlreadyExists)
{
  //Validate our parameters
  AFXASSUME(m_pOSMCtrl != NULL);

  //Pull out the tile provider we will be using
  IOSMCtrlTileProvider* pTileProvider = m_pOSMCtrl->GetTileProvider();
  AFXASSUME(pTileProvider != NULL);

  //Next get the server to connect to
  CStringW sServer(pTileProvider->GetDownloadServer());

  //Accumulate how many tiles we have deleted and not deleted
  int nTilesDownloaded = 0;
  int nTilesNotDownloaded = 0;

  //Next create the WinHTTP session object
  CWinHTTPSession session;
  HRESULT hr = m_pOSMCtrl->CreateSession(session, 0);
  if (SUCCEEDED(hr))
  {
    //Now create the connection object from the session object
    CWinHTTPConnection connection;
    hr = connection.Initialize(session, sServer, pTileProvider->GetDownloadPort());
    if (SUCCEEDED(hr))
    {
      //Iterate across the array of tiles to download
      BOOL bSuccess = TRUE;
      for (std::vector<COSMCtrlMapOperationsDlgTile>::size_type i=0; i<m_Tiles.size() && bSuccess; i++)
      {
        //Pull out the next tile to download
        const COSMCtrlMapOperationsDlgTile& tile = m_Tiles[i];

        //Create the sub directories if we can
        CString sCacheDirectory(m_pOSMCtrl->GetCacheDirectory());
        CString sSubDirectory;
        sSubDirectory.Format(_T("%s\\%d"), sCacheDirectory.operator LPCTSTR(), tile.m_nZoom);
        CreateDirectory(sSubDirectory, NULL);
        sSubDirectory.Format(_T("%s\\%d\\%d"), sCacheDirectory.operator LPCTSTR(), tile.m_nZoom, tile.m_nTileX);
        CreateDirectory(sSubDirectory, NULL);

        //Form the path to the tile we will be downloading to and determine if we should do the download
        CString sFile(COSMCtrl::GetTileCachePath(sCacheDirectory, tile.m_nZoom, tile.m_nTileX, tile.m_nTileY, FALSE));
        BOOL bDownload = TRUE;
        if (bSkipIfTileAlreadyExists)
          bDownload = (GetFileAttributes(sFile) == INVALID_FILE_ATTRIBUTES);

        //Now download the specific tile to the cache if required
        COSMCtrlMapOperationsDlgEvent dlgEvent;
        dlgEvent.m_bSuccess = false;
        if (bDownload)
        {
          //We will accept any mime type
          LPCWSTR pwszAcceptTypes[2];
          pwszAcceptTypes[0] = L"*/*";
          pwszAcceptTypes[1] = NULL;
          CSyncWinHTTPDownloader winHttpRequest;
          winHttpRequest.m_sFileToDownloadInto = sFile;
          CString sObject(pTileProvider->GetDownloadObject(tile.m_nZoom, tile.m_nTileX, tile.m_nTileY));
          hr = winHttpRequest.Initialize(connection, CStringW(sObject), NULL, NULL, NULL, pwszAcceptTypes, WINHTTP_FLAG_REFRESH);
          if (FAILED(hr))
          {
            //report the error
            TRACE(_T("COSMCtrlMapOperationsDlg::DownloadTiles, Failed to create request for tile \"%s\", Error:%08X\n"), sFile.operator LPCTSTR(), hr);
            
            //Ensure any remants of a bad download file are nuked
            DeleteFile(sFile);
            
            //Update the stats
            ++nTilesNotDownloaded;
          }
          else
          {
            hr = winHttpRequest.SendRequestSync();
            if (FAILED(hr))
            {
              //report the error
              TRACE(_T("COSMCtrlMapOperationsDlg::DownloadTiles, Failed to send request for tile \"%s\", Error:%08X\n"), sFile.operator LPCTSTR(), hr);
            
              //Ensure any remants of a bad download file are nuked
              DeleteFile(sFile);
            
              //Update the stats
              ++nTilesNotDownloaded;
            }
            else
            {
              //Update the stats
              ++nTilesDownloaded;
              dlgEvent.m_bSuccess = true;
            }
          }
        }
        else
        {
          //Update the stats
          ++nTilesNotDownloaded;
        }

        //Update the UI          
        dlgEvent.m_Event = COSMCtrlMapOperationsDlgEvent::SimpleStringStatus;
        dlgEvent.m_sString = sFile;
        dlgEvent.m_nItemData = i + 1;
        AddEvent(dlgEvent);

        //Check if we have been cancelled before we loop around
        bSuccess = (WaitForSingleObject(m_WorkerTerminateEvent, 0) == WAIT_TIMEOUT);
      }
    }
  }

  //Finally add a event about how many items have been downloaded
  COSMCtrlMapOperationsDlgEvent dlgEvent;
  dlgEvent.m_Event = COSMCtrlMapOperationsDlgEvent::SimpleStringStatus;
  CString sTilesDownloaded;
  sTilesDownloaded.Format(_T("%d"), nTilesDownloaded);
  CString sTilesNotDownloaded;
  sTilesNotDownloaded.Format(_T("%d"), nTilesNotDownloaded);
  AfxFormatString2(dlgEvent.m_sString, IDS_OSMCTRL_DOWNLOAD_TILES_STATS, sTilesDownloaded, sTilesNotDownloaded);
  AddEvent(dlgEvent);

  return TRUE;
}
示例#17
0
void ParticleEditor::OpenConfigFile(QString filename)
{
	QFile sFile(fileName);
	if (sFile.open(QIODevice::ReadOnly | QIODevice::Text)){
		QTextStream in(&sFile);
		QString content = in.readAll();
		QJsonParseError jsonError;
		QJsonDocument document = QJsonDocument::fromJson(content.toLatin1(), &jsonError);
		if (jsonError.error == QJsonParseError::NoError && document.isObject()){
			QJsonObject obj = document.object();
			QJsonArray resList = obj["resList"].toArray();
			QJsonObject particleData = obj["particleData"].toObject();

			resourceView->clearResourceList();
			for (int i = 0; i < resList.size(); i++){
				resourceView->addRes(resList.at(i).toString());
			}

			auto layer = dynamic_cast<C3DLayer*>(g_Layer);
			auto particleSystem = layer->getParticleSystem();
			auto acclerationMin = Vec3(particleData["accleration_min_x"].toDouble(), particleData["accleration_min_y"].toDouble(), particleData["accleration_min_z"].toDouble());
			auto acclerationMax = Vec3(particleData["accleration_max_x"].toDouble(), particleData["accleration_max_y"].toDouble(), particleData["accleration_max_z"].toDouble());
			auto sizeMin = Vec3(particleData["size_min_x"].toDouble(), particleData["size_min_y"].toDouble(), particleData["size_min_z"].toDouble());
			auto sizeMax = Vec3(particleData["size_max_x"].toDouble(), particleData["size_max_y"].toDouble(), particleData["size_max_z"].toDouble());
			auto sizeVelocity = Vec3(particleData["size_velocity_x"].toDouble(), particleData["size_velocity_z"].toDouble(), particleData["size_velocity_z"].toDouble());
			auto velocityMin = Vec3(particleData["velocity_min_x"].toDouble(), particleData["velocity_min_y"].toDouble(), particleData["velocity_min_z"].toDouble());
			auto velocityMax = Vec3(particleData["velocity_max_x"].toDouble(), particleData["velocity_max_y"].toDouble(), particleData["velocity_max_z"].toDouble());
			auto colorMin = Vec3(particleData["color_min_x"].toDouble(), particleData["color_min_y"].toDouble(), particleData["color_min_z"].toDouble());
			auto colorMax = Vec3(particleData["color_max_x"].toDouble(), particleData["color_max_y"].toDouble(), particleData["color_max_z"].toDouble());
			auto colorVelocity = Vec3(particleData["color_velocity_x"].toDouble(), particleData["color_velocity_y"].toDouble(), particleData["color_velocity_z"].toDouble());
			auto life = Vec3(particleData["life_min"].toDouble(), particleData["life_max"].toDouble(), particleData["life_velocity"].toDouble());
			particleSystem->resetParticleAccelerationMin(acclerationMin);
			particleSystem->resetParticleAccelerationMax(acclerationMax);
			particleSystem->resetParticleSizeMin(sizeMin);
			particleSystem->resetParticleSizeMax(sizeMax);
			particleSystem->resetParticleSizeVelocity(sizeVelocity);
			particleSystem->resetParticleVelocityMin(velocityMin); 
			particleSystem->resetParticleVelocityMax(velocityMax);
			particleSystem->resetParticleColorMin(colorMin);
			particleSystem->resetParticleColorMax(colorMax);
			particleSystem->resetParticleColorVelocity(colorVelocity);
			particleSystem->resetParticleLifeMin(life.x);
			particleSystem->resetParticleLifeMax(life.y); 
			particleSystem->resetParticleLife_Velocity(life.z);
			particleSystem->SetTexture(particleData["texture"].toString().toLocal8Bit().data());
			particleSystem->setColor(particleData["m_color_r"].toDouble(), particleData["m_color_g"].toDouble(), particleData["m_color_b"].toDouble(), particleData["m_color_a"].toDouble());
			eParticleType _type;
			switch (particleData["particle_type"].toInt()){
			case 0:
				_type = eParticleType::PT_FIRE;
				break;
			case 1:
				_type = eParticleType::PT_FIREWORK;
				break;
			case 2:
				_type = eParticleType::PT_FOUNTAIN;
				break;
			case 3:
				_type = eParticleType::PT_MAX;
				break;
			}
			layer->resetParticle(particleData["count"].toInt(), _type, { particleData["blendfunc_src"].toInt(), particleData["blendfunc_dst"].toInt() });
			controlView->setTarget(particleSystem);
			controlView->setParticleType(_type);
		}
		else{
			addConsoleInfo("文件错误");
		}
	}
	else{
		addConsoleInfo("读取文件错误");
	}
}
示例#18
0
bool Jpg2Bmp(BYTE* lpJpgBuf, DWORD nBufSize, LPBITMAPINFOHEADER &head, LPBYTE &data)
{
	try{
		//取得运行程序的绝对路径 
		CString  strPath(__argv[0]);
		strPath  =  strPath.Left(strPath.ReverseFind('\\')); 
		CString sFile(strPath+"\\TempJpgFile.jpg");

		try{	
			CFile  jpgFile(sFile, CFile::modeWrite|CFile::modeCreate);	
			jpgFile.Write(lpJpgBuf, nBufSize);
			jpgFile.Flush();
			jpgFile.Close();
			IplImage *Img = NULL;
			Img = cvLoadImage(sFile, CV_LOAD_IMAGE_ANYCOLOR);
			
			int width    = Img->width;
			int height   = Img->height;
			int nchannels= Img->nChannels;

			head = new BITMAPINFOHEADER;
			head->biBitCount = nchannels * 8;
			head->biHeight   = height;
			head->biWidth    = width;
			head->biSizeImage= WIDTHBYTES(head->biBitCount*width)*height;
			head->biPlanes = 1;
			head->biXPelsPerMeter = 0; //GetDeviceCaps(GetDC(GetDesktopWindow()),LOGPIXELSX);
			head->biYPelsPerMeter = 0; //GetDeviceCaps(GetDC(GetDesktopWindow()),LOGPIXELSY);
			head->biCompression=0;
			head->biClrUsed=0;
			head->biClrImportant=0;
			head->biSize  = sizeof(BITMAPINFOHEADER);
			
			data = new BYTE[head->biSizeImage];
			
			int i,j;
			int lw = WIDTHBYTES(head->biBitCount*head->biWidth);
			for(i=0;i<Img->height;++i)
				for(j=0;j<Img->width;++j)
				{
					data[(Img->height-1-i)*lw+nchannels*j+0] = Img->imageData[i*Img->widthStep+nchannels*j+0];
					data[(Img->height-1-i)*lw+nchannels*j+1] = Img->imageData[i*Img->widthStep+nchannels*j+1];
					data[(Img->height-1-i)*lw+nchannels*j+2] = Img->imageData[i*Img->widthStep+nchannels*j+2];
				}
				
				
				CFile::Remove(sFile);
				return true;
			}
			catch(CFileException e)
			{
				CString ErrorInfoStr;
				ErrorInfoStr.Format("文件"+e.m_strFileName+"写入失败!");
				AfxMessageBox(ErrorInfoStr);
				return false;
			}


	}
	catch(...) 
	{
		ASSERT(NULL);
		return false;
	}
}
示例#19
0
/** Reads detector information from a .dat file, the file contains one line per detector
*  and its format is documented in "DETECTOR.DAT format" (more details in LoadDetectorInfo.h)
*  @param fName :: name and path of the data file to read
*  @throw invalid_argument if the detection delay time is different for different monitors
*  @throw FileError if there was a problem opening the file or its format
*  @throw MisMatch<int> if not very spectra is associated with exaltly one detector
*  @throw IndexError if there is a problem converting spectra indexes to spectra numbers, which would imply there is a problem with the workspace
*  @throw runtime_error if the SpectraDetectorMap had not been filled
*/
void LoadDetectorInfo::readDAT(const std::string& fName)
{
  g_log.information() << "Opening DAT file " << fName << std::endl;
  std::ifstream sFile(fName.c_str());
  if (!sFile)
  {
    throw Exception::FileError("Can't open file", fName);
  }
  // update the progress monitor and allow for user cancel
  progress(0.05);
  interruption_point();
 
  std::string str;
  // skip header line which contains something like <filename> generated by <prog>
  getline(sFile,str);
  g_log.debug() << "Reading " << fName << std::endl;
  g_log.information() << "Writing to the detector parameter map, only the first and last entries will be logged here\n";

  int detectorCount, numColumns;
  getline(sFile,str);
  std::istringstream header2(str);
  // header information is two numbers, the number of detectors, which we use but don't rely on, and the number of columns which we trust
  header2 >> detectorCount >> numColumns;
  if( detectorCount < 1 || numColumns != 14)
  {
    g_log.debug() << "Problem with the header information on the second line of the file, found: " << str << std::endl; 
    g_log.error() << name() << " requires that the input file has 14 columns and the number of detectors is positve\n";
    throw Exception::FileError("Incompatible file format found when reading line 2 in the input file", fName);
  }
 
  // skip title line
  getline(sFile,str);

  // will store all hte detector IDs that we get data for
  std::vector<detid_t> detectorList;
  detectorList.reserve(detectorCount);
  // stores the time offsets that the TOF X-values will be adjusted by at the end
  std::vector<float> offsets;
  offsets.reserve(detectorCount);
  float detectorOffset = UNSETOFFSET;
  bool differentOffsets = false;
  // used only for progress and logging
  std::vector<detid_t> missingDetectors;
  int count = 0, detectorProblemCount = 0;
  detectorInfo log;
  bool noneSet = true;
  // Now loop through lines, one for each detector or monitor. The latter are ignored.
  while( getline(sFile, str) )
  {
    if (str.empty() || str[0] == '#')
    {// comments and empty lines are allowed and ignored
      continue;
    }
    std::istringstream istr(str);
    
    detectorInfo readin;
    int code;
    float delta;
    // data for each detector in the file that we don't need
    float dump;

    // columns in the file, the detector ID and a code for the type of detector CODE = 3 (psd gas tube)
    istr >> readin.detID >> delta >> readin.l2 >> code >> readin.theta >> readin.phi;
    detectorList.push_back(readin.detID);
    offsets.push_back(delta);
    
    // check we have a supported code
    switch (code)
    {
      // these first two codes are detectors that we'll process, the code for this is below
      case PSD_GAS_TUBE : break;
      case NON_PSD_GAS_TUBE : break;

      // the following detectors codes specify little or no analysis
      case MONITOR_DEVICE :
        // throws invalid_argument if the detection delay time is different for different monitors
        noteMonitorOffset( delta, readin.detID);
        // skip the rest of this loop and move on to the next detector
        continue;

      // the detector is set to dummy, we won't report any error for this we'll just do nothing
      case DUMMY_DECT : continue;
      
      //we can't use data for detectors with other codes because we don't know the format, ignore the data and write to g_log.warning() once at the end
      default :
        detectorProblemCount ++;
        g_log.debug() << "Ignoring data for a detector with code " << code << std::endl;
        continue;
    }

    // gas filled detector specific code now until the end of this method
    
    // normally all the offsets are the same and things work faster, check for this
    if ( delta != detectorOffset )
    {// could mean different detectors have different offsets and we need to do things thoroughly
      if ( detectorOffset !=  UNSETOFFSET )
      {
        differentOffsets = true;
      }
      detectorOffset = delta;
    }

    //there are 10 uninteresting columns
    istr >> dump >> dump >> dump >> dump >> dump >> dump >> dump >> dump >> dump >> dump;
    // column names det_2   ,   det_3  , (assumes that code=3), the last column is not read
    istr >> readin.pressure >> readin.wallThick;
    try
    {
      setDetectorParams(readin, log);
      sometimesLogSuccess(log, noneSet);
    }
    catch (Exception::NotFoundError &)
    {// there are likely to be some detectors that we can't find in the instrument definition and we can't save parameters for these. We can't do anything about this just report the problem at the end
      missingDetectors.push_back(readin.detID);
      continue;
    }

    // report progress and check for a user cancel message at regualar intervals
    count ++;
    if ( count % INTERVAL == INTERVAL/2 )
    {
      progress(static_cast<double>(count)/(3*detectorCount));
      interruption_point();
    }
  }

  sometimesLogSuccess(log, noneSet = true);
  g_log.debug() << "Adjusting time of flight X-values by detector delay times" << std::endl;
  adjDelayTOFs(detectorOffset, differentOffsets, detectorList, offsets);
  
  if ( detectorProblemCount > 0 )
  {
    g_log.warning() << "Data for " << detectorProblemCount << " detectors that are neither monitors or psd gas tubes, the data have been ignored" << std::endl;
  }
  logErrorsFromRead(missingDetectors);
  g_log.debug() << "Successfully read DAT file " << fName << std::endl;
}