コード例 #1
0
ファイル: umaxfind.cpp プロジェクト: DimondTheCat/xray
void UMaxFind::StartFileFinder()
{
	TCHAR				szExeFile[_MAX_PATH];
	TSTR				szPath;
	PROCESS_INFORMATION	process;
	STARTUPINFO			si;
	BOOL				res;

	memset(&si, 0, sizeof(STARTUPINFO));
	si.cb = sizeof(STARTUPINFO);
	si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
	si.wShowWindow = SW_SHOWDEFAULT;
	si.hStdError = NULL;


	GetModuleFileName(NULL, szExeFile, _MAX_PATH);
	SplitFilename(TSTR(szExeFile), &szPath, NULL, NULL);
	szPath = szPath+GetString(IDS_EXE_FILENAME);	

	res = CreateProcess(NULL, szPath, NULL, NULL, FALSE, 0, NULL, NULL, &si, &process);
	if (!res) {
		// Error
		TSTR msg = GetString(IDS_ERROR);
		MessageBox(hPanel, GetString(IDS_NOEXE), msg, MB_OK | MB_ICONEXCLAMATION);
		return;
		}

	CloseHandle(process.hThread);
}
コード例 #2
0
ファイル: GenethonDoc.cpp プロジェクト: karlnicholas/GeneThon
PyObject*  CGenethonDoc::setPythonPath(CString& fileName) {
    CString filePath;
    CString appName;
    SplitFilename(fileName, &filePath, &appName);

    PyObject* sysPath = PySys_GetObject("path");
    PyObject* pyPath = PyUnicode_FromString(filePath);
    PyList_Append(sysPath, pyPath);
    Py_DECREF(pyPath);
    pyPath = PyUnicode_FromString("c:/users/karl/Anaconda3");
    PyList_Append(sysPath, pyPath);
    Py_DECREF(pyPath);
    pyPath = PyUnicode_FromString("c:/users/karl/Anaconda3/Lib");
    PyList_Append(sysPath, pyPath);
    Py_DECREF(pyPath);
    pyPath = PyUnicode_FromString("c:/users/karl/Anaconda3/Dlls");
    PyList_Append(sysPath, pyPath);
    Py_DECREF(pyPath);
    pyPath = PyUnicode_FromString("c:/users/karl/Anaconda3/Lib/site-packages");
    PyList_Append(sysPath, pyPath);
    Py_DECREF(pyPath);

    PyObject*pName = PyUnicode_DecodeFSDefault(appName);
    PyObject*pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    return pModule;
}
コード例 #3
0
 // ----------------------------------------------------------------------------------------------------------------------------------------------
 void SplitFullFilename(	const std::string& qualifiedName,
                                    std::string& outBasename, std::string& outExtention, std::string& outPath )
 {
     std::string fullName;
     SplitFilename( qualifiedName, fullName, outPath );
     SplitBaseFilename( fullName, outBasename, outExtention );
 }
コード例 #4
0
rapp_platform_ros_communications::ontologyLoadDumpSrv::Response KnowrobWrapper::dumpOntologyQuery(rapp_platform_ros_communications::ontologyLoadDumpSrv::Request req)
{
  rapp_platform_ros_communications::ontologyLoadDumpSrv::Response res;

  std::string path = getenv("HOME");
  path=path+std::string("/rapp_platform_files/");

  if(req.file_url.empty())   // || req.file_url==std::string("")
  {
    res.success=false;
    res.trace.push_back(std::string("Empty file path"));
    res.trace.push_back(req.file_url);
    res.error=std::string("Empty file path");
    return res;
  }
  size_t pathDepth = std::count(req.file_url.begin(), req.file_url.end(), '/');
  std::string str2 ("/");
  std::size_t found = req.file_url.find(str2);
  if (found!=std::string::npos && pathDepth>1)
  {
    std::string folderFromPath=SplitFilename(req.file_url);
    const char * c = folderFromPath.c_str();
    if(!checkIfFileExists(c))
    {
      res.success=false;
      res.trace.push_back(std::string("Path does not exist, invalid folder?"));
      res.trace.push_back(req.file_url);
      res.error=std::string("Path does not exist, invalid folder?");
      return res;
    }
  }



  req.file_url=path+req.file_url;


  std::string query = std::string("rdf_save('") + req.file_url + std::string("')");
  json_prolog::PrologQueryProxy results = pl.query(query.c_str());


  char status = results.getStatus();
  if(status==0)
  {
    res.success=false;
    //std_msgs::String temp_std_msgs_string;
    //temp_std_msgs_string.data=std::string("Ontology dump failed");
    res.trace.push_back(std::string("Ontology dump failed"));
    res.error=std::string("Ontology dump failed");
    return res;
  }
  else if(status==3)
  {
    res.success=true;
  }
  return res;


}
コード例 #5
0
ファイル: surf.cpp プロジェクト: wheam/pai
bool SURFFeatureManager::LoadFeatureSet() {
  DIR *dir = opendir(kDataFolder);
  struct dirent *dir_ent = NULL;
  char folder[64];
  char filepath[128];
  while ((dir_ent = readdir(dir)) != NULL) {
    if (strcmp(".", dir_ent->d_name) == 0 ||
        strcmp("..", dir_ent->d_name) == 0) continue;
    sprintf(folder, "%s/%s", kDataFolder, dir_ent->d_name);
    printf("In folder %s\n", folder);
    DIR *category_dir = opendir(folder);
    struct dirent *file_ent = NULL;
    while ((file_ent = readdir(category_dir)) != NULL) {
      if (strcmp(".", file_ent->d_name) == 0 ||
          strcmp("..", file_ent->d_name) == 0) continue;
      sprintf(filepath, "%s/%s", folder, file_ent->d_name);
      std::vector<std::string> arr;
      SplitFilename(file_ent->d_name, &arr);
      cv::FileStorage fs(filepath, cv::FileStorage::READ);
      SURFFeature *feature = new SURFFeature;
      fs["D"] >> feature->descriptor;
      fs["I"] >> feature->image;
      cv::FileNode roi_node = fs["R"];
      feature->roi.x = roi_node["x"];
      feature->roi.y = roi_node["y"];
      feature->roi.width = roi_node["width"];
      feature->roi.height = roi_node["height"];
      cv::FileNode kp_node = fs["K"];
      for (cv::FileNodeIterator fit = kp_node.begin();
           fit != kp_node.end();
           ++fit) {
        cv::FileNode kp = *fit;
        cv::KeyPoint point;
        point.pt.x = kp["x"];
        point.pt.y = kp["y"];
        point.size = kp["size"];
        point.angle = kp["angle"];
        point.octave = kp["octave"];
        point.response = kp["response"];
        point.class_id = kp["class_id"];
        feature->key_points.push_back(point);
        int media_type = atoi(dir_ent->d_name);
        FeatureMap::iterator it;
        if ((it = feature_map_.find(media_type)) == feature_map_.end()) {
          feature_map_.insert(make_pair(media_type,
                                        std::map<std::string, SURFFeature*>()));
        } else {
          it->second.insert(make_pair(arr[1], feature));
        }
      }
    }
  }
  for (FeatureMap::iterator it = feature_map_.begin();
       it != feature_map_.end();
       ++it) {
    printf("%d: %lu\n", it->first, it->second.size());
  }
  return true;
}
コード例 #6
0
ファイル: colclip.cpp プロジェクト: artemeliy/inf4715
void SetupTitle(HWND hWnd,TSTR &name)
   {
   TSTR fl, ext;
   SplitFilename(name,NULL,&fl,&ext);
   fl = TSTR(GetString(IDS_RB_COLORCLIPSHORT)) + 
      TSTR(_T(" - ")) + fl + ext;
   SetWindowText(hWnd,fl);
   }
コード例 #7
0
ファイル: HexMergeDoc.cpp プロジェクト: seanedwards/COS-420
/**
 * @brief Update document filenames to title
 */
