Beispiel #1
0
wxString ClangPlugin::GetSourceOf(cbEditor* ed)
{
    cbProject* project = nullptr;
    ProjectFile* opf = ed->GetProjectFile();
    if (opf)
        project = opf->GetParentProject();
    if (!project)
        project = Manager::Get()->GetProjectManager()->GetActiveProject();

    wxFileName theFile(ed->GetFilename());
    wxFileName candidateFile;
    bool isCandidate;
    wxArrayString fileArray;
    wxDir::GetAllFiles(theFile.GetPath(wxPATH_GET_VOLUME), &fileArray,
            theFile.GetName() + wxT(".*"), wxDIR_FILES | wxDIR_HIDDEN);
    wxFileName currentCandidateFile = FindSourceIn(fileArray, theFile, isCandidate);
    if (isCandidate)
        candidateFile = currentCandidateFile;
    else if (currentCandidateFile.IsOk())
        return currentCandidateFile.GetFullPath();

    fileArray.Clear();
    EditorManager* edMgr = Manager::Get()->GetEditorManager();
    for (int i = 0; i < edMgr->GetEditorsCount(); ++i)
    {
        cbEditor* edit = edMgr->GetBuiltinEditor(i);
        if (!edit)
            continue;

        ProjectFile* pf = edit->GetProjectFile();
        if (!pf)
            continue;

        fileArray.Add(pf->file.GetFullPath());
    }
    currentCandidateFile = FindSourceIn(fileArray, theFile, isCandidate);
    if (!isCandidate && currentCandidateFile.IsOk())
        return currentCandidateFile.GetFullPath();

    if (project)
    {
        fileArray.Clear();
        for (FilesList::const_iterator it = project->GetFilesList().begin();
                it != project->GetFilesList().end(); ++it)
        {
            ProjectFile* pf = *it;
            if (!pf)
                continue;

            fileArray.Add(pf->file.GetFullPath());
        }
        currentCandidateFile = FindSourceIn(fileArray, theFile, isCandidate);
        if (isCandidate && !candidateFile.IsOk())
            candidateFile = currentCandidateFile;
        else if (currentCandidateFile.IsOk())
            return currentCandidateFile.GetFullPath();

        wxArrayString dirs = project->GetIncludeDirs();
        for (int i = 0; i < project->GetBuildTargetsCount(); ++i)
        {
            ProjectBuildTarget* target = project->GetBuildTarget(i);
            if (target)
            {
                for (size_t ti = 0; ti < target->GetIncludeDirs().GetCount(); ++ti)
                {
                    wxString dir = target->GetIncludeDirs()[ti];
                    if (dirs.Index(dir) == wxNOT_FOUND)
                        dirs.Add(dir);
                }
            }
        }
        for (size_t i = 0; i < dirs.GetCount(); ++i)
        {
            wxString dir = dirs[i];
            Manager::Get()->GetMacrosManager()->ReplaceMacros(dir);
            wxFileName dname(dir);
            if (!dname.IsAbsolute())
                dname.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE, project->GetBasePath());
            fileArray.Clear();
            wxDir::GetAllFiles(dname.GetPath(), &fileArray, theFile.GetName() + wxT(".*"), wxDIR_FILES | wxDIR_HIDDEN);
            currentCandidateFile = FindSourceIn(fileArray, theFile, isCandidate);
            if (isCandidate)
                candidateFile = currentCandidateFile;
            else if (currentCandidateFile.IsOk())
                return currentCandidateFile.GetFullPath();
        }
    }
    if (candidateFile.IsOk())
        return candidateFile.GetFullPath();
    return wxEmptyString;
}
Beispiel #2
0
/*
Reads a file called fileName into an IndexInterface using rapidxml
@param fileName - the name of the file to index
@param index - the index to populate with information from the file
*/
bool XMLParser::readFileToIndex(string fileName, IndexInterface* index){

   /*
   This is a block of setup code for rapidxml so that I can parse through the xml file efficiently
   */

 	rapidxml::xml_document<> doc;
   rapidxml::xml_node<> * root_node;
   ifstream theFile (fileName);

   vector<char> buffer((istreambuf_iterator<char>(theFile)), istreambuf_iterator<char>());
   buffer.push_back('\0');
   // Parse the buffer using the xml file parsing library into doc 
   doc.parse<0>(&buffer[0]);
   // Find our root node
   root_node = doc.first_node("mediawiki");

   //Save the number of documents that have been indexed
   int num = 0;
   for (rapidxml::xml_node<> * document_node = root_node->first_node("page"); document_node; document_node = document_node->next_sibling()){

      //The text element of the current document node
      rapidxml::xml_node<> * text;

      //Grab the text and document name of the current document
      text = document_node->first_node("revision")->first_node("text");
      string docName = document_node->first_node("title")->value();

      //Ignore documents called user or file. They're garbage
      if(docName.substr(0, 4) == "User" || docName.substr(0,4) == "File") continue;

      //Find and save the author of the last revision
      string docAuthor;
      if(document_node->first_node("revision")->first_node("contributor") != nullptr
      	&& document_node->first_node("revision")->first_node("contributor")->first_node("username") != nullptr)
     	 docAuthor = document_node->first_node("revision")->first_node("contributor")->first_node("username")->value();
      else
      	docAuthor = "No author information given";

      //Find and save the timestamp for the last revision
      string timestamp;
      if(document_node->first_node("revision")->first_node("timestamp") != nullptr)
      	timestamp = document_node->first_node("revision")->first_node("timestamp")->value();
      else
      	timestamp = "No timestamp given";

      string fileName = "SearchDocs/";
      string docNameCopy = docName;
      replace(docNameCopy.begin(), docNameCopy.end(), '/', '.');
      replace(docNameCopy.begin(), docNameCopy.end(), ' ', '_');
      fileName = fileName + docNameCopy;
      ofstream writeDocFile(fileName);


      //Add this document to the index and save it's index in the index number-name registry
      int indexOfDoc = index->addDocument(docName, docAuthor, timestamp);

      //If we've successfully found a text node for this document
      if(text){


      	//Calculate file name for document file
      	 docNameCopy = docName;
      	 replace(docNameCopy.begin(), docNameCopy.end(), '/', ' ');
      	 replace(docNameCopy.begin(), docNameCopy.end(), ':', '.');
      	 stringstream titleStream(docNameCopy);


      	 while(!titleStream.eof()){


            //save the current word and add it to the index for the current document number
         	string word;
         	titleStream >> word;
         	writeDocFile << word << " ";

         	//Check if the word is a stop word or xml garbage
            if(!isStopWord(word) && !isXMLTag(word)){
				
				//If not, remove capitalization, stem it, and index it
				word[0] = tolower(word[0]);
            	Porter2Stemmer::stem(word);
            	index->addWordForDocument(indexOfDoc, word);
            }
          }

         //Make a stringstream of the text element of the document node
         stringstream ss(text->value());
         
         //Parse through the whole stringstream
         while(!ss.eof()){

            //save the current word and add it to the index for the current document number
         	string word;
         	ss >> word;
         	writeDocFile << word << " ";

         	//Check if the word is a stop word or xml garbage
            if(!isStopWord(word) && !isXMLTag(word)){

            	//If not, remove capitalization, stem it, and index it
				word[0] = tolower(word[0]);
            	Porter2Stemmer::stem(word);
            	index->addWordForDocument(indexOfDoc, word);           	
           	}
         }


       }

       //close ofstream for this doc
       writeDocFile.close();
       cout << num++ << docName << endl;
	}

   return true;
}
Beispiel #3
0
void drawHFPosition(char file[100]="hf.out", int save=0) {

  setTDRStyle();
  std::ifstream theFile(file);
  static const int NPMAX=20000;
  int    etaIndex[NPMAX], phiIndex[NPMAX], depths[NPMAX], np=0;
  float  radiusT[NPMAX], radiusH[NPMAX], phiH[NPMAX];
  double deg=3.1415926/180.;
  while (theFile) {
    int   ieta, iphi, idep;
    float etaR, rr, phideg;
    theFile >> ieta >> iphi >> idep >> etaR >> rr >> phideg;
    if (np < NPMAX) {
      etaIndex[np] = ieta;
      phiIndex[np] = iphi;
      depths[np]   = idep;
      radiusT[np]  = etaR;
      radiusH[np]  = rr;
      if (phideg < 0) phideg += 360;
      int iphi = (int)(phideg/20);
      float phi = (phideg - iphi*20.0);
      if (phi > 10) phi -= 20;
      phiH[np] = phi*deg;
      np++;
    }
  }
  std::cout << np << " points found\n";
  //  for (int i=0; i<np; i++) std::cout << std::setw(4) << i << " " << std::setw(3) << etaIndex[i] << " " << std::setw(3) << phiIndex[i] << " " << depths[i] << " " << std::setw(6) << radiusT[i] << " " << std::setw(6) << radiusH[i] << " " << std::setw(6) << phiH[i] << "\n";

  int symbol[14] = {20,21,22,23,24,25,26,27,28,29,30,3,5,2};
  int colr[3]    = {2,4,1};
  TGraph *gr[3][14];
  float x1[NPMAX], y1[NPMAX], x2[NPMAX], y2[NPMAX], x3[NPMAX], y3[NPMAX];
  int np1, np2, np3;
  for (int i=0; i<13; i++) {
    np1 = np2 = np3 = 0;
    for (int j=0; j<np; j++) {
      if (etaIndex[j] == (i+29)) {
	int k = 2;
	if (depths[j] == 3) k = 0;
	else if (depths[j] == 4) k = 1;
	if (k == 0) {
	  x1[np1] = radiusH[j]*cos(phiH[j]);
	  y1[np1] = radiusH[j]*sin(phiH[j]);
	  np1++;
	  //	  if (np1 == 1) std::cout << i << " 0 " <<x1[0] << " " <<y1[0] << "\n";
	} else if (k==1) {
	  x2[np2] = radiusH[j]*cos(phiH[j]);
	  y2[np2] = radiusH[j]*sin(phiH[j]);
	  np2++;
	  //	  if (np2 == 1) std::cout << i << " 1 " <<x2[0] << " " <<y2[0] << "\n";
	} else {
	  x3[np3] = radiusH[j]*cos(phiH[j]);
	  y3[np3] = radiusH[j]*sin(phiH[j]);
	  np3++;
	}
      }
    }
    //    std::cout << "i " << i << " " <<np1 << " " <<np2 << " " <<np3 <<"\n";
    if (np1 > 0) {
      gr[0][i] = new TGraph(np1,x1,y1); gr[0][i]->SetTitle(""); 
      gr[0][i]->SetMarkerStyle(symbol[i]);  gr[0][i]->SetMarkerColor(colr[0]);
    } else 
      gr[0][i] = 0;
    if (np2 > 0) {
      gr[1][i] = new TGraph(np2,x2,y2); gr[1][i]->SetTitle(""); 
      gr[1][i]->SetMarkerStyle(symbol[i]);  gr[1][i]->SetMarkerColor(colr[1]);
    } else 
      gr[1][i] = 0;
    if (np3 > 0) {
      gr[2][i] = new TGraph(np3,x3,y3); gr[2][i]->SetTitle(""); 
      gr[2][i]->SetMarkerStyle(symbol[i]);  gr[2][i]->SetMarkerColor(colr[2]);
    } else 
      gr[2][i] = 0;
  }
  np1 = np2 = np3 = 0;
  for (int j=0; j<np; j++) {
    if (etaIndex[j] < 29 || etaIndex[j] > 41) {
      int k = 2;
      if (depths[j] == 3) k = 0;
      else if (depths[j] == 4) k = 1;
      if (k == 0) {
	x1[np1] = radiusH[j]*cos(phiH[j]);
	y1[np1] = radiusH[j]*sin(phiH[j]);
	np1++;
	if (np1 == 1) std::cout << i << " 0 " <<x1[0] << " " <<y1[0] << "\n";
      } else if (k==1) {
	x2[np2] = radiusH[j]*cos(phiH[j]);
	y2[np2] = radiusH[j]*sin(phiH[j]);
	np2++;
	if (np2 == 1) std::cout << i << " 1 " <<x2[0] << " " <<y2[0] << "\n";
      } else {
	x3[np3] = radiusH[j]*cos(phiH[j]);
	y3[np3] = radiusH[j]*sin(phiH[j]);
	np3++;
      }
    }
  }
  //    std::cout << "i " << i << " " <<np1 << " " <<np2 << " " <<np3 <<"\n";
  if (np1 > 0) {
    gr[0][13] = new TGraph(np1,x1,y1); gr[0][13]->SetTitle(""); 
    gr[0][13]->SetMarkerStyle(symbol[13]);  gr[0][13]->SetMarkerColor(colr[0]);
  } else 
    gr[0][13] = 0;
  if (np2 > 0) {
    gr[1][13] = new TGraph(np2,x2,y2); gr[1][13]->SetTitle(""); 
    gr[1][13]->SetMarkerStyle(symbol[13]);  gr[1][13]->SetMarkerColor(colr[1]);
  } else 
    gr[1][13] = 0;
  if (np3 > 0) {
    gr[2][13] = new TGraph(np3,x3,y3); gr[2][13]->SetTitle(""); 
    gr[2][13]->SetMarkerStyle(symbol[13]);  gr[2][13]->SetMarkerColor(colr[2]);
  } else 
    gr[2][13] = 0;

  TCanvas *c0  = new TCanvas("c0","PMT Hits",800,600); 
  TH1F *vFrame = c0->DrawFrame(1000.0,-250.0,1500.0,250.0);
  vFrame->SetXTitle("x (mm)");
  vFrame->SetYTitle("y (mm)");
  for (int i=0; i<=13; i++) {
    for (int j=0; j<3; j++) {
      if (gr[j][i] != 0) {
	gr[j][i]->Draw("p");
	gr[j][i]->SetLineColor(colr[j]); gr[j][i]->SetLineWidth(2);
	//	std::cout << "Next " << i << " " << j << "\n";
      }
    }
  }
  TLegend *leg1 = new TLegend(0.75,0.55,0.90,0.90);
  char list[40];
  for (i=0; i<= 13; i++) {
    if (i < 13) sprintf (list, "#eta = %d", i+29);
    else        sprintf (list, "Unknown #eta");
    if      (gr[0][i] != 0) leg1->AddEntry(gr[0][i], list, "P");
    else if (gr[1][i] != 0) leg1->AddEntry(gr[1][i], list, "P");
  }
  for (i=0; i<2; i++) {
    if (i == 0) sprintf (list, "Long Fibre");
    else        sprintf (list, "Short Fibre");
    if      (gr[i][0] != 0) leg1->AddEntry(gr[i][0], list, "L");
    else if (gr[i][1] != 0) leg1->AddEntry(gr[i][1], list, "L");
    else if (gr[i][2] != 0) leg1->AddEntry(gr[i][2], list, "L");
  }
  leg1->SetFillColor(0); leg1->SetTextSize(0.03); 
  leg1->SetBorderSize(1); leg1->Draw();

  if (save != 0) {
    if (save > 0) c0->SaveAs("PMTHits.eps");
    else          c0->SaveAs("PMTHits.gif");
  }
}
Beispiel #4
0
/**
* GetFtpDirectory
*
* Description: 1) Conect to ftp server, change directory. 
*	2) Get dir listing.
*	3) Read existing listing file, 
*	4) If listing has changed, write new dir listing file.
*
* Parameters:	CConnection - describes ftp connection info, user, host etc.
*				dir - ftp remote directory
*				ftpClient - optional ftpclient. if null, will create, connect and close.
* Return:
*				bool - success
* ??? was it updated?
*/
bool CFtpManager::GetFtpDirectory(CConnection * con, CString &directory, CRealFtpClient * ftpClient)
{
	bool result = false;
	//TRACE1(" con %s \n ", con->name);

	//Connect(con, m_ftpClient);
	//if(!m_ftpClient.IsConnected()) // Not connected
	//{
	//	return;
	//}
	bool closeConnection = false;
	if(!ftpClient)
	{
		ftpClient = new CRealFtpClient();
		closeConnection = true;
	}
	if(!ftpClient->IsConnected()) // Not connected
	{
		int retcode = 11;
		retcode = ftpClient->FTPConnect(con->host, con->user, con->password, _T(""));
		if(retcode == UTE_SUCCESS)
		{
			ftpClient->SetFireWallMode(TRUE);
		}
	}

	//m_ftpClient.SetFireWallMode(TRUE);
	//ftpClient->SetFireWallMode(TRUE);

	CString localStorePath;
	GetLocalStorePath(con, localStorePath);
	localStorePath = localStorePath + directory + CString(_T(""));
	localStorePath.Replace('/', '\\');

	CString dirContentListing(_T(""));
	CString fileListing(_T(""));
	CString folderListing(_T(""));

	CUT_DIRINFO di;
	_TCHAR entry[HISTORY_ENTRY_SIZE];
	_TCHAR dir[MAX_PATH];
	int valRet;
	{
		valRet = ftpClient->ChDir( directory );
		if (valRet != UTE_SUCCESS){
			//m_history.AddLine(CUT_ERR::GetErrorString (valRet));
			TRACE1(" chdir failed: %s \n ", CUT_ERR::GetErrorString(valRet) );
		}
		else 
		{
			int dirInfo = ftpClient->GetDirInfo();

			int count = ftpClient->GetDirInfoCount();
			for(int t=0;t<count;t++){
				ftpClient->GetDirEntry(t, &di);
				// v4.2 dir info now has _TCHAR
				// Format: Name,size,time, time display
				_sntprintf(entry, 
					sizeof(entry)/sizeof(_TCHAR), 
					_T("<n>%s</n><s>%ld</s><d>%2.2d/%2.2d/%2.2d %2.2d:%2.2d</d><p>%d</p><o>%s</o><g>%s</g>"),
					di.fileName, di.fileSize,
					di.year, di.month, di.day, di.hour, di.minute, di.permissions, di.owner, di.group);
					
				//m_history.AddLine(entry);

				if(di.isDir)
				{
					CString folderPath(localStorePath + _T("") + di.fileName );
					if(GetFileAttributes(folderPath) == INVALID_FILE_ATTRIBUTES){
						CreateDirectory(folderPath, NULL);
					}

					CString fileInfo(_T(""));
					fileInfo = fileInfo + CString(_T("<t>d</t>")) + CString(entry) + _T("\n");
					folderListing = folderListing + fileInfo;
				} else {
					// File
					CString fileInfo(_T(""));
					fileInfo = fileInfo + CString(_T("<t>f</t>")) + CString(entry) + _T("\n");
					fileListing = fileListing + fileInfo;
				}
			}
			dirContentListing = CString(folderListing + fileListing);

			
			// write dir descriptor
			// dirContentListing
			CString dirContentFile(localStorePath + _T(".files.rftp"));


			// Check existing files.rftp. Don't rewrite if its the same. SSD safety.
			CString existingListing(_T(""));
			CFileStatus status;
			if(CFile::GetStatus(dirContentFile, status))
			{
				CStdioFile file (dirContentFile, CStdioFile::modeRead | CFile::shareDenyNone);
				CString buffer;
				while (file.ReadString(buffer))
				{
					existingListing = existingListing + buffer + _T("\n");
				}
			}

			
			if(existingListing.Compare(dirContentListing) != 0)
			{
				CFile theFile(dirContentFile, CFile::modeReadWrite | CFile::modeCreate);
				
				char buffer[200000];
				sprintf(buffer, "%S", dirContentListing); // CString to char *
				int len = strlen(buffer);
				//theFile.Write( (LPCTSTR) dirContentListing, dirContentListing.GetLength() * sizeof(TCHAR));
				
				//
				// Error here ***********
				//
				CString buffy(dirContentFile);
				if(buffy.Find(CString(_T("newsletter-form"))) != 1){
					int i  = 0;
				}

				theFile.Write(buffer, len);

				TRACE0(" GetFtpDirectory Updated \n");
				m_directoryUpdated = true;  
			} else {
				//TRACE0(" GetFtpDirectory Allready up to date \n");
				m_directoryUpdated = false;
			}

			//TRACE1(" file: %s \n", entry);
			result = true;
		} // chdir success		
	}
	if(closeConnection){
		ftpClient->Close();
		delete ftpClient;
	}
	return result;
}
Beispiel #5
0
std::ofstream fileFactory(std::string filename){
	std::ofstream theFile(filename.c_str());
	return theFile;
}
VexEditorComponent::VexEditorComponent (VexFilter* const ownerFilter)
    : AudioProcessorEditor(ownerFilter)
{
	//Comboboxes, wave selection
	addAndMakeVisible (comboBox = new ComboBox (String::empty));
    comboBox->setEditableText (false);
    comboBox->setJustificationType (Justification::centredLeft);
    comboBox->setTextWhenNothingSelected (String(T("silent")));
    comboBox->setTextWhenNoChoicesAvailable (String(T("silent")));
    comboBox->addListener (this);
	comboBox->setColour(ComboBox::backgroundColourId, Colours::black);
	comboBox->setColour(ComboBox::textColourId, Colours::lightgrey);
	comboBox->setColour(ComboBox::outlineColourId, Colours::grey);
	comboBox->setColour(ComboBox::buttonColourId, Colours::grey);
	comboBox->setWantsKeyboardFocus(false); 
	comboBox->setLookAndFeel(&mlaf);

    addAndMakeVisible (comboBox2 = new ComboBox (String::empty));
    comboBox2->setEditableText (false);
    comboBox2->setJustificationType (Justification::centredLeft);
    comboBox2->setTextWhenNothingSelected (String(T("silent")));
    comboBox2->setTextWhenNoChoicesAvailable (String(T("silent")));
    comboBox2->addListener (this);
	comboBox2->setColour(ComboBox::backgroundColourId, Colours::black);
	comboBox2->setColour(ComboBox::textColourId, Colours::lightgrey);
	comboBox2->setColour(ComboBox::outlineColourId, Colours::grey);
	comboBox2->setColour(ComboBox::buttonColourId, Colours::grey);
	comboBox2->setWantsKeyboardFocus(false);
	comboBox2->setLookAndFeel(&mlaf);

    addAndMakeVisible (comboBox3 = new ComboBox (String::empty));
    comboBox3->setEditableText (false);
    comboBox3->setJustificationType (Justification::centredLeft);
    comboBox3->setTextWhenNothingSelected (String(T("silent")));
    comboBox3->setTextWhenNoChoicesAvailable (String(T("silent")));
    comboBox3->addListener (this);
	comboBox3->setColour(ComboBox::backgroundColourId, Colours::black);
	comboBox3->setColour(ComboBox::textColourId, Colours::lightgrey);
	comboBox3->setColour(ComboBox::outlineColourId, Colours::grey);
	comboBox3->setColour(ComboBox::buttonColourId, Colours::grey);
	comboBox3->setWantsKeyboardFocus(false);
	comboBox3->setLookAndFeel(&mlaf);
	
#if 0
	File location = (File::getSpecialLocation(File::userHomeDirectory)).getChildFile(".vex");
	if (! location.exists ())
	    location.createDirectory ();

    DBG (location.getFullPathName());

	String filePath = location.getFullPathName();

    DirectoryIterator iter (File(filePath), true, "*.raw");

	int i = 1;
	while (iter.next())
	{
		File theFile(iter.getFile());
		if (theFile.hasFileExtension (T("raw")))
		{
			i++;
			comboBox->addItem (theFile.getFileNameWithoutExtension(), i);
			comboBox2->addItem (theFile.getFileNameWithoutExtension(), i);
			comboBox3->addItem (theFile.getFileNameWithoutExtension(), i);
		}
	}
#endif

    int tableSize = waveRenderer::getWaveTableSize ();
	for (int i = 0; i < tableSize; i++)
	{
	    String tableName (waveRenderer::getWaveTableName (i));

		comboBox->addItem (tableName, i + 1);
		comboBox2->addItem (tableName, i + 1);
		comboBox3->addItem (tableName, i + 1);
	}

	//Make sliders
	for (int i = 0; i < 89; i++)
	{
		addAndMakeVisible (sliders[i] = new SnappingSlider (T("s")));
		sliders[i]->setSliderStyle(Slider::RotaryVerticalDrag);
		sliders[i]->setRange (0, 1, 0);
		sliders[i]->setSnap(0.0f, 0.0f);
		sliders[i]->setLookAndFeel(&mlaf);
		sliders[i]->addListener (this);
	}

	//Adjust the center of some
    sliders[1]->setRange (0, 1, 0.25f);		
	sliders[1]->setSnap(0.5f, 0.05f);
    sliders[2]->setSnap(0.5f, 0.05f);
    sliders[3]->setSnap(0.5f, 0.05f);
    sliders[4]->setSnap(0.5f, 0.05f);
    sliders[8]->setSnap(0.5f, 0.05f);
    sliders[13]->setSnap(0.5f, 0.05f);
    sliders[18]->setSnap(0.5f, 0.05f);

	int tmp = 24;
    sliders[1 + tmp]->setRange (0, 1, 0.25f);
	sliders[1 + tmp]->setSnap(0.5f, 0.05f);
    sliders[2 + tmp]->setSnap(0.5f, 0.05f);
    sliders[3 + tmp]->setSnap(0.5f, 0.05f);
    sliders[4 + tmp]->setSnap(0.5f, 0.05f);
    sliders[8 + tmp]->setSnap(0.5f, 0.05f);
    sliders[13 + tmp]->setSnap(0.5f, 0.05f);
    sliders[18 + tmp]->setSnap(0.5f, 0.05f);

	tmp = 48;
    sliders[1 + tmp]->setRange (0, 1, 0.25f);
	sliders[1 + tmp]->setSnap(0.5f, 0.05f);
    sliders[2 + tmp]->setSnap(0.5f, 0.05f);
    sliders[3 + tmp]->setSnap(0.5f, 0.05f);
    sliders[4 + tmp]->setSnap(0.5f, 0.05f);
    sliders[8 + tmp]->setSnap(0.5f, 0.05f);
    sliders[13 + tmp]->setSnap(0.5f, 0.05f);
    sliders[18 + tmp]->setSnap(0.5f, 0.05f);

    sliders[83]->setSnap(0.5f, 0.05f);
    sliders[84]->setSnap(0.5f, 0.05f);
    sliders[85]->setSnap(0.5f, 0.05f);

	sliders[75]->setSnap(0.0f, 0.05f);
	sliders[78]->setSnap(0.0f, 0.05f);
	sliders[82]->setSnap(0.0f, 0.05f);

	//PART ON/OFF
    addAndMakeVisible (TB = new TextButton (T("new button")));
    TB->setButtonText (String::empty);
    TB->addButtonListener (this);
    TB->setColour (TextButton::buttonColourId, Colours::darkred.withAlpha(0.5f));
	TB->setColour(TextButton::buttonOnColourId, Colours::red);
	TB->setClickingTogglesState(true);
	TB->setToggleState(false,false);

    addAndMakeVisible (TB2 = new TextButton (T("new button")));
    TB2->setButtonText (String::empty);
    TB2->addButtonListener (this);
    TB2->setColour (TextButton::buttonColourId, Colours::darkred.withAlpha(0.5f));
	TB2->setColour(TextButton::buttonOnColourId, Colours::red);
	TB2->setClickingTogglesState(true);
	TB2->setToggleState(false,false);

    addAndMakeVisible (TB3 = new TextButton (T("new button")));
    TB3->setButtonText (String::empty);
    TB3->addButtonListener (this);
    TB3->setColour (TextButton::buttonColourId, Colours::darkred.withAlpha(0.5f));
	TB3->setColour(TextButton::buttonOnColourId, Colours::red);
	TB3->setClickingTogglesState(true);
	TB3->setToggleState(false,false);

	//Peggy ON/OFF
    addAndMakeVisible (TB4 = new TextButton (T("new button")));
    TB4->setButtonText (String::empty);
    TB4->addButtonListener (this);
    TB4->setColour (TextButton::buttonColourId, Colours::darkblue.withAlpha(0.5f));
	TB4->setColour(TextButton::buttonOnColourId, Colours::blue);
	TB4->setClickingTogglesState(true);
	TB4->setToggleState(false,false);

    addAndMakeVisible (TB5 = new TextButton (T("new button")));
    TB5->setButtonText (String::empty);
    TB5->addButtonListener (this);
    TB5->setColour (TextButton::buttonColourId, Colours::darkblue.withAlpha(0.5f));
	TB5->setColour(TextButton::buttonOnColourId, Colours::blue);
	TB5->setClickingTogglesState(true);
	TB5->setToggleState(false,false);

    addAndMakeVisible (TB6 = new TextButton (T("new button")));
    TB6->setButtonText (String::empty);
    TB6->addButtonListener (this);
    TB6->setColour (TextButton::buttonColourId, Colours::darkblue.withAlpha(0.5f));
	TB6->setColour(TextButton::buttonOnColourId, Colours::blue);
	TB6->setClickingTogglesState(true);
	TB6->setToggleState(false,false);

	addChildComponent(p1 = new PeggyViewComponent(ownerFilter, 1));
	p1->setLookAndFeel(&mlaf);
	addChildComponent(p2 = new PeggyViewComponent(ownerFilter, 2));
	p2->setLookAndFeel(&mlaf);
	addChildComponent(p3 = new PeggyViewComponent(ownerFilter, 3));
	p3->setLookAndFeel(&mlaf);

	internalCachedImage1 = ImageCache::getFromMemory (Resources::vex3_png, Resources::vex3_pngSize);

	ownerFilter->addChangeListener (this);
	setSize(800,500);

	updateParametersFromFilter(true);
Beispiel #7
0
int main(int argc, char *argv[])
{

    Foam::timeSelector::addOptions(false);
    Foam::argList::validArgs.append("expressionDict");
#   include "addRegionOption.H"
    argList::validOptions.insert("noDimensionChecking","");
    argList::validOptions.insert("foreignMeshesThatFollowTime",
                                  "<list of mesh names>");

#   include "setRootCase.H"

    printSwakVersion();

    IFstream theFile(args.args()[1]);
    dictionary theExpressions(theFile);
    wordList foreignMeshesThatFollowTime(0);

    if (!args.options().found("time") && !args.options().found("latestTime")) {
        FatalErrorIn("main()")
            << args.executable()
                << ": time/latestTime option is required" << endl
            << exit(FatalError);
    }

    if(args.options().found("noDimensionChecking")) {
        dimensionSet::debug=0;
    }
    if(args.options().found("foreignMeshesThatFollowTime")) {
        string followMeshes(
            args.options()["foreignMeshesThatFollowTime"]
        );
        IStringStream followStream("("+followMeshes+")");
        foreignMeshesThatFollowTime=wordList(followStream);
    }

#   include "createTime.H"
    Foam::instantList timeDirs = Foam::timeSelector::select0(runTime, args);

#   include "createNamedMesh.H"

    forAllConstIter(IDLList<entry>, theExpressions, iter)
    {
        const dictionary &dict=iter().dict();

        CommonValueExpressionDriver::readForeignMeshInfo(dict);
    }

    forAll(timeDirs, timeI)
    {
        runTime.setTime(timeDirs[timeI], timeI);

        Foam::Info << "\nTime = " << runTime.timeName() << Foam::endl;

        mesh.readUpdate();

        forAll(foreignMeshesThatFollowTime,i) {
            const word &name=foreignMeshesThatFollowTime[i];
            if(MeshesRepository::getRepository().hasMesh(name)) {
                Info << "Setting mesh " << name << " to current Time"
                    << endl;

                MeshesRepository::getRepository().setTime(
                    name,
                    runTime.value()
                );
            } else {
                FatalErrorIn(args.executable())
                    << "No mesh with name " << name << " declared. " << nl
                        << "Can't follow current time"
                        << endl
                        << exit(FatalError);

            }
        }

        forAllConstIter(IDLList<entry>, theExpressions, iter)
        {
            Info << iter().keyword() << " : " << flush;

            const dictionary &dict=iter().dict();

            autoPtr<CommonValueExpressionDriver> driver=
                CommonValueExpressionDriver::New(dict,mesh);
            wordList accumulations(dict.lookup("accumulations"));

            driver->setSearchBehaviour(
                true,
                true,
                true         // search on disc
            );

            driver->clearVariables();
            driver->parse(string(dict.lookup("expression")));
            word rType=driver->CommonValueExpressionDriver::getResultType();

            if(rType==pTraits<scalar>::typeName) {
                writeData<scalar>(driver(),accumulations);
            } else if(rType==pTraits<vector>::typeName) {
                writeData<vector>(driver(),accumulations);
            } else if(rType==pTraits<tensor>::typeName) {
                writeData<tensor>(driver(),accumulations);
            } else if(rType==pTraits<symmTensor>::typeName) {
                writeData<symmTensor>(driver(),accumulations);
            } else if(rType==pTraits<sphericalTensor>::typeName) {
                writeData<sphericalTensor>(driver(),accumulations);
            } else {
                WarningIn(args.executable())
                    << "Don't know how to handle type " << rType
                        << endl;
            }

            Info << endl;
        }
Beispiel #8
0
MapTile::MapTile(int pX, int pZ, const std::string& pFilename, bool pBigAlpha)
{
	this->modelCount = 0;
	this->mPositionX = pX;
	this->mPositionZ = pZ;

	this->changed = 0;
	this->xbase = mPositionX * TILESIZE;
	this->zbase = mPositionZ * TILESIZE;

	this->mBigAlpha = pBigAlpha;

	for (int i = 0; i < 16; ++i)
	{
		for (int j = 0; j < 16; j++)
		{
			mChunks[i][j] = NULL;
		}
	}

	mFilename = pFilename;

	MPQFile theFile(mFilename);

	Log << "Opening tile " << mPositionX << ", " << mPositionZ << " (\"" << mFilename << "\") from " << (theFile.isExternal() ? "disk" : "MPQ") << "." << std::endl;

	// - Parsing the file itself. --------------------------

	// We store this data to load it at the end.
	uint32_t lMCNKOffsets[256];
	std::vector<ENTRY_MDDF> lModelInstances;
	std::vector<ENTRY_MODF> lWMOInstances;

	uint32_t fourcc;
	uint32_t size;

	MHDR Header;

	// - MVER ----------------------------------------------

	uint32_t version;

	theFile.read(&fourcc, 4);
	theFile.seekRelative(4);
	theFile.read(&version, 4);

	assert(fourcc == 'MVER' && version == 18);

	// - MHDR ----------------------------------------------

	theFile.read(&fourcc, 4);
	theFile.seekRelative(4);

	assert(fourcc == 'MHDR');

	theFile.read(&Header, sizeof(MHDR));

	mFlags = Header.flags;

	// - MCIN ----------------------------------------------

	theFile.seek(Header.mcin + 0x14);
	theFile.read(&fourcc, 4);
	theFile.seekRelative(4);

	assert(fourcc == 'MCIN');

	for (int i = 0; i < 256; ++i)
	{
		theFile.read(&lMCNKOffsets[i], 4);
		theFile.seekRelative(0xC);
	}

	// - MTEX ----------------------------------------------

	theFile.seek(Header.mtex + 0x14);
	theFile.read(&fourcc, 4);
	theFile.read(&size, 4);

	assert(fourcc == 'MTEX');

	{
		char* lCurPos = reinterpret_cast<char*>(theFile.getPointer());
		char* lEnd = lCurPos + size;

		while (lCurPos < lEnd)
		{
			mTextureFilenames.push_back(std::string(lCurPos));
			lCurPos += strlen(lCurPos) + 1;
		}
	}

	// - MMDX ----------------------------------------------

	theFile.seek(Header.mmdx + 0x14);
	theFile.read(&fourcc, 4);
	theFile.read(&size, 4);

	assert(fourcc == 'MMDX');

	{
		char* lCurPos = reinterpret_cast<char*>(theFile.getPointer());
		char* lEnd = lCurPos + size;

		while (lCurPos < lEnd)
		{
			mModelFilenames.push_back(std::string(lCurPos));
			lCurPos += strlen(lCurPos) + 1;
		}
	}

	// - MWMO ----------------------------------------------

	theFile.seek(Header.mwmo + 0x14);
	theFile.read(&fourcc, 4);
	theFile.read(&size, 4);

	assert(fourcc == 'MWMO');

	{
		char* lCurPos = reinterpret_cast<char*>(theFile.getPointer());
		char* lEnd = lCurPos + size;

		while (lCurPos < lEnd)
		{
			mWMOFilenames.push_back(std::string(lCurPos));
			lCurPos += strlen(lCurPos) + 1;
		}
	}

	// - MDDF ----------------------------------------------

	theFile.seek(Header.mddf + 0x14);
	theFile.read(&fourcc, 4);
	theFile.read(&size, 4);

	assert(fourcc == 'MDDF');

	ENTRY_MDDF* mddf_ptr = reinterpret_cast<ENTRY_MDDF*>(theFile.getPointer());
	for (unsigned int i = 0; i < size / 36; ++i)
	{
		lModelInstances.push_back(mddf_ptr[i]);
	}

	// - MODF ----------------------------------------------

	theFile.seek(Header.modf + 0x14);
	theFile.read(&fourcc, 4);
	theFile.read(&size, 4);

	assert(fourcc == 'MODF');

	ENTRY_MODF* modf_ptr = reinterpret_cast<ENTRY_MODF*>(theFile.getPointer());
	for (unsigned int i = 0; i < size / 64; ++i)
	{
		lWMOInstances.push_back(modf_ptr[i]);
	}

	// - MISC ----------------------------------------------

	//! \todo  Parse all chunks in the new style!

	// - MH2O ----------------------------------------------
	if (Header.mh2o != 0) {
		theFile.seek(Header.mh2o + 0x14);
		theFile.read(&fourcc, 4);
		theFile.read(&size, 4);

		int ofsW = Header.mh2o + 0x14 + 0x8;
		assert(fourcc == 'MH2O');

		Water = new TileWater(this, xbase, zbase); //has water
		Water->readFromFile(theFile, ofsW); //reading MH2O data at separated class...
	}
	else{
		Water = new TileWater(this, xbase, zbase); //empty water tile
	}

	// - MFBO ----------------------------------------------

	if (mFlags & 1)
	{
		theFile.seek(Header.mfbo + 0x14);
		theFile.read(&fourcc, 4);
		theFile.read(&size, 4);

		assert(fourcc == 'MFBO');

		int16_t mMaximum[9], mMinimum[9];
		theFile.read(mMaximum, sizeof(mMaximum));
		theFile.read(mMinimum, sizeof(mMinimum));

		static const float xPositions[] = { this->xbase, this->xbase + 266.0f, this->xbase + 533.0f };
		static const float yPositions[] = { this->zbase, this->zbase + 266.0f, this->zbase + 533.0f };

		for (int y = 0; y < 3; y++)
		{
			for (int x = 0; x < 3; x++)
			{
				int pos = x + y * 3;
				mMinimumValues[pos * 3 + 0] = xPositions[x];
				mMinimumValues[pos * 3 + 1] = mMinimum[pos];
				mMinimumValues[pos * 3 + 2] = yPositions[y];

				mMaximumValues[pos * 3 + 0] = xPositions[x];
				mMaximumValues[pos * 3 + 1] = mMaximum[pos];
				mMaximumValues[pos * 3 + 2] = yPositions[y];
			}
		}
	}

	// - MTFX ----------------------------------------------
	/*
	//! \todo Implement this or just use Terrain Cube maps?
	Log << "MTFX offs: " << Header.mtfx << std::endl;
	if(Header.mtfx != 0){
	Log << "Try to load MTFX" << std::endl;
	theFile.seek( Header.mtfx + 0x14 );

	theFile.read( &fourcc, 4 );
	theFile.read( &size, 4 );

	assert( fourcc == 'MTFX' );


	{
	char* lCurPos = reinterpret_cast<char*>( theFile.getPointer() );
	char* lEnd = lCurPos + size;
	int tCount = 0;
	while( lCurPos < lEnd ) {
	int temp = 0;
	theFile.read(&temp, 4);
	Log << "Adding to " << mTextureFilenames[tCount].first << " texture effect: " << temp << std::endl;
	mTextureFilenames[tCount++].second = temp;
	lCurPos += 4;
	}
	}

	}*/

	// - Done. ---------------------------------------------

	// - Load textures -------------------------------------

	//! \note We no longer pre load textures but the chunks themselves do.

	// - Load WMOs -----------------------------------------

	for (std::vector<ENTRY_MODF>::iterator it = lWMOInstances.begin(); it != lWMOInstances.end(); ++it)
	{
		gWorld->mWMOInstances.insert(std::pair<int, WMOInstance>(it->uniqueID, WMOInstance(WMOManager::add(mWMOFilenames[it->nameID]), &(*it))));
	}

	// - Load M2s ------------------------------------------

	for (std::vector<ENTRY_MDDF>::iterator it = lModelInstances.begin(); it != lModelInstances.end(); ++it)
	{
		gWorld->mModelInstances.insert(std::pair<int, ModelInstance>(it->uniqueID, ModelInstance(ModelManager::add(mModelFilenames[it->nameID]), &(*it))));
	}

	// - Load chunks ---------------------------------------

	for (int nextChunk = 0; nextChunk < 256; ++nextChunk)
	{
		theFile.seek(lMCNKOffsets[nextChunk]);
		mChunks[nextChunk / 16][nextChunk % 16] = new MapChunk(this, &theFile, mBigAlpha);
	}

	theFile.close();

	// - Really done. --------------------------------------

	LogDebug << "Done loading tile " << mPositionX << "," << mPositionZ << "." << std::endl;
}
Beispiel #9
0
void produceMikeTables(int LHCsqrts = 7, string sample = "gg") {

  cout << "FIRST RUN source changeCinZero.csh!" << endl;

  string Sources[6] = {"","","","","","",""};
  if (sample == "gg") {
    Sources[0] = "Resummation";
    Sources[1] = "TopMass";
  }
  if (sample == "zz" && LHCsqrts == 7) {
    Sources[0] = "SingleZ";
  }
  if (sample == "zz" && LHCsqrts == 8) {
    Sources[0] = "UnbRegion";
  }

  ofstream *mikeFile;
  char fileName[200];

  sprintf(fileName,"text/paramShifts_%s_%dTeV.txt",sample.c_str(),LHCsqrts);
  mikeFile = new ofstream(fileName);

  char thePar[10];
  char equalS[1];
  char dashS[1];
  char pmS[3];
  char theLimit1[10];
  char theLimit2[10];
  float fitted, error;

  const int nPars = 7;
  string parNames[nPars] = {"m","n","n2","bb","bb2","fexp","T"};
  float parVal[nPars];
  float upVar[nPars];
  float downVar[nPars];

  // Inizia
  sprintf(fileName,"text/paramsCJLST_%s_%dTeV_default.txt",sample.c_str(),LHCsqrts);
  ifstream theFile(fileName);
  
  while (theFile >> thePar >> equalS >> fitted >> pmS >> error >> theLimit1 >> dashS >> theLimit2) {
    cout << thePar << " " << fitted << " " << error << endl;
    for (int ii = 0; ii < nPars; ii++) {
      if (!strcmp(thePar,parNames[ii].c_str())) {
	parVal[ii] = fitted; 
	upVar[ii] = error*error;
	downVar[ii] = error*error;
      }
    }
  }
   
  theFile.close();

  for (int jj = 0; jj < 6; jj++) {
    if (Sources[jj] != "") {
      
      cout << "Systematics n. " << jj+1 << " : " << Sources[jj] << endl;

      sprintf(fileName,"text/paramsCJLST_%s_%dTeV_%s.txt",sample.c_str(),LHCsqrts,Sources[jj].c_str());
      ifstream theFile(fileName);
      while (theFile >> thePar >> equalS >> fitted >> pmS >> error >> theLimit1 >> dashS >> theLimit2) {
	cout << thePar << " " << fitted << " " << error << endl;
	for (int ii = 0; ii < nPars; ii++) {
	  if (!strcmp(thePar,parNames[ii].c_str())) {
	    if (fitted > parVal[ii]) upVar[ii] += (fitted - parVal[ii])*(fitted - parVal[ii]);
	    if (fitted < parVal[ii]) downVar[ii] += (fitted - parVal[ii])*(fitted - parVal[ii]);
	  }
	}
      }

      theFile.close();
    }
  }
Beispiel #10
0
MapIndex::MapIndex(const std::string &pBasename)
  : mHasAGlobalWMO(false)
  , mBigAlpha(false)
  , noadt(false)
  , changed(false)
  , cx(-1)
  , cz(-1)
  , basename(pBasename)
{
  std::stringstream filename;
  filename << "World\\Maps\\" << basename << "\\" << basename << ".wdt";

  MPQFile theFile(filename.str());

  uint32_t fourcc;
  uint32_t size;

  // - MVER ----------------------------------------------

  uint32_t version;

  theFile.read(&fourcc, 4);
  theFile.read(&size, 4);
  theFile.read(&version, 4);

  //! \todo find the correct version of WDT files.
  assert( fourcc == 'MVER' && version == 18 );

  // - MHDR ----------------------------------------------

  theFile.read(&fourcc, 4);
  theFile.read(&size, 4);

  assert( fourcc == 'MPHD' );

  theFile.read(&mphd, sizeof(MPHD));

  mHasAGlobalWMO = mphd.flags & 1;
  mBigAlpha = mphd.flags & 4;

  // - MAIN ----------------------------------------------

  theFile.read( &fourcc, 4 );
  theFile.seekRelative( 4 );

  assert( fourcc == 'MAIN' );

  /// this is the theory. Sadly, we are also compiling on 64 bit machines with size_t being 8 byte, not 4. Therefore, we can't do the same thing, Blizzard does in its 32bit executable.
  //theFile.read( &(mTiles[0][0]), sizeof( 8 * 64 * 64 ) );

  for( int j = 0; j < 64; ++j )
  {
    for( int i = 0; i < 64; ++i )
    {
      theFile.read(&mTiles[j][i].flags, 4);
      theFile.seekRelative( 4 );

      std::stringstream filename;
      filename << "World\\Maps\\" << basename << "\\" << basename << "_" << i << "_" << j << ".adt";

      mTiles[j][i].tile = NULL;
      mTiles[j][i].onDisc = MPQFile::existsOnDisk(filename.str());

      if(mTiles[j][i].onDisc && !(mTiles[j][i].flags & 1))
      {
        mTiles[j][i].flags |= 1;
        changed = true;
      }
    }
  }

  if(!theFile.isEof() && mHasAGlobalWMO)
  {
    //! \note We actually don't load WMO only worlds, so we just stop reading here, k?
    //! \bug MODF reads wrong. The assertion fails every time. Somehow, it keeps being MWMO. Or are there two blocks?
    //! \nofuckingbug  on eof read returns just without doing sth to the var and some wdts have a MWMO without having a MODF so only checking for eof above is not enough

    mHasAGlobalWMO = false;

    // - MWMO ----------------------------------------------

    theFile.read(&fourcc, 4);
    theFile.read(&size, 4);

    assert(fourcc == 'MWMO');

    globalWMOName = std::string(theFile.getPointer(), size);
    theFile.seekRelative(size);

    // - MODF ----------------------------------------------

    theFile.read(&fourcc, 4);
    theFile.read(&size, 4);

    assert( fourcc == 'MODF' );

    theFile.read(&wmoEntry, sizeof(ENTRY_MODF));
  }

  // -----------------------------------------------------

  theFile.close();
}
Beispiel #11
0
P<BundleData> DirBundleLoader::loadBundle(String location)
{
	P<BundleData> bundleData = new BundleData();

	bundleData->setLocation(location);

	String path = location;
	path.append(L"\\META-INF\\MANIFEST.MF");
	P<File> file = new File(path);

	P<Manifest> mf = new Manifest(file);
	P<Map<String,String>> entries = mf->getEntries();

	String symbolicName = entries->get(Constants::BUNDLE_SYMBOLICNAME);
	if (symbolicName == (String)null || symbolicName.equals(L"") ) 
	{
        throw BundleException(String(L"Bundle symbolic name not found: ") + file->getAbsolutePath());
    }

	//if (framework->getBundle(symbolicName) != null) 
	//{
 //       throw BundleException(String(L"Bundle(SymbolicName: ") + symbolicName + String(L") already exists: ") + file->getAbsolutePath());
 //   }

	bundleData->setSymbolicName(symbolicName);

	//get Bundle-Name
	String name = entries->get(Constants::BUNDLE_NAME);
    if (name == (String)null || name.equals(L"")) 
	{
		name = File(location).getName();
    }

	bundleData->setName(name);

    // Validate the bundle activator.

	String activator = entries->get(Constants::BUNDLE_ACTIVATOR);
    if (activator == (String)null || symbolicName.equals(L"") )
	{
        throw BundleException(String(L"Bundle activator definition not found: ") + file->getAbsolutePath());
    }

	bundleData->setActivator(activator);

	String nativeLib = entries->get(Constants::BUNDLE_NATIVE_LIB);
	if (nativeLib == (String)null || nativeLib.equals(L"") )
	{
		nativeLib = name + String(L".dll");
	}

	nativeLib = String(location) + String(L"\\") + nativeLib;

	bundleData->setNativeLib(nativeLib);

	//P<Library> lib= new DllLibrary();
	//lib->load(this->nativeLib);

	//if (!lib->containsClass(activator)) 
	//{
 //       throw BundleException(String(L"Bundle activator class(\"") + activator + String(L"\") not found: ") + file->getAbsolutePath());
 //   }

	//lib->free();

	String description = entries->get(Constants::BUNDLE_DESCRIPTION);
    if (description == (String)null || description.equals(L"")) 
	{
        description = L"";
    }

	bundleData->setDescription(description);


	// Parse classpaths
    String classpath = entries->get(Constants::BUNDLE_CLASSPATH);

	P<Array<String>> classPaths = null;

    if (classpath != null) 
	{
        Array<String> theClassPaths =classpath.split(L",");

		int size = theClassPaths.size();
		classPaths = new Array<String>(size);

        for (int i = 0; i < size; i++) 
		{
			String theClassPath =theClassPaths.get(i);

			// Check the classpath entry
			bool entryExists = false;
			
			String theRealPath = generateURL(location, theClassPath);
			File theFile(theRealPath);

			entryExists = theFile.exists();

			if (entryExists) 
			{
				classPaths->set(i, theFile.getCanonicalPath());
			}
			else 
			{
				throw BundleException(String(L"Classpath(\"") + theClassPath + String(L"\") not found: ") + file->getAbsolutePath());
			}
		}
    }
	else 
	{
		classPaths = new Array<String>();
	}

	bundleData->setClassPaths(classPaths);

	// Parse export packages
	String exportPackages = entries->get(Constants::EXPORT_PACKAGE);
	Array<String> exportedPackages;

    if (exportPackages != null) 
	{
         
        exportedPackages =exportPackages.split(L",");
    }
	else 
	{
		exportedPackages = Array<String>();
	}

	bundleData->setExportedPackages(new Array<String>(exportedPackages));

	// Parse import packages, nee
	String importpackages = entries->get(Constants::IMPORT_PACKAGE);
	Array<String> importedPackages;

    if (importpackages != null)
	{
		importedPackages =importpackages.split(L",");
    }
	else 
	{
        importedPackages = Array<String>();
    }

	bundleData->setImportedPackages(new Array<String>(importedPackages));

	// Parse reuqired extensions
	String requiredbundles = entries->get(Constants::REQUIRE_BUNDLE);
	Array<String> requiredBundles;

    if (requiredbundles != null) 
	{
		requiredBundles =requiredbundles.split(L",");
    }
	else 
	{
        requiredBundles =  Array<String>();
    }

	bundleData->setRequiredBundles(new Array<String>(requiredBundles));

	return bundleData;
}
Beispiel #12
0
int
AIShapeImport::DoImport(const TCHAR *filename,ImpInterface *i,Interface *gi, BOOL suppressPrompts) {
	// Get a scale factor from points (the file storage) to our units
	double mScale = GetMasterScale(UNITS_INCHES);
	float scaleFactor = float((1.0 / mScale) / 72.0);
	
	// Set a global prompt display switch
	showPrompts = suppressPrompts ? FALSE : TRUE;

	WorkFile theFile(filename,_T("rb"));

	if(suppressPrompts) {
		}
	else {
		if (!DialogBox(hInstance, MAKEINTRESOURCE(IDD_MERGEORREPL), gi->GetMAXHWnd(), ImportDlgProc))
			return IMPEXP_CANCEL;
		}

	dStream = i->DumpFile();

	if(!(stream = theFile.Stream())) {
		if(showPrompts)
			MessageBox(IDS_TH_ERR_OPENING_FILE, IDS_TH_3DSIMP);
		return 0;						// Didn't open!
		}

	// Got the file -- Now put up the options dialog!
	if(showPrompts) {
		int result = DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_SHAPEIMPORTOPTIONS), gi->GetMAXHWnd(), ShapeImportOptionsDlgProc, (LPARAM)this);
		if(result <= 0)
			return IMPEXP_CANCEL;
		}
	else { // Set default parameters here
		importType = MULTIPLE_SHAPES;
		}

	if (replaceScene) {
		if (!i->NewScene())
			return IMPEXP_CANCEL;
		}

	theShapeImport = this;

	int line,count,status,phase,buflen, reason;
	float x1,y1,x2,y2,x3,y3;
	char buffer[256];

	phase=0;
	count=0;
	line=0;
	gotStuff = FALSE;

	GetDecSymbolFromRegistry();

	loop:
	line++;
	if((status=getaline(stream,buffer,255,0))<0)
		{
		reason = IDS_TH_LINE_TOO_LONG;

		corrupted:
		if(showPrompts)
			MessageBox(reason, IDS_TH_3DSIMP);
		FinishWorkingShape(TRUE, i);
		return gotStuff;
		}

	if(status==0) {
		FinishWorkingShape(TRUE, i);
		return gotStuff;	// EOF
		}

	/* Look for appropriate section of file */

	buflen=static_cast<int>(strlen(buffer));	// SR DCAST64: Downcast to 2G limit.
	switch(phase)
		{
		case 0:	/* Looking for the path */
			buffer[10]=0;
			if(stricmp(buffer,"%%endsetup")==0)
				phase=1;
			break;
		case 1:	/* Loading the path data -- looking for initial 'm' */
			if(buflen<2)
				break;
			if(buffer[buflen-2]==' ' && buffer[buflen-1]=='m') {
				phase=2;
				goto phase2;
				}
			break;
		case 2:
			phase2:
			if(buflen<2)
				break;
			if(buffer[buflen-2]!=' ')
				break;
			switch(buffer[buflen-1]) {
				case 'm': {	/* Moveto */
					FixDecimalSymbol(buffer);
					if(sscanf(buffer,"%f %f",&x1,&y1)!=2) {
	#ifdef DBG1
	DebugPrint("Moveto buffer:%s\n",buffer);
	#endif
						bad_file:
						reason = IDS_TH_INVALIDFILE;
						goto corrupted;
						}
					// If had one working, wrap it up
					FinishWorkingShape(FALSE, i);
					// Start this new spline
					if(!StartWorkingShape()) {
						reason = IDS_TH_NO_RAM;
						goto corrupted;
						}
					Point3 p(x1 * scaleFactor, y1 * scaleFactor, 0.0f);
					SplineKnot k(KTYPE_BEZIER, LTYPE_CURVE, p, p, p);
					spline->AddKnot(k);
					}
					break;
				case 'l':	/* Lineto */
				case 'L': {	/* Lineto corner */
					FixDecimalSymbol(buffer);
					if(sscanf(buffer,"%f %f",&x1,&y1)!=2) {
	#ifdef DBG1
	DebugPrint("Lineto buffer:%s\n",buffer);
	#endif
						goto bad_file;
						}
					Point3 p(x1 * scaleFactor, y1 * scaleFactor, 0.0f);
					SplineKnot k(KTYPE_BEZIER, LTYPE_CURVE, p, p, p);
					spline->AddKnot(k);
					}
					break;
				case 'c':	/* Curveto */
				case 'C': {	/* Curveto corner */
					FixDecimalSymbol(buffer);
					if(sscanf(buffer,"%f %f %f %f %f %f",&x1,&y1,&x2,&y2,&x3,&y3)!=6) {
	#ifdef DBG1
	DebugPrint("Curveto buffer:%s\n",buffer);
	#endif
						goto bad_file;
						}
					int lastKnot = spline->KnotCount() - 1;
					spline->SetOutVec(lastKnot, Point3(x1 * scaleFactor, y1 * scaleFactor, 0.0f));
					Point3 p(x3 * scaleFactor, y3 * scaleFactor, 0.0f);
					Point3 in(x2 * scaleFactor, y2 * scaleFactor, 0.0f);
					SplineKnot k(KTYPE_BEZIER, LTYPE_CURVE, p, in, p);
					spline->AddKnot(k);
					}
					break;
				case 'v':	/* Current/vec */
				case 'V': {	/* Current/vec corner */
					FixDecimalSymbol(buffer);
					if(sscanf(buffer,"%f %f %f %f",&x2,&y2,&x3,&y3)!=4) {
	#ifdef DBG1
	DebugPrint("Current/vec buffer:%s\n",buffer);
	#endif
						goto bad_file;
						}
					Point3 p(x3 * scaleFactor, y3 * scaleFactor, 0.0f);
					Point3 in(x2 * scaleFactor, y2 * scaleFactor, 0.0f);
					SplineKnot k(KTYPE_BEZIER, LTYPE_CURVE, p, in, p);
					spline->AddKnot(k);
					}
					break;
				case 'y':	/* Vec/next */
				case 'Y': {	/* Vec/next corner */
					FixDecimalSymbol(buffer);
					if(sscanf(buffer,"%f %f %f %f",&x1,&y1,&x3,&y3)!=4) {
	#ifdef DBG1
	DebugPrint("vec/next buffer:%s\n",buffer);
	#endif
						goto bad_file;
						}
					int lastKnot = spline->KnotCount() - 1;
					spline->SetOutVec(lastKnot, Point3(x1 * scaleFactor, y1 * scaleFactor, 0.0f));
					Point3 p(x3 * scaleFactor, y3 * scaleFactor, 0.0f);
					SplineKnot k(KTYPE_BEZIER, LTYPE_CURVE, p, p, p);
					spline->AddKnot(k);
					}
					break;
				}
			break;
		}

	count++;
	goto loop;
	}
StageStartingAttributesParser::StageStartingAttributesParser(const char * path){
	xmlFilePath = path;
	rapidxml::xml_document<> doc;
	//open path and read
	std::ifstream theFile (xmlFilePath);
	std::vector<char> buffer = std::vector<char>((std::istreambuf_iterator<char>(theFile)), std::istreambuf_iterator<char>());
	buffer.push_back('\0');
	//parse
	doc.parse<0>( &buffer[0] );

	DNEWPTR( rapidxml::xml_node<>, rootNode);
	rootNode = doc.first_node("StartingSprites");
	DASSERT( rootNode );

	int totealStages = GetGetIntAtrr( rootNode, "totalStages" );
	DASSERT(totealStages>0);

	attributes.resize(totealStages);
	positions.resize(totealStages);

	int stages = 0;
	attributeMap attrMap;
	positionMap posMap;
	for(rapidxml::xml_node<>* stagesIterate = rootNode->first_node(); stagesIterate; stagesIterate = stagesIterate->next_sibling()){
		int currStage = GetGetIntAtrr( stagesIterate, "stageNum" );
		++stages;
		DASSERT( currStage == stages);
		
		attrMap.clear();
		posMap.clear();

		std::list<StartingAttributes_t> charAttrs;
		charAttrs.push_front(getNewAttribute( stagesIterate->first_node("BubXY") ));
		attrMap["BubXY"] = charAttrs;

		charAttrs.clear();
		charAttrs.push_front(getNewAttribute( stagesIterate->first_node("BobXY") ));
		attrMap["BobXY"] = charAttrs;

		charAttrs.clear();
		for(rapidxml::xml_node<>* charAttrsIterate = stagesIterate->first_node("ZenChanXY")->first_node(); charAttrsIterate; charAttrsIterate = charAttrsIterate->next_sibling()){
			charAttrs.push_front(getNewAttribute( charAttrsIterate ));
		}
		attrMap["ZenChanXY"] = charAttrs;

		charAttrs.clear();
		for(rapidxml::xml_node<>* charAttrsIterate = stagesIterate->first_node("MightaXY")->first_node(); charAttrsIterate; charAttrsIterate = charAttrsIterate->next_sibling()){
			charAttrs.push_front(getNewAttribute( charAttrsIterate ));
		}
		attrMap["MightaXY"] = charAttrs;

		charAttrs.clear();
		for(rapidxml::xml_node<>* charAttrsIterate = stagesIterate->first_node("PowerUpXY")->first_node(); charAttrsIterate; charAttrsIterate = charAttrsIterate->next_sibling()){
			charAttrs.push_front(getNewAttribute( charAttrsIterate ));
		}
		attrMap["PowerUpXY"] = charAttrs;
		
		std::list<StartingPosition_t> charPoss;
		for(rapidxml::xml_node<>* charAttrsIterate = stagesIterate->first_node("BubbleDrivers")->first_node(); charAttrsIterate; charAttrsIterate = charAttrsIterate->next_sibling()){
			charPoss.push_front( getNewPosition(charAttrsIterate) );
		}
		
		posMap["BubbleDrivers"] = charPoss;

		attributes[stages-1] = attrMap;
		positions[stages-1] = posMap;
	}
}
Beispiel #14
0
void QWzmViewer::actionOpen()
{
	static QString lastDir; // Convenience HACK to remember last succesful directory a model was loaded from.
	filename = QFileDialog::getOpenFileName(this, tr("Choose a PIE or WZM file"), lastDir, tr("All Compatible (*.wzm *.pie);;WZM models (*.wzm);;PIE models (*.pie)"));
	if (!filename.isEmpty())
	{
		QFileInfo theFile(filename);
		MODEL *tmpModel = NULL;

		if (theFile.completeSuffix().compare(QString("wzm"), Qt::CaseInsensitive) == 0)
		{
			tmpModel = readModel(filename.toAscii().constData(), 0);
		}
		else if (theFile.completeSuffix().compare(QString("pie"), Qt::CaseInsensitive) == 0)
		{
			tmpModel = loadPIE(filename);
		}
		else
		{
			return;
		}

		if (tmpModel)
		{

			QFileInfo texPath(theFile.absoluteDir(), tmpModel->texPath);

			// Try to find texture automatically
			if (!texPath.exists())
			{
				texPath.setFile(QString("../../data/base/texpages/"), tmpModel->texPath);
				if (!texPath.exists())
				{
					texPath.setFile(QFileDialog::getExistingDirectory(this, tr("Specify texture directory"), QString::null), tmpModel->texPath);
					if (!texPath.exists())
					{
						QMessageBox::warning(this, tr("Oops..."), "Could not find texture", QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton);
						freeModel(tmpModel);
						return;
					}
				}
			}
			if (psModel)
			{
				freeModel(psModel);
			}
			psModel = tmpModel;
			setModel(texPath);
			ui->actionSave->setEnabled(true);
			lastDir = theFile.absolutePath();
			fileNameLabel->setText(theFile.fileName());
			fileNameLabel->setToolTip(filename);
		}
		else
		{
			qWarning("Failed to create model!");

			ui->statusBar->showMessage(tr("Failed to create model!"), 3000);
		}
	}
}
Beispiel #15
0
int NECOutputParser(NECOutput * theNECOutput, QString theFileName)
{
  //NEC's outputs seem to be written with the C locale
  QLocale::setDefault(QLocale::C);
  QFile theFile(theFileName);

  //RadiationPattern * nullRP;
  //nullRP = new RadiationPattern(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0, 0.0, 0.0, 0.0, 0.0);

  //Let's check that the file exists
  if ( !theFile.exists() )
  {
    //The file does not exists
    qDebug("NEC output parser - The file does not exist\n");
    return 1;
  }
  //The file exists, but can we read it?
  if (!theFile.open(QIODevice::ReadOnly | QIODevice::Text))
  {
    //We can not read the file
    qDebug("NEC output parser - I can not read the file\n");
    return 1;
  }

  //We generate the stream from the file
  QTextStream text(&theFile);
  //And we need some extra variables
  QString line;
  QStringList dataList;
  QString elDato;
  int sense = 0;

  //We opened the file, but is it empty?
  if(text.atEnd())
  {
    qDebug("The file is empty\n");
    return 1;
  }

  line = "";

  /*
    We search for the beggining of the radiation patterns
    The headers of the radiation patterns of nec2 and nec2++ differ
    in the seventh word, so I include both of them.
  */
  while((!text.atEnd()) &&
        (line != "DEGREES DEGREES DB DB DB RATIO DEG. VOLTS/M DEGREES VOLTS/M DEGREES") &&
        (line != "DEGREES DEGREES DB DB DB RATIO DEGREES VOLTS/M DEGREES VOLTS/M DEGREES")
      &&(!line.contains("GEOMETRY DATA CARD ERROR")) )
  {
    //We read a single line
    line = text.readLine();
    line = line.simplified();
  }

  if (line.contains("GEOMETRY DATA CARD ERROR"))
  {
    qDebug("Geometry data card error\n");
    return 1;
  }
  else if (text.atEnd())
  {
    qDebug("Radiation pattern data from nec2++ is missing\n");
    return 1;
  }
  else
  {

    RadiationPattern * newRP;

    //We scan the radiation patterns for data
    line = text.readLine();
    // We now check which kind of alignment we have
    sense = cleanRadiationPatternLine(line,dataList);

    // And now we check that we didn't have any errors
    if( sense == -1 )
      return 1;

    /*
      We scan the data until Theta <= 180, because all the rest of the data
      is redundant.
      For making the plotting of the surface much easier, we will need an
      extra set of data {(Theta == 180) == (Theta == 0) }. If we don't have
      Theta == 180, we will make one more iteration, which is considered
      below.
    */

    bool exists180 = false;

    while(!text.atEnd() && line !="" && dataList.at(1).toDouble()<=180.0)
    {
      if(sense != 3)
      {
        newRP = new RadiationPattern(dataList.at(0).toDouble(),
                    dataList.at(1).toDouble(),
                    dataList.at(2).toDouble(), dataList.at(3).toDouble(),
                    dataList.at(4).toDouble(), dataList.at(5).toDouble(),
                    dataList.at(6).toDouble(), sense,
                    dataList.at(8).toDouble(), dataList.at(9).toDouble(),
                    dataList.at(10).toDouble(), dataList.at(11).toDouble());
      }
      else
      {
        // We don't have a Sense field
        newRP = new RadiationPattern(dataList.at(0).toDouble(),
                    dataList.at(1).toDouble(),
                    dataList.at(2).toDouble(), dataList.at(3).toDouble(),
                    dataList.at(4).toDouble(), dataList.at(5).toDouble(),
                    dataList.at(6).toDouble(), sense,
                    dataList.at(7).toDouble(), dataList.at(8).toDouble(),
                    dataList.at(9).toDouble(), dataList.at(10).toDouble());
      }
      theNECOutput->setRadiationPattern(newRP);
      line = text.readLine();
      // We now check which kind of alignment we have
      if(line != "")
        sense = cleanRadiationPatternLine(line,dataList);
      // And now we check that we didn't have any errors
      if( sense == -1 )
        return 1;
      // Check if we have theta == 180
      if(dataList.at(1).toDouble() == 180.0)
        exists180 = true;
    }

    /*
      Now we must take into account the case in which we don't have
      Theta == 180 but a bigger number.
      Take into account that now Theta can't be less than 180.
    */
    double stop = 0.0;
    if(!exists180)
      stop = dataList.at(1).toDouble();
      while(!text.atEnd() && line !="" && dataList.at(1).toDouble()==stop)
      {
        if(sense != 3)
        {
          newRP = new RadiationPattern(dataList.at(0).toDouble(),
                      dataList.at(1).toDouble(),
                      dataList.at(2).toDouble(), dataList.at(3).toDouble(),
                      dataList.at(4).toDouble(), dataList.at(5).toDouble(),
                      dataList.at(6).toDouble(), sense,
                      dataList.at(8).toDouble(), dataList.at(9).toDouble(),
                      dataList.at(10).toDouble(), dataList.at(11).toDouble());
        }
        else
        {
          // We don't have a Sense field
          newRP = new RadiationPattern(dataList.at(0).toDouble(),
                      dataList.at(1).toDouble(),
                      dataList.at(2).toDouble(), dataList.at(3).toDouble(),
                      dataList.at(4).toDouble(), dataList.at(5).toDouble(),
                      dataList.at(6).toDouble(), sense,
                      dataList.at(7).toDouble(), dataList.at(8).toDouble(),
                      dataList.at(9).toDouble(), dataList.at(10).toDouble());
        }
        theNECOutput->setRadiationPattern(newRP);
        line = text.readLine();
        // We now check which kind of alignment we have
        if(line != "")
          sense = cleanRadiationPatternLine(line,dataList);
        // And now we check that we didn't have any errors
        if( sense == -1 )
          return 1;
    }

  }

  //All that has been opened must be closed before leaving
  theFile.close();
  return 0;
}// ParserNecOutput
Beispiel #16
0
bool BmpFile::loadData(std::string * fileName)
{
	std::ifstream theFile(fileName->c_str(), std::ios::binary);
	this->fileName = * fileName;
	if (!theFile.good())
	{
		std::cout << "Couldn't file the file\n";
		return false;
	}
	
	theFile.read(reinterpret_cast<char *>(&magicNum), sizeof(magicNumber));
	theFile.read(reinterpret_cast<char *>(&head), sizeof(fileHeader));
	theFile.read(reinterpret_cast<char *>(&info), sizeof(infoHeader));
	// now to pass the file stream to an appropiate loading function
	printFileStats();
	width = info.width;
	height = info.height;
	bitsPerPixel = info.bitsPerPixel;
	bytesPerPixel = bitsPerPixel / 8;
	// rember it's bgr not rgb!
	std::cout << "After reading in the headers the reader is " << theFile.tellg() << " bytes in.\n The offset for the start of the imaeg data is: " << head.bmpOffset << " bytes in.\n";  
	theFile.seekg(head.bmpOffset); // move to reader to the start of image data
	std::cout << "After moving the reader, its at " << theFile.tellg() << " bytes in.\n";  

	std::cout << "This is a " << info.bitsPerPixel << " bit bitmap file\n";
	

	if (info.bitsPerPixel == 8) 
	{
		std::cout << "This is a 8 bit bitmap image, ony 24 bit and 32 bit will be supported\n";
		return false;
	}
	else if(info.bitsPerPixel == 16) 
	{
		std::cout << "This is a 16 bit bitmap image, ony 24 bit and 32 bit will be supported\n";
		return false;
	}
	else if (info.bitsPerPixel == 24) // 24 bit colour
	{
		if (info.compressionType == BMP_RGB) // uncompressed
		{
			return loadUncompressed24Bit(&theFile);
		}
		else if (info.compressionType == BMP_RLE4) // 4 bit rle commands
		{
			std::cout << "The file uses 4 bit RLE compression which is unsupported.\n";
			return false;
		}
		else if (info.compressionType == BMP_RLE8) // 8 bit rle commands
		{
			std::cout << "The file uses 4 bit RLE compression.\n";
		}
		else if (info.compressionType == BMP_BITFIELDS)
		{
			std::cout << "The file uses bitfields compression which is unsupported.\n";
			return false;
		}
		else if (info.compressionType == BMP_JPEG)
		{
			std::cout << "The file uses jpeg compression which is unsupported.\n";
			return false;
		}
		else if (info.compressionType == BMP_PNG)
		{
			std::cout << "The file uses png compression which is unsupported.\n";
			return false;
		}
		else if (info.compressionType == BMP_ALPHABITFIELDS)
		{
			std::cout << "The file uses alpha bit fields compression which is unsupported.\n";
			return false;
		}
		else
		{
			std::cout << "The file uses unknown compression which is unsupported.\n";
			return false;
		}
		
	}
	else if(info.bitsPerPixel == 32) // 32 bit colour
	{
		if (info.compressionType == BMP_RGB) // uncompressed
		{
			return loadUncompressed32Bit(&theFile);
		}
		else if (info.compressionType == BMP_RLE4) // 4 bit rle commands
		{
			std::cout << "The file uses 4 bit RLE compression which is unsupported.\n";
			return false;
		}
		else if (info.compressionType == BMP_RLE8) // 8 bit rle commands
		{
			std::cout << "The file uses 4 bit RLE compression.\n";
		}
		else if (info.compressionType == BMP_BITFIELDS)
		{
			std::cout << "The file uses bitfields compression which is unsupported.\n";
			return false;
		}
		else if (info.compressionType == BMP_JPEG)
		{
			std::cout << "The file uses jpeg compression which is unsupported.\n";
			return false;
		}
		else if (info.compressionType == BMP_PNG)
		{
			std::cout << "The file uses png compression which is unsupported.\n";
			return false;
		}
		else if (info.compressionType == BMP_ALPHABITFIELDS)
		{
			std::cout << "The file uses alpha bit fields compression which is unsupported.\n";
			return false;
		}
		else
		{
			std::cout << "The file uses unknown compression which is unsupported.\n";
			return false;
		}
	}

	theFile.close();
	return true;
}