void CHexMergeDoc::SetTitle(LPCTSTR lpszTitle)
{
	const TCHAR pszSeparator[] = _T(" - ");
	String sTitle;

	if (lpszTitle)
		sTitle = lpszTitle;
	else
	{
		if (!m_strDesc[0].empty())
			sTitle += m_strDesc[0];
		else
		{
			String file;
			String ext;
			SplitFilename(m_filePaths.GetLeft().c_str(), NULL, &file, &ext);
			sTitle += file.c_str();
			if (!ext.empty())
			{
				sTitle += _T(".");
				sTitle += ext.c_str();
			}
		}

		sTitle += pszSeparator;

		if (!m_strDesc[1].empty())
			sTitle += m_strDesc[1];
		else
		{
			String file;
			String ext;
			SplitFilename(m_filePaths.GetRight().c_str(), NULL, &file, &ext);
			sTitle += file.c_str();
			if (!ext.empty())
			{
				sTitle += _T(".");
				sTitle += ext.c_str();
			}
		}
	}
	CDocument::SetTitle(sTitle.c_str());
}
コード例 #8
0
ファイル: foo-lastslash.cpp プロジェクト: DaveAckley/ULAM
int main ()
{
  std::string str1 ("/usr/bin/man");
  std::string str2 ("c:\\windows\\winhelp.exe");
  std::string str3 ("woman");
  std::string str4 ("/hello");

  SplitFilename (str1);
  std::cout << " newfile " << str1 << '\n';

  SplitFilename (str2);
  std::cout << " newfile " << str2 << '\n';

  SplitFilename (str3);
  std::cout << " newfile " << str3 << '\n';

  SplitFilename (str4);
  std::cout << " newfile " << str4 << '\n';

  return 0;
}
コード例 #9
0
/**
 * @brief Install new filter.
 * This function is called when user selects "Install" button from GUI.
 * Function allows easy installation of new filters for user. For example
 * when user has downloaded filter file from net. First we ask user to
 * select filter to install. Then we copy selected filter to private
 * filters folder.
 */
void FileFiltersDlg::OnBnClickedFilterfileInstall()
{
    CString s;
    String path;
    String userPath = theApp.m_globalFileFilter.GetUserFilterPathWithCreate();

    if (SelectFile(GetSafeHwnd(), s, path.c_str(), IDS_FILEFILTER_INSTALL, IDS_FILEFILTER_FILEMASK,
                   TRUE))
    {
        String sfile, sext;
        SplitFilename(s, NULL, &sfile, &sext);
        String filename = sfile;
        filename += _T(".");
        filename += sext;
        userPath = paths_ConcatPath(userPath, filename);
        if (!CopyFile(s, userPath.c_str(), TRUE))
        {
            // If file already exists, ask from user
            // If user wants to, overwrite existing filter
            if (paths_DoesPathExist(userPath.c_str()) == IS_EXISTING_FILE)
            {
                int res = LangMessageBox(IDS_FILEFILTER_OVERWRITE, MB_YESNO |
                                         MB_ICONWARNING);
                if (res == IDYES)
                {
                    if (!CopyFile(s, userPath.c_str(), FALSE))
                    {
                        LangMessageBox(IDS_FILEFILTER_INSTALLFAIL, MB_ICONSTOP);
                    }
                }
            }
            else
            {
                LangMessageBox(IDS_FILEFILTER_INSTALLFAIL, MB_ICONSTOP);
            }
        }
        else
        {
            FileFilterMgr *pMgr = theApp.m_globalFileFilter.GetManager();
            pMgr->AddFilter(userPath.c_str());

            // Remove all from filterslist and re-add so we can update UI
            CString selected;
            m_Filters->RemoveAll();
            theApp.m_globalFileFilter.GetFileFilters(m_Filters, selected);

            UpdateFiltersList();
        }
    }
}
コード例 #10
0
ファイル: cpl_vsil_tar.cpp プロジェクト: sylvainallard/gdal
VSIVirtualHandle* VSITarFilesystemHandler::Open( const char *pszFilename, 
                                                 const char *pszAccess)
{
    char* tarFilename;
    CPLString osTarInFileName;

    if (strchr(pszAccess, 'w') != NULL ||
        strchr(pszAccess, '+') != NULL)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
                 "Only read-only mode is supported for /vsitar");
        return NULL;
    }

    tarFilename = SplitFilename(pszFilename, osTarInFileName, TRUE);
    if (tarFilename == NULL)
        return NULL;

    VSIArchiveReader* poReader = OpenArchiveFile(tarFilename, osTarInFileName);
    if (poReader == NULL)
    {
        CPLFree(tarFilename);
        return NULL;
    }

    CPLString osSubFileName("/vsisubfile/");
    VSITarEntryFileOffset* pOffset = (VSITarEntryFileOffset*) poReader->GetFileOffset();
    osSubFileName += CPLString().Printf(CPL_FRMT_GUIB, pOffset->nOffset);
    osSubFileName += "_";
    osSubFileName += CPLString().Printf(CPL_FRMT_GUIB, poReader->GetFileSize());
    osSubFileName += ",";
    delete pOffset;
    
    if (VSIIsTGZ(tarFilename))
    {
        osSubFileName += "/vsigzip/";
        osSubFileName += tarFilename;
    }
    else
        osSubFileName += tarFilename;

    delete(poReader);

    CPLFree(tarFilename);
    tarFilename = NULL;

    return (VSIVirtualHandle* )VSIFOpenL(osSubFileName, "rb");
}
コード例 #11
0
ファイル: CubeMap.cpp プロジェクト: 2asoft/xray
void CubeMap::UpdateButtonText()
{
	IAutoMParamDlg *dlg = pblock->GetMParamDlg();
	IParamMap2 *map = dlg->GetMap();
	if(map)
	{
		TSTR p,f,e,name;
		
		ParamDef &mapdef = pblock->GetParamDef(pb_cubemapfile);	//Added to force a filename to be present	
		mapdef.init_file = cubeMapFile;					//Added to force a filename to be present
		SplitFilename(cubeMapFile, &p, &f, &e);
		name = f+e;
		map->SetText(pb_cubemapfile, name.data());

	}
}
コード例 #12
0
ファイル: sound.cpp プロジェクト: 2asoft/xray
BOOL GetSoundFileName(HWND hWnd,TSTR &name,TSTR &dir)
	{
#ifndef INTERIM_64_BIT	// CCJ
	OPENFILENAME ofn;	
	char filter[256];

	AVIBuildFilter(filter,sizeof(filter),FALSE);

	ofn.lStructSize       = sizeof(OPENFILENAME);
	ofn.hwndOwner         = hWnd;
	ofn.hInstance         = NULL;	
	ofn.lpstrTitle        = GetResString(IDS_RB_OPENSOUND);
	ofn.lpstrFilter       = filter;
	ofn.lpstrCustomFilter = NULL;
	ofn.nMaxCustFilter    = 0;
	ofn.nFilterIndex      = 0;
	ofn.lpstrFile         = fileName;
	ofn.nMaxFile          = sizeof(fileName);
	ofn.lpstrFileTitle    = NULL;
	ofn.nMaxFileTitle     = 0;
	ofn.lpstrInitialDir   = dir;
	ofn.Flags             = OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST|OFN_HIDEREADONLY;
	ofn.nFileOffset       = 0;
	ofn.nFileExtension    = 0;
	ofn.lpstrDefExt       = NULL;
	ofn.lCustData         = 0;
	ofn.lpfnHook          = NULL;
	ofn.lpTemplateName    = NULL;

	if (GetOpenFileNamePreview(&ofn)) {
		name = fileName;
		SplitFilename(name,&dir,NULL,NULL);
		return TRUE;
	} else {
		return FALSE;
		}
#else	// INTERIM_64_BIT
	return FALSE;
#endif	// INTERIM_64_BIT
	}
コード例 #13
0
ファイル: global_idx_merge.c プロジェクト: sci-visus/PIDX
int file_initialize_time_step(int current_time_step, char* file_name, char* file_template)
{
  int N;
  char dirname[PIDX_FILE_PATH_LENGTH], basename[PIDX_FILE_PATH_LENGTH];
  int nbits_blocknumber;
  char *directory_path;
  char *data_set_path;

  data_set_path = malloc(sizeof(*data_set_path) * PIDX_FILE_PATH_LENGTH);
  memset(data_set_path, 0, sizeof(*data_set_path) * PIDX_FILE_PATH_LENGTH);

  directory_path = malloc(sizeof(*directory_path) * PIDX_FILE_PATH_LENGTH);
  memset(directory_path, 0, sizeof(*directory_path) * PIDX_FILE_PATH_LENGTH);

  strncpy(directory_path, file_name, strlen(file_name) - 4);

  char time_template[512];
  sprintf(time_template, "%%s/%s.idx", file->idx->filename_time_template);
  sprintf(data_set_path, time_template, directory_path, current_time_step);
  free(directory_path);

  nbits_blocknumber = (maxh - bits_per_block - 1);
  SplitFilename(data_set_path, dirname, basename);

  //remove suffix
  for (N = strlen(basename) - 1; N >= 0; N--)
  {
    int ch = basename[N];
    basename[N] = 0;
    if (ch == '.') break;
  }

#if 0
  //if i put . as the first character, if I move files VisusOpen can do path remapping
  sprintf(file_template, "./%s", basename);
#endif
  //pidx does not do path remapping
  strcpy(file_template, data_set_path);
  for (N = strlen(file_template) - 1; N >= 0; N--)
  {
    int ch = file_template[N];
    file_template[N] = 0;
    if (ch == '.') break;
  }

  //can happen if I have only only one block
  if (nbits_blocknumber == 0)
    strcat(file_template, "/%01x.bin");

  else
  {
    //approximate to 4 bits
    if (nbits_blocknumber % 4)
    {
      nbits_blocknumber += (4 - (nbits_blocknumber % 4));
      //assert(!(nbits_blocknumber % 4));
    }
    if (nbits_blocknumber <= 8)
      strcat(file_template, "/%02x.bin"); //no directories, 256 files
    else if (nbits_blocknumber <= 12)
      strcat(file_template, "/%03x.bin"); //no directories, 4096 files
    else if (nbits_blocknumber <= 16)
      strcat(file_template, "/%04x.bin"); //no directories, 65536  files
    else
    {
      while (nbits_blocknumber > 16)
      {
        strcat(file_template, "/%02x"); //256 subdirectories
        nbits_blocknumber -= 8;
      }
      strcat(file_template, "/%04x.bin"); //max 65536  files
      nbits_blocknumber -= 16;
      //assert(nbits_blocknumber <= 0);
    }
  }

  free(data_set_path);
  return 0;
}
コード例 #14
0
/** 
 * @brief Shows file/folder selection dialog.
 *
 * We need this custom function so we can select files and folders with the
 * same dialog.
 * - If existing filename is selected return it
 * - If filename in (CFileDialog) editbox and current folder doesn't form
 * a valid path to file, return current folder.
 * @param [in] parent Handle to parent window. Can be a NULL, but then
 *     CMainFrame is used which can cause modality problems.
 * @param [out] path Selected folder/filename
 * @param [in] initialPath Initial file or folder shown/selected.
 * @return TRUE if user choosed a file/folder, FALSE if user canceled dialog.
 */
BOOL SelectFileOrFolder(HWND parent, CString& path, LPCTSTR initialPath /*=NULL*/)
{
	String title = theApp.LoadString(IDS_OPEN_TITLE);

	// This will tell common file dialog what to show
	// and also this will hold its return value
	CString sSelectedFile;

	// check if specified path is a file
	if (initialPath && initialPath[0])
	{
		// If initial path info includes a file
		// we put the bare filename into sSelectedFile
		// so the common file dialog will start up with that file selected
		if (paths_DoesPathExist(initialPath) == IS_EXISTING_FILE)
		{
			String temp;
			SplitFilename(initialPath, 0, &temp, 0);
			sSelectedFile = temp.c_str();
		}
	}

	if (parent == NULL)
		parent = AfxGetMainWnd()->GetSafeHwnd();

	int filterid = IDS_ALLFILES;

	if (!filterid)
		filterid = IDS_ALLFILES;

	String filters = theApp.LoadString(filterid);

	// Convert extension mask from MFC style separators ('|')
	//  to Win32 style separators ('\0')
	LPTSTR filtersStr = &*filters.begin();
	ConvertFilter(filtersStr);

	String dirSelTag = theApp.LoadString(IDS_DIRSEL_TAG);

	// Set initial filename to folder selection tag
	dirSelTag += _T("."); // Treat it as filename
	sSelectedFile = dirSelTag.c_str(); // What is assignment above good for?

	OPENFILENAME_NT4 ofn;
	memset(&ofn, 0, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
	ofn.hwndOwner = parent;
	ofn.lpstrFilter = filtersStr;
	ofn.lpstrCustomFilter = NULL;
	ofn.nFilterIndex = 1;
	ofn.lpstrFile = sSelectedFile.GetBuffer(MAX_PATH);
	ofn.nMaxFile = MAX_PATH;
	ofn.lpstrInitialDir = initialPath;
	ofn.lpstrTitle = title.c_str();
	ofn.lpstrFileTitle = NULL;
	ofn.Flags = OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_NOTESTFILECREATE;

	BOOL bRetVal = GetOpenFileName((OPENFILENAME *)&ofn);
	// common file dialog populated sSelectedFile variable's buffer
	sSelectedFile.ReleaseBuffer();
	SetCurrentDirectory(env_GetWindowsDirectory().c_str()); // Free handle held by GetOpenFileName

	if (bRetVal)
	{
		path = sSelectedFile;
		struct _stati64 statBuffer;
		int nRetVal = _tstati64(path, &statBuffer);
		if (nRetVal == -1)
		{
			// We have a valid folder name, but propably garbage as a filename.
			// Return folder name
			String folder = GetPathOnly(sSelectedFile);
			path.Format(_T("%s\\"), folder.c_str());
		}
	}
	return bRetVal;
}
コード例 #15
0
ファイル: DirCmpReport.cpp プロジェクト: seanedwards/COS-420
/**
 * @brief Generate report and save it to file.
 * @param [out] errStr Empty if succeeded, otherwise contains error message.
 * @return TRUE if report was created, FALSE if user canceled report.
 */
BOOL DirCmpReport::GenerateReport(String &errStr)
{
	ASSERT(m_pList != NULL);
	ASSERT(m_pFile == NULL);
	BOOL bRet = FALSE;

	DirCmpReportDlg dlg;
	if (dlg.DoModal() == IDOK) try
	{
		WaitStatusCursor waitstatus(IDS_STATUS_CREATEREPORT);
		if (dlg.m_bCopyToClipboard)
		{
			if (!CWnd::GetSafeOwner()->OpenClipboard())
				return FALSE;
			if (!EmptyClipboard())
				return FALSE;
			CSharedFile file(GMEM_DDESHARE|GMEM_MOVEABLE|GMEM_ZEROINIT);
			m_pFile = &file;
			GenerateReport(dlg.m_nReportType);
			SetClipboardData(CF_TEXT, file.Detach());
			// If report type is HTML, render CF_HTML format as well
			if (dlg.m_nReportType == REPORT_TYPE_SIMPLEHTML)
			{
				// Reconstruct the CSharedFile object
				file.~CSharedFile();
				file.CSharedFile::CSharedFile(GMEM_DDESHARE|GMEM_MOVEABLE|GMEM_ZEROINIT);
				// Write preliminary CF_HTML header with all offsets zero
				static const char header[] =
					"Version:0.9\n"
					"StartHTML:%09d\n"
					"EndHTML:%09d\n"
					"StartFragment:%09d\n"
					"EndFragment:%09d\n";
				static const char start[] = "<html><body>\n<!--StartFragment -->";
				static const char end[] = "\n<!--EndFragment -->\n</body>\n</html>\n";
				char buffer[256];
				int cbHeader = wsprintfA(buffer, header, 0, 0, 0, 0);
				file.Write(buffer, cbHeader);
				file.Write(start, sizeof start - 1);
				GenerateHTMLHeaderBodyPortion();
				GenerateXmlHtmlContent(false);
				file.Write(end, sizeof end); // include terminating zero
				DWORD size = GetLength32(file);
				// Rewrite CF_HTML header with valid offsets
				file.SeekToBegin();
				wsprintfA(buffer, header, cbHeader, size - 1,
					cbHeader + sizeof start - 1, size - sizeof end + 1);
				file.Write(buffer, cbHeader);
				SetClipboardData(CF_HTML, GlobalReAlloc(file.Detach(), size, 0));
			}
			CloseClipboard();
		}
		if (!dlg.m_sReportFile.IsEmpty())
		{
			String path;
			SplitFilename(dlg.m_sReportFile, &path, NULL, NULL);
			if (!paths_CreateIfNeeded(path.c_str()))
			{
				errStr = LoadResString(IDS_FOLDER_NOTEXIST);
				return FALSE;
			}
			CFile file(dlg.m_sReportFile,
				CFile::modeWrite|CFile::modeCreate|CFile::shareDenyWrite);
			m_pFile = &file;
			GenerateReport(dlg.m_nReportType);
		}
		bRet = TRUE;
	}
	catch (CException *e)
	{
		e->ReportError(MB_ICONSTOP);
		e->Delete();
	}
	m_pFile = NULL;
	return bRet;
}
コード例 #16
0
/**
 * @brief Helper function for selecting folder or file.
 * This function shows standard Windows file selection dialog for selecting
 * file or folder to open or file to save. The last parameter @p is_open selects
 * between open or save modes. Biggest difference is that in save-mode Windows
 * asks if user wants to override existing file.
 * @param [in] parent Handle to parent window. Can be a NULL, but then
 *     CMainFrame is used which can cause modality problems.
 * @param [out] path Selected path is returned in this string
 * @param [in] initialPath Initial path (and file) shown when dialog is opened
 * @param [in] titleid Resource string ID for dialog title.
 * @param [in] filterid 0 or STRING ID for filter string
 *     - 0 means "All files (*.*)". Note the string formatting!
 * @param [in] is_open Selects Open/Save -dialog (mode).
 * @note Be careful when setting @p parent to NULL as there are potential
 * modality problems with this. Dialog can be lost behind other windows!
 * @param [in] defaultExtension Extension to append if user doesn't provide one
 */
BOOL SelectFile(HWND parent, CString& path, LPCTSTR initialPath /*=NULL*/,
		UINT titleid /*=0*/, UINT filterid /*=0*/,
		BOOL is_open /*=TRUE*/, LPCTSTR defaultExtension /*=NULL*/)
{
	path.Empty(); // Clear output param

	// This will tell common file dialog what to show
	// and also this will hold its return value
	CString sSelectedFile;

	// check if specified path is a file
	if (initialPath && initialPath[0])
	{
		// If initial path info includes a file
		// we put the bare filename into sSelectedFile
		// so the common file dialog will start up with that file selected
		if (paths_DoesPathExist(initialPath) == IS_EXISTING_FILE)
		{
			String temp;
			SplitFilename(initialPath, 0, &temp, 0);
			sSelectedFile = temp.c_str();
		}
	}

	if (parent == NULL)
		parent = AfxGetMainWnd()->GetSafeHwnd();
	
	if (!filterid)
		filterid = IDS_ALLFILES;
	String title = theApp.LoadString(titleid);
	String filters = theApp.LoadString(filterid);

	// Convert extension mask from MFC style separators ('|')
	//  to Win32 style separators ('\0')
	LPTSTR filtersStr = &*filters.begin();
	ConvertFilter(filtersStr);

	OPENFILENAME_NT4 ofn;
	memset(&ofn, 0, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
	ofn.hwndOwner = parent;
	ofn.lpstrFilter = filtersStr;
	ofn.lpstrCustomFilter = NULL;
	ofn.nFilterIndex = 1;
	ofn.lpstrFile = sSelectedFile.GetBuffer(MAX_PATH);
	ofn.nMaxFile = MAX_PATH;
	ofn.lpstrInitialDir = initialPath;
	ofn.lpstrTitle = title.c_str();
	ofn.lpstrFileTitle = NULL;
	if (defaultExtension)
		ofn.lpstrDefExt = defaultExtension;
	ofn.Flags = OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST;

	BOOL bRetVal = FALSE;
	if (is_open)
		bRetVal = GetOpenFileName((OPENFILENAME *)&ofn);
	else
		bRetVal = GetSaveFileName((OPENFILENAME *)&ofn);
	// common file dialog populated sSelectedFile variable's buffer
	sSelectedFile.ReleaseBuffer();
	SetCurrentDirectory(env_GetWindowsDirectory().c_str()); // Free handle held by GetOpenFileName

	if (bRetVal)
		path = sSelectedFile;
	
	return bRetVal;
}
コード例 #17
0
int VSIArchiveFilesystemHandler::Stat( const char *pszFilename,
                                       VSIStatBufL *pStatBuf,
                                       CPL_UNUSED int nFlags )
{
    int ret = -1;
    CPLString osFileInArchive;

    memset(pStatBuf, 0, sizeof(VSIStatBufL));

    char* archiveFilename = SplitFilename(pszFilename, osFileInArchive, TRUE);
    if (archiveFilename == NULL)
        return -1;

    if (strlen(osFileInArchive) != 0)
    {
        if (ENABLE_DEBUG) CPLDebug("VSIArchive", "Looking for %s %s\n",
                                    archiveFilename, osFileInArchive.c_str());

        const VSIArchiveEntry* archiveEntry = NULL;
        if (FindFileInArchive(archiveFilename, osFileInArchive, &archiveEntry))
        {
            /* Patching st_size with uncompressed file size */
            pStatBuf->st_size = archiveEntry->uncompressed_size;
            pStatBuf->st_mtime = (time_t)archiveEntry->nModifiedTime;
            if (archiveEntry->bIsDir)
                pStatBuf->st_mode = S_IFDIR;
            else
                pStatBuf->st_mode = S_IFREG;
            ret = 0;
        }
    }
    else
    {
        VSIArchiveReader* poReader = CreateReader(archiveFilename);
        CPLFree(archiveFilename);
        archiveFilename = NULL;

        if (poReader != NULL && poReader->GotoFirstFile())
        {
            /* Skip optionnal leading subdir */
            CPLString osFileName = poReader->GetFileName();
            const char* fileName = osFileName.c_str();
            if (fileName[strlen(fileName)-1] == '/' || fileName[strlen(fileName)-1] == '\\')
            {
                if (poReader->GotoNextFile() == FALSE)
                {
                    delete(poReader);
                    return -1;
                }
            }

            if (poReader->GotoNextFile())
            {
                /* Several files in archive --> treat as dir */
                pStatBuf->st_size = 0;
                pStatBuf->st_mode = S_IFDIR;
            }
            else
            {
                /* Patching st_size with uncompressed file size */
                pStatBuf->st_size = poReader->GetFileSize();
                pStatBuf->st_mtime = (time_t)poReader->GetModifiedTime();
                pStatBuf->st_mode = S_IFREG;
            }

            ret = 0;
        }

        delete(poReader);
    }

    CPLFree(archiveFilename);
    return ret;
}
コード例 #18
0
int Unreal3DExport::DoExport( const TCHAR *name, ExpInterface *ei, Interface *i, BOOL suppressPrompts, DWORD options )
{
    int Result = FALSE;

    // Set a global prompt display switch
    bShowPrompts = suppressPrompts ? false : true;
    bExportSelected = (options & SCENE_EXPORT_SELECTED) ? true : false;
    
    // Get file names
    SplitFilename(TSTR(name), &FilePath, &FileName, &FileExt);

    if( MatchPattern(FileName,TSTR(_T("*_d")),TRUE)
    ||  MatchPattern(FileName,TSTR(_T("*_a")),TRUE) )
    {
        FileName = FileName.Substr(0,FileName.length()-2);
    }

    ModelFileName = FilePath + _T("\\") + FileName + TSTR(_T("_d")) + FileExt;
    AnimFileName = FilePath + _T("\\") + FileName + TSTR(_T("_a")) + FileExt;
    ScriptFileName = FilePath + _T("\\") + FileName + TSTR(_T("_rc.uc"));


    // Open Log
    fLog = _tfopen(FilePath + _T("\\") + FileName + _T(".log") ,_T("wb"));

    // Init
    pInt = GetCOREInterface();
    pInt->ProgressStart( GetString(IDS_INFO_INIT), TRUE, fn, this);
    Progress += U3D_PROGRESS_INIT;

    try 
    {
        MyErrorProc pErrorProc;
        SetErrorCallBack(&pErrorProc);

        ReadConfig();


        //if(bShowPrompts)
        /*DialogBoxParam(hInstance, 
                MAKEINTRESOURCE(IDD_PANEL), 
                GetActiveWindow(), 
                Unreal3DExportOptionsDlgProc, (LPARAM)this);*/

	    //if(showPrompts) 
	    {
		    // Prompt the user with our dialogbox, and get all the options.
		    if(!DialogBoxParam(hInstance, 
				MAKEINTRESOURCE(IDD_PANEL), 
				GetActiveWindow(), 
				Unreal3DExportOptionsDlgProc, (LPARAM)this)) 
            {
			    throw CancelException();
		    }
	    }

        // Enumerate interesting nodes
        Init();

        // Fetch data from nodes
        GetTris();
        GetAnim();

        // Prepare data for writing
        Prepare();     

        // Write to files
        WriteScript();
        WriteModel();   
        WriteTracking();

        // Show optional summary
        ShowSummary();

        WriteConfig();

        Result = IMPEXP_SUCCESS;
    }
    catch( CancelException& )
    {
        Result = IMPEXP_CANCEL;
    }
    catch( MAXException& e )
    {
        if( bShowPrompts && !e.message.isNull() )
        {
            MaxMsgBox(pInt->GetMAXHWnd(),e.message,ShortDesc(),MB_OK|MB_ICONERROR);
        }

        Result = IMPEXP_FAIL;
    }

    // Release scene
    if( pScene != NULL )
    {
        pScene->ReleaseIGame();
        pScene = NULL;
    }

    // Close files
    fclosen(fMesh);
    fclosen(fAnim);
    fclosen(fLog);
    fclosen(fScript);
    
    // Return to MAX
    pInt->ProgressEnd();  
    return Result;
}
コード例 #19
0
ファイル: vuedlg.cpp プロジェクト: artemeliy/inf4715
BOOL RendVueParamDlg::FileBrowse() {
   int tried = 0;
   FilterList filterList;
   HWND hWnd = hPanel;
   static int filterIndex = 1;
    OPENFILENAME  ofn;
   TSTR filename;
    TCHAR fname[512];
   TCHAR saveDir[1024];
      {
      TSTR dir;
      SplitFilename(workFileName, &dir, &filename,NULL);
      _tcscpy(saveDir,dir.data());
      }
   _tcscpy(fname,filename.data());
   _tcscat(fname, VUEEXT);

   filterList.Append(GetString(IDS_VUE_FILE));
   filterList.Append(VUEFILTER);

    memset(&ofn, 0, sizeof(ofn));

    ofn.lStructSize      = sizeof(OPENFILENAME);  // No OFN_ENABLEHOOK
    ofn.hwndOwner        = hWnd;
   ofn.hInstance        = hInstance;   


   ofn.nFilterIndex = filterIndex;
    ofn.lpstrFilter  = filterList;

    ofn.lpstrTitle   = GetString(IDS_WRITE_VUEFILE); 
    ofn.lpstrFile    = fname;
    ofn.nMaxFile     = _countof(fname);      

   Interface *iface = GetCOREInterface();
   
   if(saveDir[0])
         ofn.lpstrInitialDir = saveDir;
   else
      ofn.lpstrInitialDir = iface->GetDir(APP_SCENE_DIR);

   if(RunningNewShell()) {
      ofn.Flags = OFN_HIDEREADONLY | OFN_EXPLORER /* | OFN_ENABLEHOOK | OFN_ENABLETEMPLATE*/;  // OFN_OVERWRITEPROMPT;
      ofn.lpfnHook = NULL;// (LPOFNHOOKPROC)FileHook;
      ofn.lCustData = 0;      // 0 for save, 1 for open
//    ofn.lpTemplateName = MAKEINTRESOURCE(IDD_EXT_FILE);
   }
   else {
      ofn.Flags           =   OFN_HIDEREADONLY | OFN_PATHMUSTEXIST /* |OFN_ENABLEHOOK  | OFN_ENABLETEMPLATE */;
      ofn.lpfnHook        =   NULL; // (LPOFNHOOKPROC)PMFileHook;
      ofn.lCustData       =   0;
//    ofn.lpTemplateName     =   MAKEINTRESOURCE(IDD_PM_EXT_FILE);
   }

   ofn.FlagsEx = OFN_EX_NOPLACESBAR;

   FixFileExt(ofn,VUEEXT); // add ".vue" if absent

   while (GetSaveFileName(&ofn))    {
      FixFileExt(ofn,VUEEXT); // add ".vue" if absent

      workFileName = ofn.lpstrFile;
      return TRUE;
      }
   return FALSE;
   }
コード例 #20
0
ファイル: plStaticEnvLayer.cpp プロジェクト: Asteral/Plasma
void    plStaticEnvLayer::RenderCubicMap( INode *node )
{
    int         res, size;
    BOOL        success = 0;
    TSTR        fname, fullname;
    Bitmap      *bm = NULL;
    TSTR        path, filename, ext, thisFilename;
    BitmapInfo  biOutFile;

    static TCHAR    suffixes[ 6 ][ 4 ] = { "_FR", "_BK", "_LF", "_RT", "_UP", "_DN" };


    Interface *ip = GetCOREInterface();
    size = fBitmapPB->GetInt( kBmpTextureSize, ip->GetTime() );
    if( size <= 0 ) 
    {
        return;
    }

    thisFilename = fBitmapPB->GetStr( kBmpBaseFilename, ip->GetTime() );
    if( thisFilename.isNull() )
    {
        return;
    }

    SplitFilename( thisFilename, &path, &filename, &ext );

    BOOL    wasHid = node->IsNodeHidden();
    node->Hide( TRUE );

    // Create a blank bitmap
    biOutFile.SetWidth( size );
    biOutFile.SetHeight( size );
    biOutFile.SetType( BMM_TRUE_64 );
    biOutFile.SetAspect( 1.0f );
    biOutFile.SetCurrentFrame( 0 );
    bm = TheManager->Create( &biOutFile );

    Matrix3 nodeTM = node->GetNodeTM( ip->GetTime() );
    Matrix3 tm; 
    INode *root = ip->GetRootNode();        
    bm->Display( GetString( IDS_CUBIC_RENDER_TITLE ) );

    /// Set up rendering contexts
    ViewParams vp;
    vp.projType = PROJ_PERSPECTIVE;
    vp.hither = .001f;
    vp.yon = 1.0e30f;
    vp.fov = M_PI/2.0f;
    if( fBitmapPB->GetInt( kBmpUseMAXAtmosphere ) )
    {
        vp.nearRange = 0;
        vp.farRange = fBitmapPB->GetFloat( kBmpFarDistance );
    }
    else
    {
        vp.nearRange = vp.farRange = 1.0e30f;
    }
    BOOL    saveUseEnvMap = ip->GetUseEnvironmentMap();
    ip->SetUseEnvironmentMap( false );

    res = ip->OpenCurRenderer( &vp ); 
    for( int i = 0; i < 6; i++ )
    {
        tm = IGetViewTM( i );
        tm.PreTranslate( -nodeTM.GetTrans() ); 
        vp.affineTM = tm;

        // Construct filename
        thisFilename.printf( _T( "%s\\%s%s%s" ), path, filename, suffixes[ i ], ext );

        res = ip->CurRendererRenderFrame( ip->GetTime(), bm, NULL, 1.0f, &vp );
        if( !res ) 
            goto fail;

        if( !IWriteBM( &biOutFile, bm, thisFilename ) ) 
            goto fail;
    }

    success = 1;
fail:
    ip->CloseCurRenderer(); 
    ip->SetUseEnvironmentMap( saveUseEnvMap );

    bm->DeleteThis();
    node->Hide( wasHid );
    if( success )
    {
        for(int i = 0; i < 6; i++ )
        {
            BitmapInfo  bi;
            thisFilename.printf( _T( "%s\\%s%s%s" ), path, filename, suffixes[ i ], ext );
            bi.SetName( thisFilename );

            PBBitmap    pbBitmap( bi );
            fBitmapPB->SetValue( kBmpFrontBitmap + i, ip->GetTime(), &pbBitmap );
        }
        fBitmapPB->GetMap()->UpdateUI( ip->GetTime() );
    }
}
コード例 #21
0
ファイル: smdlexp.cpp プロジェクト: jlecorre/hlinvasion
int SmdExportClass::DoExport(const TCHAR *name,ExpInterface *ei,Interface *i, BOOL suppressPrompts) 
{
	ExpInterface	*pexpiface = ei;	// Hungarian
	Interface		*piface = i;		// Hungarian
	
	// Reset the name-map property manager
	g_inmMac = 0;

	// Present the user with the Export Options dialog
	if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_EXPORTOPTIONS), GetActiveWindow(),
						ExportOptionsDlgProc, (LPARAM)this) <= 0)
		return 0;		// error or cancel

	// Break up filename, re-assemble longer versions
	TSTR strPath, strFile, strExt;
	TCHAR szFile[MAX_PATH];
	SplitFilename(TSTR(name), &strPath, &strFile, &strExt);
		sprintf(szFile,  "%s\\%s.%s",  (char*)strPath, (char*)strFile, DEFAULT_EXT);

	/*
	if (m_fReferenceFrame)
		sprintf(szFile,  "%s\\%s_model.%s",  (char*)strPath, (char*)strFile, DEFAULT_EXT);
	*/

	FILE *pFile;
	if ((pFile = fopen(szFile, "w")) == NULL)
		return FALSE/*failure*/;

	fprintf( pFile, "version %d\n", 1 );

	// Get animation metrics
	m_intervalOfAnimation = piface->GetAnimRange();
	m_tvStart = m_intervalOfAnimation.Start();
	m_tvEnd = m_intervalOfAnimation.End();
	m_tpf = ::GetTicksPerFrame();

	// Count nodes, label them, collect into array
	if (!CollectNodes(pexpiface))
		return 0;	/*fail*/
	
	// Output nodes
	if (!DumpBones(pFile, pexpiface))
	{
		fclose( pFile );
		return 0;	/*fail*/
	}

	// Output bone rotations, for each frame. Do only first frame if this is the reference frame MAX file
	DumpRotations(pFile, pexpiface);

	// Output triangle meshes (first frame/all frames), if this is the reference frame MAX file
	if (m_fReferenceFrame)
	{
		DumpModel(pFile, pexpiface);
	}

	// Tell user that exporting is finished (it can take a while with no feedback)
	char szExportComplete[300];
	sprintf(szExportComplete, "Exported %s.", szFile);
	MessageBox(GetActiveWindow(), szExportComplete, "Status", MB_OK);

	fclose( pFile );

	return 1/*success*/;
}
コード例 #22
0
ファイル: Utility.cpp プロジェクト: 2asoft/xray
TCHAR *FindFile(TCHAR *File)
{
	int			i;
	BOOL		Found;
	TCHAR		*Part;

	Interface	*I;

	Found = 0;

//	NH 21|04|2002
//  Replaced the current search but used the actual path including drive prefix
//  the original seemed to get stuck in the current path, or the last path used
//  this caused files not to be loaded, even though they were there.
//
//	_splitpath(File,Drive,Dir,FileName,Ext);
//
//	Found = SearchPath(Dir,FileName,Ext,MAX_PATH,gFilePath,&Part);
////////////////////////////////////////////////////////////////////////////////

	TSTR p,f,e;
	TSTR name(File);
	SplitFilename(name, &p, &f, &e);

	name = f + e;
	//left the following in as it is used in other methods
	

//	Found = SearchPath(p.data(),f.data(),e.data(),MAX_PATH,gFilePath,&Part);
	Found = SearchPath(p.data(),name.data(),NULL,MAX_PATH,gFilePath,&Part);
	if(!Found)
	{

		I = GetCOREInterface();

		// Search the from where the file was loaded....

		TSTR CurFileP = I->GetCurFilePath();
//		TSTR CurFile = I->GetCurFileName();
		TSTR tP;
		
		SplitFilename(CurFileP,&tP,NULL,NULL);
		Found = SearchPath(tP.data(),name.data(),NULL,MAX_PATH,gFilePath,&Part);
		
		//
		//	Search maps
		//

		if(!Found)
		{
			for (i=0; i<TheManager->GetMapDirCount(); i++) {
				TCHAR* dir = TheManager->GetMapDir(i);
				if((Found = SearchPath(dir,name.data(),NULL,MAX_PATH,gFilePath,&Part)))
				{
					break;
				}
			}
		}
		// not sure why we search here....
		if(!Found)
		{
			//
			//	Search plugins
			//
			for(i=0; i < I->GetPlugInEntryCount(); i++)
			{
				TCHAR* dir = I->GetPlugInDir(i);
				if((Found = SearchPath(dir,name.data(),NULL,MAX_PATH,gFilePath,&Part)))
				{
					break;
				}
			}

		}

	}

	if(Found)
	{
		return(gFilePath);
	}
	else
	{
		return(NULL);
	}

}
コード例 #23
0
// --[  Method  ]---------------------------------------------------------------
//
//  - Class     : CStravaganzaMaxTools
//
//  - prototype : bool BuildShaders()
//
//  - Purpose   : Builds the shader list from MAX's materials.
//                Preview mode requires texture files to be stored with full
//                path in order to load them. When we export, we only store the
//                filename. Another thing is that in the export mode, we copy
//                all textures into the path specified by the user if that
//                option is checked.
//
// -----------------------------------------------------------------------------
bool CStravaganzaMaxTools::BuildShaders()
{
	std::vector<Mtl*>::iterator it;

	assert(m_vecShaders.empty());

	if(!m_bPreview && m_bCopyTextures && m_strTexturePath == "")
	{
		CLogger::NotifyWindow("Textures won't be copied\nSpecify a valid output texture path first");
	}

	LOG.Write("\n\n-Building shaders: ");

	for(it = m_vecMaterials.begin(); it != m_vecMaterials.end(); ++it)
	{
		Mtl* pMaxMaterial = *it;
		assert(pMaxMaterial);

		LOG.Write("\n    %s", pMaxMaterial->GetName().data());
		CShaderStandard* pShaderStd = new CShaderStandard;
		pShaderStd->SetName(pMaxMaterial->GetName().data());

		// Properties

		StdMat2 *pMaxStandardMtl = NULL;
		StdMat2 *pMaxBakedMtl    = NULL;

		float fAlpha;

		if(pMaxMaterial->ClassID() == Class_ID(DMTL_CLASS_ID, 0))
		{
			pMaxStandardMtl = (StdMat2 *)pMaxMaterial;
		}
		else if(pMaxMaterial->ClassID() == Class_ID(BAKE_SHELL_CLASS_ID, 0))
		{
			pMaxStandardMtl = (StdMat2 *)pMaxMaterial->GetSubMtl(0);
			pMaxBakedMtl    = (StdMat2 *)pMaxMaterial->GetSubMtl(1);
		}

		if(pMaxStandardMtl)
		{
			// Standard material

			fAlpha = pMaxStandardMtl->GetOpacity(0);

			Shader* pMaxShader = pMaxStandardMtl->GetShader();

			CVector4 v4Specular = ColorToVector4(pMaxStandardMtl->GetSpecular(0), 0.0f) * pMaxShader->GetSpecularLevel(0, 0);

			pShaderStd->SetAmbient  (ColorToVector4(pMaxStandardMtl->GetAmbient(0),  0.0f));
			pShaderStd->SetDiffuse  (ColorToVector4(pMaxStandardMtl->GetDiffuse(0),  fAlpha));
			pShaderStd->SetSpecular (v4Specular);
			pShaderStd->SetShininess(pMaxShader->GetGlossiness(0, 0) * 128.0f);

			if(pMaxStandardMtl->GetTwoSided() == TRUE)
			{
				pShaderStd->SetTwoSided(true);
			}

			// Need to cast to StdMat2 in order to get access to IsFaceted().
			// ¿Is StdMat2 always the interface for standard materials?
			if(((StdMat2*)pMaxStandardMtl)->IsFaceted())
			{
				pShaderStd->SetFaceted(true);
			}

			if(pMaxStandardMtl->GetWire() == TRUE)
			{
				pShaderStd->SetPostWire(true);
				pShaderStd->SetWireLineThickness(pMaxStandardMtl->GetWireSize(0));
			}
		}
		else
		{
			// Material != Standard

			fAlpha = 1.0f; // pMaxMaterial->GetXParency();

			pShaderStd->SetAmbient  (ColorToVector4(pMaxMaterial->GetAmbient(),  0.0f));
			pShaderStd->SetDiffuse  (ColorToVector4(pMaxMaterial->GetDiffuse(),  fAlpha));
			pShaderStd->SetSpecular (CVector4(0.0f, 0.0f, 0.0f, 0.0f));
			pShaderStd->SetShininess(0.0f);
		}

		// Layers

		if(!pMaxStandardMtl)
		{
			m_vecShaders.push_back(pShaderStd);
			continue;
		}

		bool bDiffuseMap32Bits = false;
		StdMat2 *pStandardMtl;

		for(int i = 0; i < 3; i++)
		{
			int nMap;

			pStandardMtl = pMaxStandardMtl;

			// 0 = diffuse, 1 == bump, 2 = lightmap (self illumination slot) or envmap (reflection slot)

			if(i == 0)
			{
				nMap = ID_DI;
			}
			else if(i == 1)
			{
				nMap = ID_BU;

				// If its a baked material, get the bump map from there

				if(pMaxBakedMtl)
				{
					pStandardMtl = pMaxBakedMtl;
				}
			}
			else if(i == 2)
			{
				bool bBaked = false;

				// If its a baked material, get the map2 (lightmap) from there

				if(pMaxBakedMtl)
				{
					if(pMaxBakedMtl->GetMapState(ID_SI) == MAXMAPSTATE_ENABLED)
					{
						bBaked       = true;
						nMap         = ID_SI;
						pStandardMtl = pMaxBakedMtl;
					}
				}

				if(!bBaked)
				{
					if(pStandardMtl->GetMapState(ID_SI) == MAXMAPSTATE_ENABLED)
					{
						nMap = ID_SI;
					}
					else
					{
						nMap = ID_RL;
					}
				}
			}

			// Check validity

			if(pStandardMtl->GetMapState(nMap) != MAXMAPSTATE_ENABLED)
			{
				if(i == 0)
				{
					LOG.Write("\n        No diffuse. Skipping.");
					break;
				}

				continue;
			}

			Texmap* pMaxTexmap = pStandardMtl->GetSubTexmap(nMap);

			if(!pMaxTexmap)
			{
				if(i == 0)
				{
					LOG.Write("\n        No diffuse. Skipping.");
					break;
				}

				continue;
			}

			// Get texmaps

			std::vector<std::string> vecTextures, vecPaths;

			CShaderStandard::SLayerInfo  layerInfo;
			CShaderStandard::SBitmapInfo bitmapInfo;

			if(pMaxTexmap->ClassID() == Class_ID(BMTEX_CLASS_ID, 0))
			{
				BitmapTex* pMaxBitmapTex = (BitmapTex*)pMaxTexmap;
				Bitmap*    pMaxBitmap    = pMaxBitmapTex->GetBitmap(SECONDS_TO_TICKS(m_fStartTime));
				StdUVGen*  pMaxUVGen     = pMaxBitmapTex->GetUVGen();

				if(!pMaxBitmap)
				{
					if(i == 0)
					{
						LOG.Write("\n        Invalid diffuse. Skipping.");
						break;
					}
					continue;
				}

				assert(pMaxUVGen);

				BitmapInfo bi = pMaxBitmap->Storage()->bi;

				// bi.Name() returns the full path
				// bi.Filename() returns just the filename

				vecTextures.push_back(bi.Filename());
				vecPaths.   push_back(bi.Name());

				LOG.Write("\n        Bitmap %s", vecTextures[0].data());

				// Check if diffuse texture has alpha channel

				if(i == 0)
				{
					CBitmap    bitmap;
					CInputFile bitmapFile;

					if(!bitmapFile.Open(bi.Name(), false))
					{
						CLogger::NotifyWindow("WARNING - CStravaganzaMaxTools::BuildShaders():\nUnable to load file %s", bi.Name());
					}
					else
					{
						if(!bitmap.Load(&bitmapFile, GetFileExt(bi.Name())))
						{
							CLogger::NotifyWindow("WARNING - CStravaganzaMaxTools::BuildShaders():\nUnable to load bitmap %s", bi.Name());
						}
						else
						{
							if(bitmap.GetBpp() == 32)
							{
								bDiffuseMap32Bits = true;
								LOG.Write(" (with alpha channel)");
							}
							bitmap.Free();
						}
						bitmapFile.Close();
					}
				}

				// Ok, copy properties

				layerInfo.texInfo.bLoop        = false;
				layerInfo.texInfo.eTextureType = UtilGL::Texturing::CTexture::TEXTURE2D;

				bitmapInfo.strFile         = m_bPreview ? bi.Name() : bi.Filename();
				bitmapInfo.bTile           = ((pMaxUVGen->GetTextureTiling() & (U_WRAP | V_WRAP)) == (U_WRAP | V_WRAP)) ? true : false;
				bitmapInfo.fSeconds        = 0.0f;
				bitmapInfo.bForceFiltering = false;
				bitmapInfo.eFilter         = UtilGL::Texturing::FILTER_TRILINEAR; // won't be used (forcefiltering = false)
				
				layerInfo.texInfo.m_vecBitmaps.push_back(bitmapInfo);

				layerInfo.eTexEnv          = nMap == ID_RL ? CShaderStandard::TEXENV_ADD : CShaderStandard::TEXENV_MODULATE;
				layerInfo.eUVGen           = pMaxUVGen->GetCoordMapping(0) == UVMAP_SPHERE_ENV ? CShaderStandard::UVGEN_ENVMAPPING : CShaderStandard::UVGEN_EXPLICITMAPPING;
				layerInfo.uMapChannel      = pMaxUVGen->GetMapChannel();
				layerInfo.v3ScrollSpeed    = CVector3(0.0f, 0.0f, 0.0f);
				layerInfo.v3RotationSpeed  = CVector3(0.0f, 0.0f, 0.0f);
				layerInfo.v3ScrollOffset   = CVector3(pMaxUVGen->GetUOffs(0), pMaxUVGen->GetVOffs(0), 0.0f);
				layerInfo.v3RotationOffset = CVector3(pMaxUVGen->GetUAng(0),  pMaxUVGen->GetVAng(0),  pMaxUVGen->GetWAng(0));
			}
			else if(pMaxTexmap->ClassID() == Class_ID(ACUBIC_CLASS_ID, 0))
			{
				ACubic*       pMaxCubic  = (ACubic*)pMaxTexmap;
				IParamBlock2* pBlock     = pMaxCubic->pblock;
				Interval      validRange = m_pMaxInterface->GetAnimRange();

				for(int nFace = 0; nFace < 6; nFace++)
				{
					int nMaxFace;

					switch(nFace)
					{
					case 0: nMaxFace = 3; break;
					case 1: nMaxFace = 2; break;
					case 2: nMaxFace = 1; break;
					case 3: nMaxFace = 0; break;
					case 4: nMaxFace = 5; break;
					case 5: nMaxFace = 4; break;
					}

					TCHAR *name;
					pBlock->GetValue(acubic_bitmap_names, TICKS_TO_SECONDS(m_fStartTime), name, validRange, nMaxFace);

					vecPaths.push_back(name);

					CStr path, file, ext;
					SplitFilename(CStr(name), &path, &file, &ext);

					std::string strFile = std::string(file.data()) + ext.data();

					vecTextures.push_back(strFile);

					bitmapInfo.strFile         = m_bPreview ? name : strFile;
					bitmapInfo.bTile           = false;
					bitmapInfo.fSeconds        = 0.0f;
					bitmapInfo.bForceFiltering = false;
					bitmapInfo.eFilter         = UtilGL::Texturing::FILTER_TRILINEAR;
					
					layerInfo.texInfo.m_vecBitmaps.push_back(bitmapInfo);
				}

				layerInfo.texInfo.bLoop        = false;
				layerInfo.texInfo.eTextureType = UtilGL::Texturing::CTexture::TEXTURECUBEMAP;

				layerInfo.eTexEnv          = nMap == ID_RL ? CShaderStandard::TEXENV_ADD : CShaderStandard::TEXENV_MODULATE;
				layerInfo.eUVGen           = CShaderStandard::UVGEN_ENVMAPPING;
				layerInfo.uMapChannel      = 0;
				layerInfo.v3ScrollSpeed    = CVector3(0.0f, 0.0f, 0.0f);
				layerInfo.v3RotationSpeed  = CVector3(0.0f, 0.0f, 0.0f);
				layerInfo.v3ScrollOffset   = CVector3(0.0f, 0.0f, 0.0f);
				layerInfo.v3RotationOffset = CVector3(0.0f, 0.0f, 0.0f);
			}
			else
			{
				if(i == 0)
				{
					LOG.Write("\n        No diffuse. Skipping.");
					break;
				}
				continue;
			}

			if(!m_bPreview && m_bCopyTextures && m_strTexturePath != "")
			{
				for(int nTex = 0; nTex != vecTextures.size(); nTex++)
				{
					// Copy textures into the specified folder

					std::string strDestPath = m_strTexturePath;

					if(strDestPath[strDestPath.length() - 1] != '\\')
					{
						strDestPath.append("\\", 1);
					}

					strDestPath.append(vecTextures[nTex]);

					if(!CopyFile(vecPaths[nTex].data(), strDestPath.data(), FALSE))
					{
						CLogger::NotifyWindow("Unable to copy %s to\n%s", vecPaths[i], strDestPath.data());
					}
				}
			}

			if(layerInfo.eUVGen == CShaderStandard::UVGEN_ENVMAPPING && i == 1)
			{
				CLogger::NotifyWindow("%s : Bump with spheremapping not supported", pShaderStd->GetName().data());
			}
			else
			{
				// Add layer

				switch(i)
				{
				case 0: pShaderStd->SetLayer(CShaderStandard::LAYER_DIFF, layerInfo); break;
				case 1: pShaderStd->SetLayer(CShaderStandard::LAYER_BUMP, layerInfo); break;
				case 2: pShaderStd->SetLayer(CShaderStandard::LAYER_MAP2, layerInfo); break;
				}
			}
		}

		// ¿Do we need blending?

		if(ARE_EQUAL(fAlpha, 1.0f) && !bDiffuseMap32Bits)
		{
			pShaderStd->SetBlendSrcFactor(UtilGL::States::BLEND_ONE);
			pShaderStd->SetBlendDstFactor(UtilGL::States::BLEND_ZERO);
		}
		else
		{
			pShaderStd->SetBlendSrcFactor(UtilGL::States::BLEND_SRCALPHA);
			pShaderStd->SetBlendDstFactor(UtilGL::States::BLEND_INVSRCALPHA);
		}

		// Add shader

		m_vecShaders.push_back(pShaderStd);
	}

	return true;
}
コード例 #24
0
int VWeightExportClass::DoExport(const TCHAR *name, ExpInterface *ei, Interface *pi, BOOL suppressPrompts, DWORD options) 
{
	ExpInterface	*pexpiface = ei;	// Hungarian
	Interface		*piface = pi;		// Hungarian
	
	// Reset the name-map property manager
	ResetINodeMap();

	// Break up filename, re-assemble longer versions
	TSTR strPath, strFile, strExt;
	TCHAR szFile[MAX_PATH];
	SplitFilename(TSTR(name), &strPath, &strFile, &strExt);
		sprintf(szFile,  "%s\\%s.%s",  (char*)strPath, (char*)strFile, DEFAULT_EXT);


	// Get animation metrics
	m_intervalOfAnimation = piface->GetAnimRange();
	m_tvStart = m_intervalOfAnimation.Start();
	m_tvEnd = m_intervalOfAnimation.End();
	m_tpf = ::GetTicksPerFrame();


	Interface *ip = GetCOREInterface();

	ResetINodeMap( );
	m_cMaxNode = BuildINodeMap( ip->GetRootNode() );

	// Count nodes, label them, collect into array
	CollectNodes( ip->GetRootNode() );

	CollectModel( pexpiface );

#if 1
	FILE *pFile;
	if ((pFile = fopen(szFile, "wb")) == NULL)
		return FALSE/*failure*/;

	int version = 1;
	fwrite( &version, 1, sizeof( int ), pFile );

	int i, j;

	fwrite( &m_cMaxNode, 1, sizeof( int ), pFile );
	fwrite( &m_cMaxVertex, 1, sizeof( int ), pFile );

	for (i = 0; i < m_cMaxNode; i++)
	{
		fwrite( &m_MaxNode[i], 1, sizeof(m_MaxNode[i]), pFile );
	}

	for (j = 0; j < m_cMaxVertex; j++)
	{
		fwrite( m_MaxVertex[j], m_cMaxNode, sizeof(MaxVertWeight), pFile );
	}

	fclose( pFile );
#else
	FILE *pFile;
	if ((pFile = fopen(szFile, "w")) == NULL)
		return FALSE/*failure*/;

	fprintf( pFile, "version %d\n", 1 );

	int i, j;

	fprintf(pFile, "%d\n", m_cMaxNode );
	fprintf(pFile, "%d\n", m_cMaxVertex );

	for (i = 0; i < m_cMaxNode; i++)
	{
		fprintf(pFile, "%5d \"%s\" %3d\n", 
			i, m_MaxNode[i].szNodeName, m_MaxNode[i].imaxnodeParent );
	}

	for (j = 0; j < m_cMaxVertex; j++)
	{
		fprintf( pFile, "%d ", j );

		for (int i = 0; i < m_cMaxNode; i++)
		{
			// if (strstr(m_MaxNode[i].szNodeName, "Bip01 R Finger"))
			// if (m_MaxNode[i].szNodeName[0] == 'D')
			{
				fprintf(pFile, " %5.3f", m_MaxVertex[j][i].flDist );
				fprintf(pFile, " %3.0f", m_MaxVertex[j][i].flWeight );
			}
		}
		fprintf(pFile, "\n" );
	}

	fclose( pFile );
#endif

	// Tell user that exporting is finished (it can take a while with no feedback)
	char szExportComplete[300];
	sprintf(szExportComplete, "Exported %s.", szFile);
	MessageBox(GetActiveWindow(), szExportComplete, "Status", MB_OK);


	return 1/*success*/;
}
コード例 #25
0
ファイル: surf.cpp プロジェクト: wheam/pai
bool SURFFeatureManager::CalculateFeatureSet(const int media_type,
                                             const std::string& image_folder) {
  std::string folder = image_folder;
  if (image_folder[image_folder.size() - 1] != '/') {
    folder += "/";
  }
  DIR *dir = opendir(folder.c_str());
  if (dir == NULL) return false;

  struct dirent *ent = NULL;
  while ((ent = readdir(dir)) != NULL) {
    if (strcmp(".", ent->d_name) == 0 || strcmp("..", ent->d_name) == 0) continue;
    std::vector<std::string> arr;
    SplitFilename(ent->d_name, &arr);
    SURFFeature *feature = new SURFFeature;
    GetFeature(folder + ent->d_name, feature);

    char data_folder[64];
    sprintf(data_folder, "%s/%d", kDataFolder, media_type);
    mkdir(kDataFolder, S_IRWXU | S_IRWXG | S_IRWXO);
    mkdir(data_folder, S_IRWXU | S_IRWXG | S_IRWXO);
    char filepath[128];
    sprintf(filepath, "%s/%s_%s_.yaml",
            data_folder, arr[0].c_str(), arr[1].c_str());
    cv::FileStorage fs(filepath,
                       cv::FileStorage::WRITE);
    fs << "D" << feature->descriptor;
    fs << "I" << feature->image;
    fs << "K" << "[";
    for (std::vector<cv::KeyPoint>::iterator it = feature->key_points.begin();
         it != feature->key_points.end();
         ++it) {
      fs << "{"
         << "x" << it->pt.x
         << "y" << it->pt.y
         << "size" << it->size
         << "angle" << it->angle
         << "response" << it->response
         << "octave" << it->octave
         << "class_id" << it->class_id
         << "}";
    }
    fs << "]";
    fs << "R" << "{"
       << "x" << feature->roi.x
       << "y" << feature->roi.y
       << "width" << feature->roi.width
       << "height" << feature->roi.height
       << "}";
    fs.release();
    FeatureMap::iterator it;
    if ((it = feature_map_.find(media_type)) == feature_map_.end()) {
      feature_map_.insert(make_pair(
        media_type,
        std::map<std::string, SURFFeature*>()));
    } else {
      it->second.insert(make_pair(arr[1], feature));
    }
  }
  return true;
}