NS_IMETHODIMP
nsLocalFile::GetRelativeDescriptor(nsIFile* aFromFile, nsACString& aResult)
{
  if (NS_WARN_IF(!aFromFile)) {
    return NS_ERROR_INVALID_ARG;
  }

  //
  // aResult will be UTF-8 encoded
  //

  nsresult rv;
  aResult.Truncate(0);

  nsAutoString thisPath, fromPath;
  nsAutoTArray<char16_t*, 32> thisNodes;
  nsAutoTArray<char16_t*, 32> fromNodes;

  rv = GetPath(thisPath);
  if (NS_FAILED(rv)) {
    return rv;
  }
  rv = aFromFile->GetPath(fromPath);
  if (NS_FAILED(rv)) {
    return rv;
  }

  // get raw pointer to mutable string buffer
  char16_t* thisPathPtr;
  thisPath.BeginWriting(thisPathPtr);
  char16_t* fromPathPtr;
  fromPath.BeginWriting(fromPathPtr);

  SplitPath(thisPathPtr, thisNodes);
  SplitPath(fromPathPtr, fromNodes);

  size_t nodeIndex;
  for (nodeIndex = 0;
       nodeIndex < thisNodes.Length() && nodeIndex < fromNodes.Length();
       ++nodeIndex) {
#ifdef XP_WIN
    if (_wcsicmp(char16ptr_t(thisNodes[nodeIndex]),
                 char16ptr_t(fromNodes[nodeIndex]))) {
      break;
    }
#else
    if (nsCRT::strcmp(thisNodes[nodeIndex], fromNodes[nodeIndex])) {
      break;
    }
#endif
  }

  size_t branchIndex = nodeIndex;
  for (nodeIndex = branchIndex; nodeIndex < fromNodes.Length(); ++nodeIndex) {
    aResult.AppendLiteral("../");
  }
  for (nodeIndex = branchIndex; nodeIndex < thisNodes.Length(); ++nodeIndex) {
    NS_ConvertUTF16toUTF8 nodeStr(thisNodes[nodeIndex]);
    aResult.Append(nodeStr);
    if (nodeIndex + 1 < thisNodes.Length()) {
      aResult.Append('/');
    }
  }

  return NS_OK;
}
Example #2
0
void PHPDebugStartDlg::OnOkUI(wxUpdateUIEvent& event) { event.Enable(!GetPath().IsEmpty()); }
Example #3
0
void CVideoInfoTag::ToSortable(SortItem& sortable, Field field) const
{
  switch (field)
  {
  case FieldDirector:                 sortable[FieldDirector] = m_director; break;
  case FieldWriter:                   sortable[FieldWriter] = m_writingCredits; break;
  case FieldGenre:                    sortable[FieldGenre] = m_genre; break;
  case FieldCountry:                  sortable[FieldCountry] = m_country; break;
  case FieldTagline:                  sortable[FieldTagline] = m_strTagLine; break;
  case FieldPlotOutline:              sortable[FieldPlotOutline] = m_strPlotOutline; break;
  case FieldPlot:                     sortable[FieldPlot] = m_strPlot; break;
  case FieldTitle:
  {
    // make sure not to overwrite an existing title with an empty one
    std::string title = m_strTitle;
    if (!title.empty() || sortable.find(FieldTitle) == sortable.end())
      sortable[FieldTitle] = title;
    break;
  }
  case FieldVotes:                    sortable[FieldVotes] = m_strVotes; break;
  case FieldStudio:                   sortable[FieldStudio] = m_studio; break;
  case FieldTrailer:                  sortable[FieldTrailer] = m_strTrailer; break;
  case FieldSet:                      sortable[FieldSet] = m_strSet; break;
  case FieldTime:                     sortable[FieldTime] = GetDuration(); break;
  case FieldFilename:                 sortable[FieldFilename] = m_strFile; break;
  case FieldMPAA:                     sortable[FieldMPAA] = m_strMPAARating; break;
  case FieldPath:
  {
    // make sure not to overwrite an existing path with an empty one
    std::string path = GetPath();
    if (!path.empty() || sortable.find(FieldPath) == sortable.end())
      sortable[FieldPath] = path;
    break;
  }
  case FieldSortTitle:                sortable[FieldSortTitle] = m_strSortTitle; break;
  case FieldTvShowStatus:             sortable[FieldTvShowStatus] = m_strStatus; break;
  case FieldProductionCode:           sortable[FieldProductionCode] = m_strProductionCode; break;
  case FieldAirDate:                  sortable[FieldAirDate] = m_firstAired.IsValid() ? m_firstAired.GetAsDBDate() : (m_premiered.IsValid() ? m_premiered.GetAsDBDate() : StringUtils::Empty); break;
  case FieldTvShowTitle:              sortable[FieldTvShowTitle] = m_strShowTitle; break;
  case FieldAlbum:                    sortable[FieldAlbum] = m_strAlbum; break;
  case FieldArtist:                   sortable[FieldArtist] = m_artist; break;
  case FieldPlaycount:                sortable[FieldPlaycount] = m_playCount; break;
  case FieldLastPlayed:               sortable[FieldLastPlayed] = m_lastPlayed.IsValid() ? m_lastPlayed.GetAsDBDateTime() : StringUtils::Empty; break;
  case FieldTop250:                   sortable[FieldTop250] = m_iTop250; break;
  case FieldYear:                     sortable[FieldYear] = m_iYear; break;
  case FieldSeason:                   sortable[FieldSeason] = m_iSeason; break;
  case FieldEpisodeNumber:            sortable[FieldEpisodeNumber] = m_iEpisode; break;
  case FieldNumberOfEpisodes:         sortable[FieldNumberOfEpisodes] = m_iEpisode; break;
  case FieldNumberOfWatchedEpisodes:  sortable[FieldNumberOfWatchedEpisodes] = m_iEpisode; break;
  case FieldEpisodeNumberSpecialSort: sortable[FieldEpisodeNumberSpecialSort] = m_iSpecialSortEpisode; break;
  case FieldSeasonSpecialSort:        sortable[FieldSeasonSpecialSort] = m_iSpecialSortSeason; break;
  case FieldRating:                   sortable[FieldRating] = m_fRating; break;
  case FieldUserRating:               sortable[FieldUserRating] = m_iUserRating; break;
  case FieldId:                       sortable[FieldId] = m_iDbId; break;
  case FieldTrackNumber:              sortable[FieldTrackNumber] = m_iTrack; break;
  case FieldTag:                      sortable[FieldTag] = m_tags; break;

  case FieldVideoResolution:          sortable[FieldVideoResolution] = m_streamDetails.GetVideoHeight(); break;
  case FieldVideoAspectRatio:         sortable[FieldVideoAspectRatio] = m_streamDetails.GetVideoAspect(); break;
  case FieldVideoCodec:               sortable[FieldVideoCodec] = m_streamDetails.GetVideoCodec(); break;
  case FieldStereoMode:               sortable[FieldStereoMode] = m_streamDetails.GetStereoMode(); break;

  case FieldAudioChannels:            sortable[FieldAudioChannels] = m_streamDetails.GetAudioChannels(); break;
  case FieldAudioCodec:               sortable[FieldAudioCodec] = m_streamDetails.GetAudioCodec(); break;
  case FieldAudioLanguage:            sortable[FieldAudioLanguage] = m_streamDetails.GetAudioLanguage(); break;

  case FieldSubtitleLanguage:         sortable[FieldSubtitleLanguage] = m_streamDetails.GetSubtitleLanguage(); break;

  case FieldInProgress:               sortable[FieldInProgress] = m_resumePoint.IsPartWay(); break;
  case FieldDateAdded:                sortable[FieldDateAdded] = m_dateAdded.IsValid() ? m_dateAdded.GetAsDBDateTime() : StringUtils::Empty; break;
  case FieldMediaType:                sortable[FieldMediaType] = m_type; break;
  default: break;
  }
}
Example #4
0
void FarFileName::SetName (const FarFileName& name)
{
  *this = FarFileName::MakeName (GetPath(), name.GetName());
}
Example #5
0
	int Init(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments)
	{
		// get userdir
		fs_storage_path(pApplicationName, m_aUserdir, sizeof(m_aUserdir));

		// get datadir
		FindDatadir(ppArguments[0]);

		// get currentdir
		if(!fs_getcwd(m_aCurrentdir, sizeof(m_aCurrentdir)))
			m_aCurrentdir[0] = 0;

		// load paths from storage.cfg
		LoadPaths(ppArguments[0]);

		if(!m_NumPaths)
		{
			dbg_msg("storage", "using standard paths");
			AddDefaultPaths();
		}

		// add save directories
		if(StorageType != STORAGETYPE_BASIC)
		{
			if(m_NumPaths && (!m_aaStoragePaths[TYPE_SAVE][0] || !fs_makedir(m_aaStoragePaths[TYPE_SAVE])))
			{
				char aPath[MAX_PATH_LENGTH];
				if(StorageType == STORAGETYPE_CLIENT)
				{
					fs_makedir(GetPath(TYPE_SAVE, "screenshots", aPath, sizeof(aPath)));
					fs_makedir(GetPath(TYPE_SAVE, "screenshots/auto", aPath, sizeof(aPath)));
					fs_makedir(GetPath(TYPE_SAVE, "maps", aPath, sizeof(aPath)));
					fs_makedir(GetPath(TYPE_SAVE, "downloadedmaps", aPath, sizeof(aPath)));
					fs_makedir(GetPath(TYPE_SAVE, "downloadedmods", aPath, sizeof(aPath)));
					fs_makedir(GetPath(TYPE_SAVE, "skins", aPath, sizeof(aPath)));
				}
				fs_makedir(GetPath(TYPE_SAVE, "mods", aPath, sizeof(aPath)));
				fs_makedir(GetPath(TYPE_SAVE, "dumps", aPath, sizeof(aPath)));
				fs_makedir(GetPath(TYPE_SAVE, "demos", aPath, sizeof(aPath)));
				fs_makedir(GetPath(TYPE_SAVE, "demos/auto", aPath, sizeof(aPath)));
				fs_makedir(GetPath(TYPE_SAVE, "configs", aPath, sizeof(aPath)));
			}
			else
			{
				dbg_msg("storage", "unable to create save directory");
				return 1;
			}
		}

		return m_NumPaths ? 0 : 1;
	}
Example #6
0
File: path.c Project: mikekap/wine
/* Helper function to verify that the current path in the given DC matches the expected path.
 *
 * We use a "smart" matching algorithm that allows us to detect partial improvements
 * in conformance. Specifically, two running indices are kept, one through the actual
 * path and one through the expected path. The actual path index increases unless there is
 * no match and the todo field of the appropriate path_test_t element is 2. Similarly,
 * if the wine_entries_preceding field of the appropriate path_test_t element is non-zero,
 * the expected path index does not increase for that many elements as long as there
 * is no match. This allows us to todo_wine extra path elements that are present only
 * on wine but not on native and vice versa.
 *
 * Note that if expected_size is zero and the WINETEST_DEBUG environment variable is
 * greater than 2, the trace() output is a C path_test_t array structure, useful for making
 * new tests that use this function.
 */
static void ok_path(HDC hdc, const char *path_name, const path_test_t *expected, int expected_size, BOOL todo_size)
{
    static const char *type_string[8] = { "Unknown (0)", "PT_CLOSEFIGURE", "PT_LINETO",
                                          "PT_LINETO | PT_CLOSEFIGURE", "PT_BEZIERTO",
                                          "PT_BEZIERTO | PT_CLOSEFIGURE", "PT_MOVETO", "PT_MOVETO | PT_CLOSEFIGURE"};
    POINT *pnt = NULL;
    BYTE *types = NULL;
    int size, numskip,
        idx = 0, eidx = 0;

    /* Get the path */
    assert(hdc != 0);
    size = GetPath(hdc, NULL, NULL, 0);
    ok(size > 0, "GetPath returned size %d, last error %d\n", size, GetLastError());
    if (size <= 0)
    {
        skip("Cannot perform path comparisons due to failure to retrieve path.\n");
        return;
    }
    pnt = HeapAlloc(GetProcessHeap(), 0, size*sizeof(POINT));
    assert(pnt != 0);
    types = HeapAlloc(GetProcessHeap(), 0, size*sizeof(BYTE));
    assert(types != 0);
    size = GetPath(hdc, pnt, types, size);
    assert(size > 0);

    if (todo_size) todo_wine
        ok(size == expected_size, "Path size %d does not match expected size %d\n", size, expected_size);
    else
        ok(size == expected_size, "Path size %d does not match expected size %d\n", size, expected_size);

    if (winetest_debug > 2)
        trace("static const path_test_t %s[] = {\n", path_name);

    numskip = expected_size ? expected[eidx].wine_only_entries_preceding : 0;
    while (idx < size && eidx < expected_size)
    {
        /* We allow a few pixels fudge in matching X and Y coordinates to account for imprecision in
         * floating point to integer conversion */
        BOOL match = (types[idx] == expected[eidx].type) &&
            (pnt[idx].x >= expected[eidx].x-2 && pnt[idx].x <= expected[eidx].x+2) &&
            (pnt[idx].y >= expected[eidx].y-2 && pnt[idx].y <= expected[eidx].y+2);

        if (expected[eidx].todo || numskip) todo_wine
            ok(match, "Expected #%d: %s (%d,%d) but got %s (%d,%d)\n", eidx,
               type_string[expected[eidx].type], expected[eidx].x, expected[eidx].y,
               type_string[types[idx]], pnt[idx].x, pnt[idx].y);
        else
            ok(match, "Expected #%d: %s (%d,%d) but got %s (%d,%d)\n", eidx,
               type_string[expected[eidx].type], expected[eidx].x, expected[eidx].y,
               type_string[types[idx]], pnt[idx].x, pnt[idx].y);

        if (match || expected[eidx].todo != 2)
        {
            if (winetest_debug > 2)
                trace("    {%d, %d, %s, 0, 0}%s /* %d */\n", pnt[idx].x, pnt[idx].y,
                      type_string[types[idx]], idx < size-1 ? "," : "};", idx);
            idx++;
        }
        if (match || !numskip--)
            numskip = expected[++eidx].wine_only_entries_preceding;
    }

    /* If we are debugging and the actual path is longer than the expected path, make
     * sure to display the entire path */
    if (winetest_debug > 2 && idx < size)
        for (; idx < size; idx++)
            trace("    {%d, %d, %s, 0, 0}%s /* %d */\n", pnt[idx].x, pnt[idx].y,
                  type_string[types[idx]], idx < size-1 ? "," : "};", idx);

    HeapFree(GetProcessHeap(), 0, types);
    HeapFree(GetProcessHeap(), 0, pnt);
}
	ERMsg CUIEnvCanPrcpRadar::Execute(CCallback& callback)
	{
		ERMsg msg;
		string workingDir = GetDir(WORKING_DIR);

		CInternetSessionPtr pSession;
		CHttpConnectionPtr pConnection;

		msg = GetHttpConnection(SERVER_NAME, pConnection, pSession);
		if (!msg)
			return msg;

		callback.AddMessage(GetString(IDS_UPDATE_DIR));
		callback.AddMessage(workingDir, 1);
		callback.AddMessage(GetString(IDS_UPDATE_FROM));
		callback.AddMessage(SERVER_NAME, 1);
		callback.AddMessage("");

		string type = as<size_t>(TYPE) == TYPE_06HOURS ? "06" : "24";
		string path = SERVER_PATH + type + "/*.grib2";


		CFileInfoVector fileList;
		msg = UtilWWW::FindFiles(pConnection, path, fileList);

		callback.AddMessage("Number of images found: " + ToString(fileList.size()));
		//keep only 10km grid
		for (CFileInfoVector::const_iterator it = fileList.begin(); it != fileList.end();)
		{
		//	string fileTitle = GetFileTitle(it->m_filePath);
//			if (Find(fileTitle, "ps10km"))
	//		{
		//		it = fileList.erase(it);
//			}
	//		else
		//	{
			string fileName = GetFileName(it->m_filePath);
			string filePath = GetOutputFilePath(fileName);
			if (!NeedDownload(*it, filePath))
				it = fileList.erase(it);
			else
				it++;
			//}

			msg += callback.StepIt(0);
		}

		//remove up to date file

		//for(int i=fileList.size()-1; i>=0; i--)
		//{
		//	string fileName = GetFileName(fileList[i].m_filePath);
		//	string filePath = GetOutputFilePath(fileName);
		//	if( !NeedDownload(fileList[i], filePath) )
		//		fileList.erase(fileList.begin() + i);

		//	msg += callback.StepIt(0);
		//}



		callback.AddMessage("Number of images to download after clearing: " + ToString(fileList.size()));
		callback.PushTask("Download precipitation images + (" + ToString(fileList.size() )+ ")", fileList.size());
		//callback.SetNbStep(fileList.size());

		int nbDownload = 0;
		for (size_t i = 0; i < fileList.size() && msg; i++)
		{
			string filePath = GetOutputFilePath(GetFileName(fileList[i].m_filePath));
			CreateMultipleDir(GetPath(filePath));
			msg = UtilWWW::CopyFile(pConnection, fileList[i].m_filePath, filePath, INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD | INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_DONT_CACHE);
			if (msg)
				nbDownload++;

			msg += callback.StepIt();
		}

		pConnection->Close();
		pSession->Close();


		callback.AddMessage("Number of images downloaded: " + ToString(nbDownload));
		callback.PopTask();


		return msg;
	}
Example #8
0
//-----------------------------------------------------------------------------
// The mesh class constructor.
//-----------------------------------------------------------------------------
Mesh::Mesh( char *name, char *path ) : Resource< Mesh >( name, path )
{
	// Create the list of reference points.
	m_frames = new LinkedList< Frame >;
	m_refPoints = new LinkedList< Frame >;

	// Load the mesh's frame hierarchy.
	AllocateHierarchy ah;
	D3DXLoadMeshHierarchyFromXA( GetFilename(), D3DXMESH_MANAGED, g_engine->GetDevice(), &ah, NULL, (D3DXFRAME**)&m_firstFrame, &m_animationController );

	// Disable all the animation tracks initially.
	if( m_animationController != NULL )
		for( unsigned long t = 0; t < m_animationController->GetMaxNumTracks(); ++t )
			m_animationController->SetTrackEnable( t, false );

	// Invalidate the bone transformation matrices array.
	m_boneMatrices = NULL;
	m_totalBoneMatrices = 0;

	// Prepare the frame hierarchy.
	PrepareFrame( m_firstFrame );

	// Allocate memory for the bone matrices.
	m_boneMatrices = new D3DXMATRIX[m_totalBoneMatrices];

	// Create a static (non-animated) version of the mesh.
	m_staticMesh = new MeshContainer;
	ZeroMemory( m_staticMesh, sizeof( MeshContainer ) );

	// Load the mesh.
	ID3DXBuffer *materialBuffer, *adjacencyBuffer;
	D3DXLoadMeshFromXA( GetFilename(), D3DXMESH_MANAGED, g_engine->GetDevice(), &adjacencyBuffer, &materialBuffer, NULL, &m_staticMesh->NumMaterials, &m_staticMesh->originalMesh );

	// Optimise the mesh for better rendering performance.
	m_staticMesh->originalMesh->OptimizeInplace( D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE, (DWORD*)adjacencyBuffer->GetBufferPointer(), NULL, NULL, NULL );

	// Finished with the adjacency buffer, so destroy it.
	SAFE_RELEASE( adjacencyBuffer );

	// Check if the mesh has any materials.
	if( m_staticMesh->NumMaterials > 0 )
	{
		// Create the array of materials.
		m_staticMesh->materials = new Material*[m_staticMesh->NumMaterials];

		// Get the list of materials from the material buffer.
		D3DXMATERIAL *materials = (D3DXMATERIAL*)materialBuffer->GetBufferPointer();

		// Load each material into the array via the material manager.
		for( unsigned long m = 0; m < m_staticMesh->NumMaterials; m++ )
		{
			// Ensure the material has a texture.
			if( materials[m].pTextureFilename )
			{
				// Get the name of the material's script and load it.
				char *name = new char[strlen( materials[m].pTextureFilename ) + 5];
				sprintf( name, "%s.txt", materials[m].pTextureFilename );
				m_staticMesh->materials[m] = g_engine->GetMaterialManager()->Add( name, GetPath() );
				SAFE_DELETE_ARRAY( name );
			}
			else
				m_staticMesh->materials[m] = NULL;
		}
	}

	// Create the bounding volume around the mesh.
	BoundingVolumeFromMesh( m_staticMesh->originalMesh );

	// Destroy the material buffer.
	SAFE_RELEASE( materialBuffer );

	// Create a vertex array and an array of indices into the vertex array.
	m_vertices = new Vertex[m_staticMesh->originalMesh->GetNumVertices()];
	m_indices = new unsigned short[m_staticMesh->originalMesh->GetNumFaces() * 3];

	// Use the arrays to store a local copy of the static mesh's vertices and
	// indices so that they can be used by the scene manager on the fly.
	Vertex* verticesPtr;
	m_staticMesh->originalMesh->LockVertexBuffer( 0, (void**)&verticesPtr );
	unsigned short *indicesPtr;
	m_staticMesh->originalMesh->LockIndexBuffer( 0, (void**)&indicesPtr );

	memcpy( m_vertices, verticesPtr, VERTEX_FVF_SIZE * m_staticMesh->originalMesh->GetNumVertices() );
	memcpy( m_indices, indicesPtr, sizeof( unsigned short ) * m_staticMesh->originalMesh->GetNumFaces() * 3 );

	m_staticMesh->originalMesh->UnlockVertexBuffer();
	m_staticMesh->originalMesh->UnlockIndexBuffer();
}
Example #9
0
//-----------------------------------------------------------------------------
// Prepares the given frame.
//-----------------------------------------------------------------------------
void Mesh::PrepareFrame( Frame *frame )
{
	m_frames->Add( frame );

	// Check if this frame is actually a reference point.
	if( strncmp( "rp_", frame->Name, 3 ) == 0 )
		m_refPoints->Add( frame );

	// Set the initial final transformation.
	frame->finalTransformationMatrix = frame->TransformationMatrix;

	// Prepare the frame's mesh container, if it has one.
	if( frame->pMeshContainer != NULL )
	{
		MeshContainer *meshContainer = (MeshContainer*)frame->pMeshContainer;

		// Check if this mesh is a skinned mesh.
		if( meshContainer->pSkinInfo != NULL )
		{
			// Create the array of bone matrix pointers.
			meshContainer->boneMatrixPointers = new D3DXMATRIX*[meshContainer->pSkinInfo->GetNumBones()];

			// Set up the pointers to the mesh's bone transformation matrices.
			for( unsigned long b = 0; b < meshContainer->pSkinInfo->GetNumBones(); b++ )
			{
				Frame *bone = (Frame*)D3DXFrameFind( m_firstFrame, meshContainer->pSkinInfo->GetBoneName( b ) );
				if( bone == NULL )
					continue;

				meshContainer->boneMatrixPointers[b] = &bone->finalTransformationMatrix;
			}

			// Keep track of the maximum bones out of all the mesh containers.
			if( m_totalBoneMatrices < meshContainer->pSkinInfo->GetNumBones() )
				m_totalBoneMatrices = meshContainer->pSkinInfo->GetNumBones();
		}

		// Check if the mesh has any materials.
		if( meshContainer->NumMaterials > 0 )
		{
			// Load all the materials in via the material manager.
			for( unsigned long m = 0; m < meshContainer->NumMaterials; m++ )
			{
				// Ensure the material has a texture.
				if( meshContainer->materialNames[m] != NULL )
				{
					// Get the name of the material's script and load it.
					char *name = new char[strlen( meshContainer->materialNames[m] ) + 5];
					sprintf( name, "%s.txt", meshContainer->materialNames[m] );
					meshContainer->materials[m] = g_engine->GetMaterialManager()->Add( name, GetPath() );
					SAFE_DELETE_ARRAY( name );
				}
			}
		}
	}

	// Prepare the frame's siblings.
	if( frame->pFrameSibling != NULL )
		PrepareFrame( (Frame*)frame->pFrameSibling );

	// Prepare the frame's children.
	if( frame->pFrameFirstChild != NULL )
		PrepareFrame( (Frame*)frame->pFrameFirstChild );
}
Example #10
0
nfsstat3 CNFS3Prog::ProcedureSETATTR(void)
{
    char *path;
    sattr3 new_attributes;
    sattrguard3 guard;
    wcc_data obj_wcc;
    nfsstat3 stat;
    int nMode;
    FILE *pFile;
    HANDLE hFile;
    FILETIME fileTime;
    SYSTEMTIME systemTime;

    PrintLog("SETATTR");
    path = GetPath();
    Read(&new_attributes);
    Read(&guard);
    stat = CheckFile(path);
    obj_wcc.before.attributes_follow = GetFileAttributesForNFS(path, &obj_wcc.before.attributes);

    if (stat == NFS3_OK) {
        if (new_attributes.mode.set_it) {
            nMode = 0;

            if ((new_attributes.mode.mode & 0x100) != 0) {
                nMode |= S_IREAD;
            }

            // Always set read and write permissions (deliberately implemented this way)
            // if ((new_attributes.mode.mode & 0x80) != 0) {
            nMode |= S_IWRITE;
            // }

            // S_IEXEC is not availabile on windows
            // if ((new_attributes.mode.mode & 0x40) != 0) {
            //     nMode |= S_IEXEC;
            // }

            if (_chmod(path, nMode) != 0) {
                stat = NFS3ERR_INVAL;
            } else {

            }
        }   

        // deliberately not implemented because we cannot reflect uid/gid on windows (easliy)
        if (new_attributes.uid.set_it){}
        if (new_attributes.gid.set_it){}

        // deliberately not implemented
        if (new_attributes.mtime.set_it == SET_TO_CLIENT_TIME){}
        if (new_attributes.atime.set_it == SET_TO_CLIENT_TIME){}

        if (new_attributes.mtime.set_it == SET_TO_SERVER_TIME || new_attributes.atime.set_it == SET_TO_SERVER_TIME){
            hFile = CreateFile(path, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
            if (hFile != INVALID_HANDLE_VALUE) {
                GetSystemTime(&systemTime);
                SystemTimeToFileTime(&systemTime, &fileTime);
                if (new_attributes.mtime.set_it == SET_TO_SERVER_TIME){
                    SetFileTime(hFile, NULL, NULL, &fileTime);
                }
                if (new_attributes.atime.set_it == SET_TO_SERVER_TIME){
                    SetFileTime(hFile, NULL, &fileTime, NULL);
                }
            }
            CloseHandle(hFile);
        }

        if (new_attributes.size.set_it){
            pFile = _fsopen(path, "r+b", _SH_DENYWR);
            int filedes = _fileno(pFile);
            _chsize_s(filedes, new_attributes.size.size);
            fclose(pFile);
        }
    }

    obj_wcc.after.attributes_follow = GetFileAttributesForNFS(path, &obj_wcc.after.attributes);

    Write(&stat);
    Write(&obj_wcc);

    return stat;
}
Example #11
0
nfsstat3 CNFS3Prog::ProcedureREADLINK(void)
{
    PrintLog("READLINK");
    char *path;
    char *pMBBuffer = 0;

    post_op_attr symlink_attributes;
    nfspath3 data = nfspath3();

    //opaque data;
    nfsstat3 stat;

    HANDLE hFile;
    REPARSE_DATA_BUFFER *lpOutBuffer;
    lpOutBuffer = (REPARSE_DATA_BUFFER*)malloc(MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
    DWORD bytesReturned;

    path = GetPath();
    stat = CheckFile(path);
    if (stat == NFS3_OK) {

        hFile = CreateFile(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_REPARSE_POINT | FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);

        if (hFile == INVALID_HANDLE_VALUE) {
            stat = NFS3ERR_IO;
        }
        else
        {
            lpOutBuffer = (REPARSE_DATA_BUFFER*)malloc(MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
            if (!lpOutBuffer) {
                stat = NFS3ERR_IO;
            }
            else {
                DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, NULL, 0, lpOutBuffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &bytesReturned, NULL);

                if (lpOutBuffer->ReparseTag == IO_REPARSE_TAG_SYMLINK || lpOutBuffer->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
                {
                    if (lpOutBuffer->ReparseTag == IO_REPARSE_TAG_SYMLINK)
                    {
                        size_t plen = lpOutBuffer->SymbolicLinkReparseBuffer.PrintNameLength / sizeof(WCHAR);
                        pMBBuffer = (char *)malloc((plen + 1));
                        WCHAR *szPrintName = new WCHAR[plen + 1];
                        wcsncpy_s(szPrintName, plen + 1, &lpOutBuffer->SymbolicLinkReparseBuffer.PathBuffer[lpOutBuffer->SymbolicLinkReparseBuffer.PrintNameOffset / sizeof(WCHAR)], plen);
                        szPrintName[plen] = 0;
                        size_t i;
                        wcstombs_s(&i, pMBBuffer, (plen + 1), szPrintName, (plen + 1));
                        // TODO: Revisit with cleaner solution
                        if (!PathIsRelative(pMBBuffer))
                        {
                            std::string strFromChar;
                            strFromChar.append("\\\\?\\");
                            strFromChar.append(pMBBuffer);
                            char *target = _strdup(strFromChar.c_str());
                            // remove last folder
                            char *pos = strrchr(path, '\\');
                            if (pos != NULL) {
                                *pos = '\0';
                            }
                            PathRelativePathTo(pMBBuffer, path, FILE_ATTRIBUTE_DIRECTORY, target, FILE_ATTRIBUTE_DIRECTORY);
                        }
                    }

                    // TODO: Revisit with cleaner solution
                    if (lpOutBuffer->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
                    {
                        size_t slen = lpOutBuffer->MountPointReparseBuffer.SubstituteNameLength / sizeof(WCHAR);
                        pMBBuffer = (char *)malloc((slen + 1));
                        WCHAR *szSubName = new WCHAR[slen + 1];
                        wcsncpy_s(szSubName, slen + 1, &lpOutBuffer->MountPointReparseBuffer.PathBuffer[lpOutBuffer->MountPointReparseBuffer.SubstituteNameOffset / sizeof(WCHAR)], slen);
                        szSubName[slen] = 0;
                        std::wstring wStringTemp(szSubName);
                        std::string target(wStringTemp.begin(), wStringTemp.end());
                        target.erase(0, 2);
                        target.insert(0, 2, '\\');
                        // remove last folder, see above
                        char *pos = strrchr(path, '\\');
                        if (pos != NULL) {
                            *pos = '\0';
                        }
                        PathRelativePathTo(pMBBuffer, path, FILE_ATTRIBUTE_DIRECTORY, target.c_str(), FILE_ATTRIBUTE_DIRECTORY);
                    }

                    // write path always with / separator, so windows created symlinks work too
                    std::string strFromChar;
                    strFromChar.append(pMBBuffer);
                    std::replace(strFromChar.begin(), strFromChar.end(), '\\', '/');
                    char *result = _strdup(strFromChar.c_str());

                    data.Set(result);
                    free(pMBBuffer);
                    free(result);
                }
                free(lpOutBuffer);
            }
        }
        CloseHandle(hFile);
    }

    symlink_attributes.attributes_follow = GetFileAttributesForNFS(path, &symlink_attributes.attributes);

    Write(&stat);
    Write(&symlink_attributes);
    if (stat == NFS3_OK) {
        Write(&data);
    }

    return stat;
}
Example #12
0
nfsstat3 CNFS3Prog::ProcedureREADDIRPLUS(void)
{
    char *path;
    cookie3 cookie;
    cookieverf3 cookieverf;
    count3 dircount, maxcount;
    post_op_attr dir_attributes;
    fileid3 fileid;
    filename3 name;
    post_op_attr name_attributes;
    post_op_fh3 name_handle;
    bool eof;
    nfsstat3 stat;
    char filePath[MAXPATHLEN];
    int handle, nFound;
    struct _finddata_t fileinfo;
    unsigned int i, j;
    bool bFollows;

    PrintLog("READDIRPLUS");
    path = GetPath();
    Read(&cookie);
    Read(&cookieverf);
    Read(&dircount);
    Read(&maxcount);
    stat = CheckFile(path);

    if (stat == NFS3_OK) {
        dir_attributes.attributes_follow = GetFileAttributesForNFS(path, &dir_attributes.attributes);
        
        if (!dir_attributes.attributes_follow) {
            stat = NFS3ERR_IO;
        }
    }

    Write(&stat);
    Write(&dir_attributes);

    if (stat == NFS3_OK) {
        Write(&cookieverf);
        sprintf_s(filePath, "%s\\*", path);
        handle = _findfirst(filePath, &fileinfo);
        eof = true;

        if (handle) {
            nFound = 0;

            for (i = (unsigned int)cookie; i > 0; i--) {
                nFound = _findnext(handle, &fileinfo);
            }              

            if (nFound == 0) {
                bFollows = true;
                j = 10;

                do {
                    Write(&bFollows); //value follows
                    sprintf_s(filePath, "%s\\%s", path, fileinfo.name);
                    fileid = GetFileID(filePath);
                    Write(&fileid); //file id
                    name.Set(fileinfo.name);
                    Write(&name); //name
                    ++cookie;
                    Write(&cookie); //cookie
                    name_attributes.attributes_follow = GetFileAttributesForNFS(filePath, &name_attributes.attributes);
                    Write(&name_attributes);
                    name_handle.handle_follows = GetFileHandle(filePath, &name_handle.handle);
                    Write(&name_handle);

                    if (--j == 0) {
                        eof = false;
                        break;
                    }
                } while (_findnext(handle, &fileinfo) == 0);
            }

            _findclose(handle);
        }

        bFollows = false;
        Write(&bFollows); //value follows
        Write(&eof); //eof
    }

    return stat;
}
Example #13
0
nfsstat3 CNFS3Prog::ProcedureREADDIR(void)
{
    char *path;
    cookie3 cookie;
    cookieverf3 cookieverf;
    count3 count;
    post_op_attr dir_attributes;
    fileid3 fileid;
    filename3 name;
    bool eof;
    bool bFollows;
    nfsstat3 stat;
    char filePath[MAXPATHLEN];
    int handle;
    struct _finddata_t fileinfo;

    PrintLog("READDIR");
    path = GetPath();
    Read(&cookie);
    Read(&cookieverf);
    Read(&count);
    stat = CheckFile(path);

    if (stat == NFS3_OK) {
        dir_attributes.attributes_follow = GetFileAttributesForNFS(path, &dir_attributes.attributes);

        if (!dir_attributes.attributes_follow) {
            stat = NFS3ERR_IO;
        }    
    }

    Write(&stat);
    Write(&dir_attributes);

    if (stat == NFS3_OK) {
        Write(&cookieverf);
        sprintf_s(filePath, "%s\\*", path);
        cookie = 0;
        eof = false;
        handle = _findfirst(filePath, &fileinfo);
        bFollows = true;

        if (handle) {
            do {
                Write(&bFollows); //value follows
                sprintf_s(filePath, "%s\\%s", path, fileinfo.name);
                fileid = GetFileID(filePath);
                Write(&fileid); //file id
                name.Set(fileinfo.name);
                Write(&name); //name
                ++cookie;
                Write(&cookie); //cookie
            } while (_findnext(handle, &fileinfo) == 0);

            _findclose(handle);
        }

        bFollows = false;
        Write(&bFollows);
        eof = true;
        Write(&eof); //eof
    }

    return stat;
}
NS_IMETHODIMP
nsLocalFile::CreateUnique(uint32_t aType, uint32_t aAttributes)
{
  nsresult rv;
  bool longName;

#ifdef XP_WIN
  nsAutoString pathName, leafName, rootName, suffix;
  rv = GetPath(pathName);
#else
  nsAutoCString pathName, leafName, rootName, suffix;
  rv = GetNativePath(pathName);
#endif
  if (NS_FAILED(rv)) {
    return rv;
  }

  longName = (pathName.Length() + kMaxSequenceNumberLength >
              kMaxFilenameLength);
  if (!longName) {
    rv = Create(aType, aAttributes);
    if (rv != NS_ERROR_FILE_ALREADY_EXISTS) {
      return rv;
    }
  }

#ifdef XP_WIN
  rv = GetLeafName(leafName);
  if (NS_FAILED(rv)) {
    return rv;
  }

  const int32_t lastDot = leafName.RFindChar(char16_t('.'));
#else
  rv = GetNativeLeafName(leafName);
  if (NS_FAILED(rv)) {
    return rv;
  }

  const int32_t lastDot = leafName.RFindChar('.');
#endif

  if (lastDot == kNotFound) {
    rootName = leafName;
  } else {
    suffix = Substring(leafName, lastDot);      // include '.'
    rootName = Substring(leafName, 0, lastDot); // strip suffix and dot
  }

  if (longName) {
    int32_t maxRootLength = (kMaxFilenameLength -
                             (pathName.Length() - leafName.Length()) -
                             suffix.Length() - kMaxSequenceNumberLength);

    // We cannot create an item inside a directory whose name is too long.
    // Also, ensure that at least one character remains after we truncate
    // the root name, as we don't want to end up with an empty leaf name.
    if (maxRootLength < 2) {
      return NS_ERROR_FILE_UNRECOGNIZED_PATH;
    }

#ifdef XP_WIN
    // ensure that we don't cut the name in mid-UTF16-character
    rootName.SetLength(NS_IS_LOW_SURROGATE(rootName[maxRootLength]) ?
                       maxRootLength - 1 : maxRootLength);
    SetLeafName(rootName + suffix);
#else
    if (NS_IsNativeUTF8()) {
      // ensure that we don't cut the name in mid-UTF8-character
      // (assume the name is valid UTF8 to begin with)
      while (UTF8traits::isInSeq(rootName[maxRootLength])) {
        --maxRootLength;
      }

      // Another check to avoid ending up with an empty leaf name.
      if (maxRootLength == 0 && suffix.IsEmpty()) {
        return NS_ERROR_FILE_UNRECOGNIZED_PATH;
      }
    }

    rootName.SetLength(maxRootLength);
    SetNativeLeafName(rootName + suffix);
#endif
    nsresult rvCreate = Create(aType, aAttributes);
    if (rvCreate != NS_ERROR_FILE_ALREADY_EXISTS) {
      return rvCreate;
    }
  }

  for (int indx = 1; indx < 10000; ++indx) {
    // start with "Picture-1.jpg" after "Picture.jpg" exists
#ifdef XP_WIN
    SetLeafName(rootName +
                NS_ConvertASCIItoUTF16(nsPrintfCString("-%d", indx)) +
                suffix);
#else
    SetNativeLeafName(rootName + nsPrintfCString("-%d", indx) + suffix);
#endif
    rv = Create(aType, aAttributes);
    if (NS_SUCCEEDED(rv) || rv != NS_ERROR_FILE_ALREADY_EXISTS) {
      return rv;
    }
  }

  // The disk is full, sort of
  return NS_ERROR_FILE_TOO_BIG;
}
void UBlinkyChaseBehaviorComponent::FindPath()
{
	auto Owner = static_cast<AGhost*>(GetOwner());
	auto PathFollower = Owner->GetPathFollowingComponent();

	TActorIterator<APacmanPlayer> PlayerIt(GetWorld());

	GNavigationSystem->FindPathToLocation(Owner->GetActorLocation(), PlayerIt->GetActorLocation(), Owner->GetActorForwardVector(), PathFollower->GetPath());
	PathFollower->StartPathFollowing();
}
bool TextureCube::BeginLoad(Deserializer& source)
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();

    // In headless mode, do not actually load the texture, just return success
    if (!graphics_)
        return true;

    // If device is lost, retry later
    if (graphics_->IsDeviceLost())
    {
        ATOMIC_LOGWARNING("Texture load while device is lost");
        dataPending_ = true;
        return true;
    }

    cache->ResetDependencies(this);

    String texPath, texName, texExt;
    SplitPath(GetName(), texPath, texName, texExt);

    loadParameters_ = (new XMLFile(context_));
    if (!loadParameters_->Load(source))
    {
        loadParameters_.Reset();
        return false;
    }

    loadImages_.Clear();

    XMLElement textureElem = loadParameters_->GetRoot();
    XMLElement imageElem = textureElem.GetChild("image");
    // Single image and multiple faces with layout
    if (imageElem)
    {
        String name = imageElem.GetAttribute("name");
        // If path is empty, add the XML file path
        if (GetPath(name).Empty())
            name = texPath + name;

        SharedPtr<Image> image = cache->GetTempResource<Image>(name);
        if (!image)
            return false;

        int faceWidth, faceHeight;
        loadImages_.Resize(MAX_CUBEMAP_FACES);

        if (image->IsCubemap())
        {
            loadImages_[FACE_POSITIVE_X] = image;
            loadImages_[FACE_NEGATIVE_X] = loadImages_[FACE_POSITIVE_X]->GetNextSibling();
            loadImages_[FACE_POSITIVE_Y] = loadImages_[FACE_NEGATIVE_X]->GetNextSibling();
            loadImages_[FACE_NEGATIVE_Y] = loadImages_[FACE_POSITIVE_Y]->GetNextSibling();
            loadImages_[FACE_POSITIVE_Z] = loadImages_[FACE_NEGATIVE_Y]->GetNextSibling();
            loadImages_[FACE_NEGATIVE_Z] = loadImages_[FACE_POSITIVE_Z]->GetNextSibling();
        }
        else
        {
        
            CubeMapLayout layout =
                (CubeMapLayout)GetStringListIndex(imageElem.GetAttribute("layout").CString(), cubeMapLayoutNames, CML_HORIZONTAL);
            
            switch (layout)
            {
            case CML_HORIZONTAL:
                faceWidth = image->GetWidth() / MAX_CUBEMAP_FACES;
                faceHeight = image->GetHeight();
                loadImages_[FACE_POSITIVE_Z] = GetTileImage(image, 0, 0, faceWidth, faceHeight);
                loadImages_[FACE_POSITIVE_X] = GetTileImage(image, 1, 0, faceWidth, faceHeight);
                loadImages_[FACE_NEGATIVE_Z] = GetTileImage(image, 2, 0, faceWidth, faceHeight);
                loadImages_[FACE_NEGATIVE_X] = GetTileImage(image, 3, 0, faceWidth, faceHeight);
                loadImages_[FACE_POSITIVE_Y] = GetTileImage(image, 4, 0, faceWidth, faceHeight);
                loadImages_[FACE_NEGATIVE_Y] = GetTileImage(image, 5, 0, faceWidth, faceHeight);
                break;

            case CML_HORIZONTALNVIDIA:
                faceWidth = image->GetWidth() / MAX_CUBEMAP_FACES;
                faceHeight = image->GetHeight();
                for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
                    loadImages_[i] = GetTileImage(image, i, 0, faceWidth, faceHeight);
                break;

            case CML_HORIZONTALCROSS:
                faceWidth = image->GetWidth() / 4;
                faceHeight = image->GetHeight() / 3;
                loadImages_[FACE_POSITIVE_Y] = GetTileImage(image, 1, 0, faceWidth, faceHeight);
                loadImages_[FACE_NEGATIVE_X] = GetTileImage(image, 0, 1, faceWidth, faceHeight);
                loadImages_[FACE_POSITIVE_Z] = GetTileImage(image, 1, 1, faceWidth, faceHeight);
                loadImages_[FACE_POSITIVE_X] = GetTileImage(image, 2, 1, faceWidth, faceHeight);
                loadImages_[FACE_NEGATIVE_Z] = GetTileImage(image, 3, 1, faceWidth, faceHeight);
                loadImages_[FACE_NEGATIVE_Y] = GetTileImage(image, 1, 2, faceWidth, faceHeight);
                break;

            case CML_VERTICALCROSS:
                faceWidth = image->GetWidth() / 3;
                faceHeight = image->GetHeight() / 4;
                loadImages_[FACE_POSITIVE_Y] = GetTileImage(image, 1, 0, faceWidth, faceHeight);
                loadImages_[FACE_NEGATIVE_X] = GetTileImage(image, 0, 1, faceWidth, faceHeight);
                loadImages_[FACE_POSITIVE_Z] = GetTileImage(image, 1, 1, faceWidth, faceHeight);
                loadImages_[FACE_POSITIVE_X] = GetTileImage(image, 2, 1, faceWidth, faceHeight);
                loadImages_[FACE_NEGATIVE_Y] = GetTileImage(image, 1, 2, faceWidth, faceHeight);
                loadImages_[FACE_NEGATIVE_Z] = GetTileImage(image, 1, 3, faceWidth, faceHeight);
                if (loadImages_[FACE_NEGATIVE_Z])
                {
                    loadImages_[FACE_NEGATIVE_Z]->FlipVertical();
                    loadImages_[FACE_NEGATIVE_Z]->FlipHorizontal();
                }
                break;

            case CML_BLENDER:
                faceWidth = image->GetWidth() / 3;
                faceHeight = image->GetHeight() / 2;
                loadImages_[FACE_NEGATIVE_X] = GetTileImage(image, 0, 0, faceWidth, faceHeight);
                loadImages_[FACE_NEGATIVE_Z] = GetTileImage(image, 1, 0, faceWidth, faceHeight);
                loadImages_[FACE_POSITIVE_X] = GetTileImage(image, 2, 0, faceWidth, faceHeight);
                loadImages_[FACE_NEGATIVE_Y] = GetTileImage(image, 0, 1, faceWidth, faceHeight);
                loadImages_[FACE_POSITIVE_Y] = GetTileImage(image, 1, 1, faceWidth, faceHeight);
                loadImages_[FACE_POSITIVE_Z] = GetTileImage(image, 2, 1, faceWidth, faceHeight);
                break;
            }
        }
    }
    // Face per image
    else
    {
        XMLElement faceElem = textureElem.GetChild("face");
        while (faceElem)
        {
            String name = faceElem.GetAttribute("name");

            // If path is empty, add the XML file path
            if (GetPath(name).Empty())
                name = texPath + name;

            loadImages_.Push(cache->GetTempResource<Image>(name));
            cache->StoreResourceDependency(this, name);

            faceElem = faceElem.GetNext("face");
        }
    }

    // Precalculate mip levels if async loading
    if (GetAsyncLoadState() == ASYNC_LOADING)
    {
        for (unsigned i = 0; i < loadImages_.Size(); ++i)
        {
            if (loadImages_[i])
                loadImages_[i]->PrecalculateLevels();
        }
    }

    return true;
}
Example #17
0
void LoadMesh(const ea::string& inputFileName, bool generateTangents, bool splitSubMeshes, bool exportMorphs)
{
    File meshFileSource(context_);
    meshFileSource.Open(inputFileName);
    if (!meshFile_->Load(meshFileSource))
        ErrorExit("Could not load input file " + inputFileName);

    XMLElement root = meshFile_->GetRoot("mesh");
    XMLElement subMeshes = root.GetChild("submeshes");
    XMLElement skeletonLink = root.GetChild("skeletonlink");
    if (root.IsNull())
        ErrorExit("Could not load input file " + inputFileName);

    ea::string skeletonName = skeletonLink.GetAttribute("name");
    if (!skeletonName.empty())
        LoadSkeleton(GetPath(inputFileName) + GetFileName(skeletonName) + ".skeleton.xml");

    // Check whether there's benefit of avoiding 32bit indices by splitting each submesh into own buffer
    XMLElement subMesh = subMeshes.GetChild("submesh");
    unsigned totalVertices = 0;
    unsigned maxSubMeshVertices = 0;
    while (subMesh)
    {
        materialNames_.push_back(subMesh.GetAttribute("material"));
        XMLElement geometry = subMesh.GetChild("geometry");
        if (geometry)
        {
            unsigned vertices = geometry.GetInt("vertexcount");
            totalVertices += vertices;
            if (maxSubMeshVertices < vertices)
                maxSubMeshVertices = vertices;
        }
        ++numSubMeshes_;

        subMesh = subMesh.GetNext("submesh");
    }

    XMLElement sharedGeometry = root.GetChild("sharedgeometry");
    if (sharedGeometry)
    {
        unsigned vertices = sharedGeometry.GetInt("vertexcount");
        totalVertices += vertices;
        if (maxSubMeshVertices < vertices)
            maxSubMeshVertices = vertices;
    }

    if (!sharedGeometry && (splitSubMeshes || (totalVertices > 65535 && maxSubMeshVertices <= 65535)))
    {
        useOneBuffer_ = false;
        vertexBuffers_.resize(numSubMeshes_);
        indexBuffers_.resize(numSubMeshes_);
    }
    else
    {
        vertexBuffers_.resize(1);
        indexBuffers_.resize(1);
    }

    subMesh = subMeshes.GetChild("submesh");
    unsigned indexStart = 0;
    unsigned vertexStart = 0;
    unsigned subMeshIndex = 0;

    ea::vector<unsigned> vertexStarts;
    vertexStarts.resize(numSubMeshes_);

    while (subMesh)
    {
        XMLElement geometry = subMesh.GetChild("geometry");
        XMLElement faces = subMesh.GetChild("faces");

        // If no submesh vertexbuffer, process the shared geometry, but do it only once
        unsigned vertices = 0;
        if (!geometry)
        {
            vertexStart = 0;
            if (!subMeshIndex)
                geometry = root.GetChild("sharedgeometry");
        }

        if (geometry)
            vertices = geometry.GetInt("vertexcount");

        ModelSubGeometryLodLevel subGeometryLodLevel;
        ModelVertexBuffer* vBuf;
        ModelIndexBuffer* iBuf;

        if (useOneBuffer_)
        {
            vBuf = &vertexBuffers_[0];
            if (vertices)
                vBuf->vertices_.resize(vertexStart + vertices);
            iBuf = &indexBuffers_[0];

            subGeometryLodLevel.vertexBuffer_ = 0;
            subGeometryLodLevel.indexBuffer_ = 0;
        }
        else
        {
            vertexStart = 0;
            indexStart = 0;

            vBuf = &vertexBuffers_[subMeshIndex];
            vBuf->vertices_.resize(vertices);
            iBuf = &indexBuffers_[subMeshIndex];

            subGeometryLodLevel.vertexBuffer_ = subMeshIndex;
            subGeometryLodLevel.indexBuffer_ = subMeshIndex;
        }

        // Store the start vertex for later use
        vertexStarts[subMeshIndex] = vertexStart;

        // Ogre may have multiple buffers in one submesh. These will be merged into one
        XMLElement bufferDef;
        if (geometry)
            bufferDef = geometry.GetChild("vertexbuffer");

        while (bufferDef)
        {
            if (bufferDef.HasAttribute("positions"))
                vBuf->elementMask_ |= MASK_POSITION;
            if (bufferDef.HasAttribute("normals"))
                vBuf->elementMask_ |= MASK_NORMAL;
            if (bufferDef.HasAttribute("texture_coords"))
            {
                vBuf->elementMask_ |= MASK_TEXCOORD1;
                if (bufferDef.GetInt("texture_coords") > 1)
                    vBuf->elementMask_ |= MASK_TEXCOORD2;
            }

            unsigned vertexNum = vertexStart;
            if (vertices)
            {
                XMLElement vertex = bufferDef.GetChild("vertex");
                while (vertex)
                {
                    XMLElement position = vertex.GetChild("position");
                    if (position)
                    {
                        // Convert from right- to left-handed
                        float x = position.GetFloat("x");
                        float y = position.GetFloat("y");
                        float z = position.GetFloat("z");
                        Vector3 vec(x, y, -z);

                        vBuf->vertices_[vertexNum].position_ = vec;
                        boundingBox_.Merge(vec);
                    }
                    XMLElement normal = vertex.GetChild("normal");
                    if (normal)
                    {
                        // Convert from right- to left-handed
                        float x = normal.GetFloat("x");
                        float y = normal.GetFloat("y");
                        float z = normal.GetFloat("z");
                        Vector3 vec(x, y, -z);

                        vBuf->vertices_[vertexNum].normal_ = vec;
                    }
                    XMLElement uv = vertex.GetChild("texcoord");
                    if (uv)
                    {
                        float x = uv.GetFloat("u");
                        float y = uv.GetFloat("v");
                        Vector2 vec(x, y);

                        vBuf->vertices_[vertexNum].texCoord1_ = vec;

                        if (vBuf->elementMask_ & MASK_TEXCOORD2)
                        {
                            uv = uv.GetNext("texcoord");
                            if (uv)
                            {
                                float x = uv.GetFloat("u");
                                float y = uv.GetFloat("v");
                                Vector2 vec(x, y);

                                vBuf->vertices_[vertexNum].texCoord2_ = vec;
                            }
                        }
                    }

                    vertexNum++;
                    vertex = vertex.GetNext("vertex");
                }
            }

            bufferDef = bufferDef.GetNext("vertexbuffer");
        }

        unsigned triangles = faces.GetInt("count");
        unsigned indices = triangles * 3;

        XMLElement triangle = faces.GetChild("face");
        while (triangle)
        {
            unsigned v1 = triangle.GetInt("v1");
            unsigned v2 = triangle.GetInt("v2");
            unsigned v3 = triangle.GetInt("v3");
            iBuf->indices_.push_back(v3 + vertexStart);
            iBuf->indices_.push_back(v2 + vertexStart);
            iBuf->indices_.push_back(v1 + vertexStart);
            triangle = triangle.GetNext("face");
        }

        subGeometryLodLevel.indexStart_ = indexStart;
        subGeometryLodLevel.indexCount_ = indices;
        if (vertexStart + vertices > 65535)
            iBuf->indexSize_ = sizeof(unsigned);

        XMLElement boneAssignments = subMesh.GetChild("boneassignments");
        if (bones_.size())
        {
            if (boneAssignments)
            {
                XMLElement boneAssignment = boneAssignments.GetChild("vertexboneassignment");
                while (boneAssignment)
                {
                    unsigned vertex = boneAssignment.GetInt("vertexindex") + vertexStart;
                    unsigned bone = boneAssignment.GetInt("boneindex");
                    float weight = boneAssignment.GetFloat("weight");

                    BoneWeightAssignment assign{static_cast<unsigned char>(bone), weight};
                    // Source data might have 0 weights. Disregard these
                    if (assign.weight_ > 0.0f)
                    {
                        subGeometryLodLevel.boneWeights_[vertex].push_back(assign);

                        // Require skinning weight to be sufficiently large before vertex contributes to bone hitbox
                        if (assign.weight_ > 0.33f)
                        {
                            // Check distance of vertex from bone to get bone max. radius information
                            Vector3 bonePos = bones_[bone].derivedPosition_;
                            Vector3 vertexPos = vBuf->vertices_[vertex].position_;
                            float distance = (bonePos - vertexPos).Length();
                            if (distance > bones_[bone].radius_)
                            {
                                bones_[bone].collisionMask_ |= 1;
                                bones_[bone].radius_ = distance;
                            }
                            // Build the hitbox for the bone
                            bones_[bone].boundingBox_.Merge(bones_[bone].inverseWorldTransform_ * (vertexPos));
                            bones_[bone].collisionMask_ |= 2;
                        }
                    }
                    boneAssignment = boneAssignment.GetNext("vertexboneassignment");
                }
            }

            if ((subGeometryLodLevel.boneWeights_.size()) && bones_.size())
            {
                vBuf->elementMask_ |= MASK_BLENDWEIGHTS | MASK_BLENDINDICES;
                bool sorted = false;

                // If amount of bones is larger than supported by HW skinning, must remap per submesh
                if (bones_.size() > maxBones_)
                {
                    ea::unordered_map<unsigned, unsigned> usedBoneMap;
                    unsigned remapIndex = 0;
                    for (auto i = subGeometryLodLevel.boneWeights_.begin(); i !=
                        subGeometryLodLevel.boneWeights_.end(); ++i)
                    {
                        // Sort the bone assigns by weight
                        ea::quick_sort(i->second.begin(), i->second.end(), CompareWeights);

                        // Use only the first 4 weights
                        for (unsigned j = 0; j < i->second.size() && j < 4; ++j)
                        {
                            unsigned originalIndex = i->second[j].boneIndex_;
                            if (!usedBoneMap.contains(originalIndex))
                            {
                                usedBoneMap[originalIndex] = remapIndex;
                                remapIndex++;
                            }
                            i->second[j].boneIndex_ = usedBoneMap[originalIndex];
                        }
                    }

                    // If still too many bones in one subgeometry, error
                    if (usedBoneMap.size() > maxBones_)
                        ErrorExit("Too many bones (limit " + ea::to_string(maxBones_) + ") in submesh " + ea::to_string(subMeshIndex + 1));

                    // Write mapping of vertex buffer bone indices to original bone indices
                    subGeometryLodLevel.boneMapping_.resize(usedBoneMap.size());
                    for (auto j = usedBoneMap.begin(); j != usedBoneMap.end(); ++j)
                        subGeometryLodLevel.boneMapping_[j->second] = j->first;

                    sorted = true;
                }

                for (auto i = subGeometryLodLevel.boneWeights_.begin(); i != subGeometryLodLevel.boneWeights_.end(); ++i)
                {
                    // Sort the bone assigns by weight, if not sorted yet in bone remapping pass
                    if (!sorted)
                        ea::quick_sort(i->second.begin(), i->second.end(), CompareWeights);

                    float totalWeight = 0.0f;
                    float normalizationFactor = 0.0f;

                    // Calculate normalization factor in case there are more than 4 blend weights, or they do not add up to 1
                    for (unsigned j = 0; j < i->second.size() && j < 4; ++j)
                        totalWeight += i->second[j].weight_;
                    if (totalWeight > 0.0f)
                        normalizationFactor = 1.0f / totalWeight;

                    for (unsigned j = 0; j < i->second.size() && j < 4; ++j)
                    {
                        vBuf->vertices_[i->first].blendIndices_[j] = i->second[j].boneIndex_;
                        vBuf->vertices_[i->first].blendWeights_[j] = i->second[j].weight_ * normalizationFactor;
                    }

                    // If there are less than 4 blend weights, fill rest with zero
                    for (unsigned j = i->second.size(); j < 4; ++j)
                    {
                        vBuf->vertices_[i->first].blendIndices_[j] = 0;
                        vBuf->vertices_[i->first].blendWeights_[j] = 0.0f;
                    }

                    vBuf->vertices_[i->first].hasBlendWeights_ = true;
                }
            }
        }
        else if (boneAssignments)
            PrintLine("No skeleton loaded, skipping skinning information");

        // Calculate center for the subgeometry
        Vector3 center = Vector3::ZERO;
        for (unsigned i = 0; i < iBuf->indices_.size(); i += 3)
        {
            center += vBuf->vertices_[iBuf->indices_[i]].position_;
            center += vBuf->vertices_[iBuf->indices_[i + 1]].position_;
            center += vBuf->vertices_[iBuf->indices_[i + 2]].position_;
        }
        if (iBuf->indices_.size())
            center /= (float) iBuf->indices_.size();
        subGeometryCenters_.push_back(center);

        indexStart += indices;
        vertexStart += vertices;

        OptimizeIndices(&subGeometryLodLevel, vBuf, iBuf);

        PrintLine("Processed submesh " + ea::to_string(subMeshIndex + 1) + ": " + ea::to_string(vertices) + " vertices " +
            ea::to_string(triangles) + " triangles");
        ea::vector<ModelSubGeometryLodLevel> thisSubGeometry;
        thisSubGeometry.push_back(subGeometryLodLevel);
        subGeometries_.push_back(thisSubGeometry);

        subMesh = subMesh.GetNext("submesh");
        subMeshIndex++;
    }

    // Process LOD levels, if any
    XMLElement lods = root.GetChild("levelofdetail");
    if (lods)
    {
        try
        {
            // For now, support only generated LODs, where the vertices are the same
            XMLElement lod = lods.GetChild("lodgenerated");
            while (lod)
            {
                float distance = M_EPSILON;
                if (lod.HasAttribute("fromdepthsquared"))
                    distance = sqrtf(lod.GetFloat("fromdepthsquared"));
                if (lod.HasAttribute("value"))
                    distance = lod.GetFloat("value");
                XMLElement lodSubMesh = lod.GetChild("lodfacelist");
                while (lodSubMesh)
                {
                    unsigned subMeshIndex = lodSubMesh.GetInt("submeshindex");
                    unsigned triangles = lodSubMesh.GetInt("numfaces");

                    ModelSubGeometryLodLevel newLodLevel;
                    ModelSubGeometryLodLevel& originalLodLevel = subGeometries_[subMeshIndex][0];

                    // Copy all initial values
                    newLodLevel = originalLodLevel;

                    ModelVertexBuffer* vBuf;
                    ModelIndexBuffer* iBuf;

                    if (useOneBuffer_)
                    {
                        vBuf = &vertexBuffers_[0];
                        iBuf = &indexBuffers_[0];
                    }
                    else
                    {
                        vBuf = &vertexBuffers_[subMeshIndex];
                        iBuf = &indexBuffers_[subMeshIndex];
                    }

                    unsigned indexStart = iBuf->indices_.size();
                    unsigned indexCount = triangles * 3;
                    unsigned vertexStart = vertexStarts[subMeshIndex];

                    newLodLevel.distance_ = distance;
                    newLodLevel.indexStart_ = indexStart;
                    newLodLevel.indexCount_ = indexCount;

                    // Append indices to the original index buffer
                    XMLElement triangle = lodSubMesh.GetChild("face");
                    while (triangle)
                    {
                        unsigned v1 = triangle.GetInt("v1");
                        unsigned v2 = triangle.GetInt("v2");
                        unsigned v3 = triangle.GetInt("v3");
                        iBuf->indices_.push_back(v3 + vertexStart);
                        iBuf->indices_.push_back(v2 + vertexStart);
                        iBuf->indices_.push_back(v1 + vertexStart);
                        triangle = triangle.GetNext("face");
                    }

                    OptimizeIndices(&newLodLevel, vBuf, iBuf);

                    subGeometries_[subMeshIndex].push_back(newLodLevel);
                    PrintLine("Processed LOD level for submesh " + ea::to_string(subMeshIndex + 1) + ": distance " + ea::to_string(distance));

                    lodSubMesh = lodSubMesh.GetNext("lodfacelist");
                }
                lod = lod.GetNext("lodgenerated");
            }
        }
        catch (...) {}
    }

    // Process poses/morphs
    // First find out all pose definitions
    if (exportMorphs)
    {
        try
        {
            ea::vector<XMLElement> poses;
            XMLElement posesRoot = root.GetChild("poses");
            if (posesRoot)
            {
                XMLElement pose = posesRoot.GetChild("pose");
                while (pose)
                {
                    poses.push_back(pose);
                    pose = pose.GetNext("pose");
                }
            }

            // Then process animations using the poses
            XMLElement animsRoot = root.GetChild("animations");
            if (animsRoot)
            {
                XMLElement anim = animsRoot.GetChild("animation");
                while (anim)
                {
                    ea::string name = anim.GetAttribute("name");
                    float length = anim.GetFloat("length");
                    ea::hash_set<unsigned> usedPoses;
                    XMLElement tracks = anim.GetChild("tracks");
                    if (tracks)
                    {
                        XMLElement track = tracks.GetChild("track");
                        while (track)
                        {
                            XMLElement keyframes = track.GetChild("keyframes");
                            if (keyframes)
                            {
                                XMLElement keyframe = keyframes.GetChild("keyframe");
                                while (keyframe)
                                {
                                    float time = keyframe.GetFloat("time");
                                    XMLElement poseref = keyframe.GetChild("poseref");
                                    // Get only the end pose
                                    if (poseref && time == length)
                                        usedPoses.insert(poseref.GetInt("poseindex"));

                                    keyframe = keyframe.GetNext("keyframe");
                                }
                            }
                            track = track.GetNext("track");
                        }
                    }

                    if (usedPoses.size())
                    {
                        ModelMorph newMorph;
                        newMorph.name_ = name;

                        if (useOneBuffer_)
                            newMorph.buffers_.resize(1);
                        else
                            newMorph.buffers_.resize(usedPoses.size());

                        unsigned bufIndex = 0;

                        for (auto i = usedPoses.begin(); i != usedPoses.end(); ++i)
                        {
                            XMLElement pose = poses[*i];
                            unsigned targetSubMesh = pose.GetInt("index");
                            XMLElement poseOffset = pose.GetChild("poseoffset");

                            if (useOneBuffer_)
                                newMorph.buffers_[bufIndex].vertexBuffer_ = 0;
                            else
                                newMorph.buffers_[bufIndex].vertexBuffer_ = targetSubMesh;

                            newMorph.buffers_[bufIndex].elementMask_ = MASK_POSITION;

                            ModelVertexBuffer* vBuf = &vertexBuffers_[newMorph.buffers_[bufIndex].vertexBuffer_];

                            while (poseOffset)
                            {
                                // Convert from right- to left-handed
                                unsigned vertexIndex = poseOffset.GetInt("index") + vertexStarts[targetSubMesh];
                                float x = poseOffset.GetFloat("x");
                                float y = poseOffset.GetFloat("y");
                                float z = poseOffset.GetFloat("z");
                                Vector3 vec(x, y, -z);

                                if (vBuf->morphCount_ == 0)
                                {
                                    vBuf->morphStart_ = vertexIndex;
                                    vBuf->morphCount_ = 1;
                                }
                                else
                                {
                                    unsigned first = vBuf->morphStart_;
                                    unsigned last = first + vBuf->morphCount_ - 1;
                                    if (vertexIndex < first)
                                        first = vertexIndex;
                                    if (vertexIndex > last)
                                        last = vertexIndex;
                                    vBuf->morphStart_ = first;
                                    vBuf->morphCount_ = last - first + 1;
                                }

                                ModelVertex newVertex;
                                newVertex.position_ = vec;
                                newMorph.buffers_[bufIndex].vertices_.push_back(ea::make_pair(vertexIndex, newVertex));
                                poseOffset = poseOffset.GetNext("poseoffset");
                            }

                            if (!useOneBuffer_)
                                ++bufIndex;
                        }
                        morphs_.push_back(newMorph);
                        PrintLine("Processed morph " + name + " with " + ea::to_string(usedPoses.size()) + " sub-poses");
                    }

                    anim = anim.GetNext("animation");
                }
            }
        }
        catch (...) {}
    }

    // Check any of the buffers for vertices with missing blend weight assignments
    for (unsigned i = 0; i < vertexBuffers_.size(); ++i)
    {
        if (vertexBuffers_[i].elementMask_ & MASK_BLENDWEIGHTS)
        {
            for (unsigned j = 0; j < vertexBuffers_[i].vertices_.size(); ++j)
                if (!vertexBuffers_[i].vertices_[j].hasBlendWeights_)
                    ErrorExit("Found a vertex with missing skinning information");
        }
    }

    // Tangent generation
    if (generateTangents)
    {
        for (unsigned i = 0; i < subGeometries_.size(); ++i)
        {
            for (unsigned j = 0; j < subGeometries_[i].size(); ++j)
            {
                ModelVertexBuffer& vBuf = vertexBuffers_[subGeometries_[i][j].vertexBuffer_];
                ModelIndexBuffer& iBuf = indexBuffers_[subGeometries_[i][j].indexBuffer_];
                unsigned indexStart = subGeometries_[i][j].indexStart_;
                unsigned indexCount = subGeometries_[i][j].indexCount_;

                // If already has tangents, do not regenerate
                if (vBuf.elementMask_ & MASK_TANGENT || vBuf.vertices_.empty() || iBuf.indices_.empty())
                    continue;

                vBuf.elementMask_ |= MASK_TANGENT;

                if ((vBuf.elementMask_ & (MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1)) != (MASK_POSITION | MASK_NORMAL |
                    MASK_TEXCOORD1))
                    ErrorExit("To generate tangents, positions normals and texcoords are required");

                GenerateTangents(&vBuf.vertices_[0], sizeof(ModelVertex), &iBuf.indices_[0], sizeof(unsigned), indexStart,
                    indexCount, offsetof(ModelVertex, normal_), offsetof(ModelVertex, texCoord1_), offsetof(ModelVertex,
                    tangent_));

                PrintLine("Generated tangents");
            }
        }
    }
}
Example #18
0
// Return: false if deleted
bool CItem::StartRefresh() 
{
	ASSERT(GetType() != IT_FREESPACE);
	ASSERT(GetType() != IT_UNKNOWN);

	m_ticksWorked = 0;

	// Special case IT_MYCOMPUTER
	if (GetType() == IT_MYCOMPUTER)
	{
		ZeroMemory(&m_lastChange, sizeof(m_lastChange));

		for (int i=0; i < GetChildrenCount(); i++)
			GetChild(i)->StartRefresh();

		return true;
	}
	ASSERT(GetType() == IT_FILE || GetType() == IT_DRIVE || GetType() == IT_DIRECTORY || GetType() == IT_FILESFOLDER);

	bool wasExpanded = IsVisible() && IsExpanded();
	int oldScrollPosition = 0;
	if (IsVisible())
		oldScrollPosition = GetScrollPosition();

	UncacheImage();

	// Upward clear data
	UpdateLastChange();

	UpwardSetUndone();

	UpwardAddReadJobs(-GetReadJobs());
	ASSERT(GetReadJobs() == 0);

	if (GetType() == IT_FILE)
		GetParent()->UpwardAddFiles(-1);
	else
		UpwardAddFiles(-GetFilesCount());
	ASSERT(GetFilesCount() == 0);

	if (GetType() == IT_DIRECTORY || GetType() == IT_DRIVE)
		UpwardAddSubdirs(-GetSubdirsCount());
	ASSERT(GetSubdirsCount() == 0);

	UpwardAddSize(-GetSize());
	ASSERT(GetSize() == 0);

	RemoveAllChildren();
	UpwardRecalcLastChange();

	// Special case IT_FILESFOLDER
	if (GetType() == IT_FILESFOLDER)
	{
		CFileFindWDS finder;
		BOOL b = finder.FindFile(GetFindPattern());
		while (b)
		{
			b = finder.FindNextFile();
			if (finder.IsDirectory())
				continue;

			FILEINFO fi;
			fi.name = finder.GetFileName();
			fi.attributes = finder.GetAttributes();
			// Retrieve file size
			fi.length = finder.GetCompressedLength();
			finder.GetLastWriteTime(&fi.lastWriteTime);

			AddFile(fi);
			UpwardAddFiles(1);
		}
		SetDone();

		if (wasExpanded)
			GetTreeListControl()->ExpandItem(this);
		return true;
	}
	ASSERT(GetType() == IT_FILE || GetType() == IT_DRIVE || GetType() == IT_DIRECTORY);

	// The item may have been deleted.
	bool deleted = false;
	if (GetType() == IT_DRIVE)
		deleted = !DriveExists(GetPath());
	else if (GetType() == IT_FILE)
		deleted = !FileExists(GetPath());
	else if (GetType() == IT_DIRECTORY)
		deleted = !FolderExists(GetPath());

	if (deleted)
	{
		if (GetParent() == NULL)
		{
			GetDocument()->UnlinkRoot();
		}
		else
		{
			GetParent()->UpwardRecalcLastChange();
			GetParent()->RemoveChild(GetParent()->FindChildIndex(this)); // --> delete this
		}
		return false;
	}

	// Case IT_FILE
	if (GetType() == IT_FILE)
	{
		CFileFindWDS finder;
		BOOL b = finder.FindFile(GetPath());
		if (b)
		{
			finder.FindNextFile();
			if (!finder.IsDirectory())
			{
				FILEINFO fi;
				fi.name = finder.GetFileName();
				fi.attributes = finder.GetAttributes();
				// Retrieve file size
				fi.length = finder.GetCompressedLength();
				finder.GetLastWriteTime(&fi.lastWriteTime);

				SetLastChange(fi.lastWriteTime);

				UpwardAddSize(fi.length);
				UpwardUpdateLastChange(GetLastChange());
				GetParent()->UpwardAddFiles(1);
			}
		}
		SetDone();
		return true;
	}

	ASSERT(GetType() == IT_DRIVE || GetType() == IT_DIRECTORY);

	if (GetType() == IT_DIRECTORY && !IsRootItem() && GetApp()->IsMountPoint(GetPath()) && !GetOptions()->IsFollowMountPoints())
		return true;

	if (GetType() == IT_DIRECTORY && !IsRootItem() && GetApp()->IsJunctionPoint(GetPath()) && !GetOptions()->IsFollowJunctionPoints())
		return true;

	// Initiate re-read
	SetReadJobDone(false);

	// Re-create <free space> and <unknown>
	if (GetType() == IT_DRIVE)
	{
		if (GetDocument()->OptionShowFreeSpace())
			CreateFreeSpaceItem();
		if (GetDocument()->OptionShowUnknown())
			CreateUnknownItem();
	}

	DoSomeWork(0);

	if (wasExpanded)
		GetTreeListControl()->ExpandItem(this);

	if (IsVisible())
		SetScrollPosition(oldScrollPosition);

	return true;
}
Example #19
0
File: path.c Project: mikekap/wine
static void test_widenpath(void)
{
    HDC hdc = GetDC(0);
    HPEN greenPen, narrowPen;
    POINT pnt[6];
    INT nSize, ret;

    /* Create a pen to be used in WidenPath */
    greenPen = CreatePen(PS_SOLID, 10, RGB(0,0,0));
    SelectObject(hdc, greenPen);

    /* Prepare a path */
    pnt[0].x = 100;
    pnt[0].y = 0;
    pnt[1].x = 200;
    pnt[1].y = 0;
    pnt[2].x = 300;
    pnt[2].y = 100;
    pnt[3].x = 300;
    pnt[3].y = 200;
    pnt[4].x = 200;
    pnt[4].y = 300;
    pnt[5].x = 100;
    pnt[5].y = 300;

    /* Set a polyline path */
    BeginPath(hdc);
    Polyline(hdc, pnt, 6);
    EndPath(hdc);

    /* Widen the polyline path */
    ok(WidenPath(hdc), "WidenPath fails while widening a poyline path.\n");

    /* Test if WidenPath seems to have done his job */
    nSize = GetPath(hdc, NULL, NULL, 0);
    ok(nSize != -1, "GetPath fails after calling WidenPath.\n");
    ok(nSize > 6, "Path number of points is too low. Should be more than 6 but is %d\n", nSize);

    AbortPath(hdc);

    /* Test WidenPath with an open path (last error only set on Win2k and later) */
    SetLastError(0xdeadbeef);
    BeginPath(hdc);
    ret = WidenPath(hdc);
    ok(ret == FALSE && (GetLastError() == ERROR_CAN_NOT_COMPLETE || GetLastError() == 0xdeadbeef),
       "WidenPath fails while widening an open path. Return value is %d, should be %d. Error is %u\n", ret, FALSE, GetLastError());

    AbortPath(hdc);

    /* Test when the pen width is equal to 1. The path should change too */
    narrowPen = CreatePen(PS_SOLID, 1, RGB(0,0,0));
    SelectObject(hdc, narrowPen);
    BeginPath(hdc);
    Polyline(hdc, pnt, 6);
    EndPath(hdc);
    ret = WidenPath(hdc);
    nSize = GetPath(hdc, NULL, NULL, 0);
    ok(nSize > 6, "WidenPath should compute a widdened path with a 1px wide pen. Path length is %d, should be more than 6\n", nSize);

    ReleaseDC(0, hdc);
    return;
}
Example #20
0
int CItem::CompareSibling(const CTreeListItem *tlib, int subitem) const
{ 
	CItem *other = (CItem *)tlib;

	int r=0;
	switch (subitem)
	{
	case COL_NAME:
		if (GetType() == IT_DRIVE)
		{
			ASSERT(other->GetType() == IT_DRIVE);
			r = signum(GetPath().CompareNoCase(other->GetPath()));
		}
		else
		{
			r = signum(m_name.CompareNoCase(other->m_name));
		}
		break;

	case COL_SUBTREEPERCENTAGE:
		if (MustShowReadJobs())
			r = signum(m_readJobs - other->m_readJobs);
		else
			r = signum(GetFraction() - other->GetFraction());
		break;

	case COL_PERCENTAGE:
		r = signum(GetFraction() - other->GetFraction());
		break;

	case COL_SUBTREETOTAL:
		r = signum(GetSize() - other->GetSize());
		break;

	case COL_ITEMS:
		r = signum(GetItemsCount() - other->GetItemsCount());
		break;

	case COL_FILES:
		r = signum(GetFilesCount() - other->GetFilesCount());
		break;

	case COL_SUBDIRS:
		r = signum(GetSubdirsCount() - other->GetSubdirsCount());
		break;

	case COL_LASTCHANGE:
		{
			if (m_lastChange < other->m_lastChange)
				return -1;
			else if (m_lastChange == other->m_lastChange)
				return 0;
			else 
				return 1;
		}
		break;
	case COL_ATTRIBUTES:
		r = signum(GetSortAttributes() - other->GetSortAttributes());
		break;

	default:
		ASSERT(false);
		break;
	}
	return r;
}
Example #21
0
bool CModel::WriteExternal(bool bPromptForNames, bool& bCFGWritten)
{
	bCFGWritten = false;

	CString filename;
	if (bPromptForNames)
	{
		CString strInitialPrompt(ghAssimilateView->GetDocument()->GetPathName());
		Filename_RemoveFilename(strInitialPrompt);
		strInitialPrompt.Replace("/","\\");
		strInitialPrompt += "\\";
		strInitialPrompt += sANIMATION_CFG_NAME;
		
		CFileDialog dialog(FALSE, ".cfg", strInitialPrompt, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "Config Data Files (*.cfg)|*.cfg|All Files (*.*)|*.*||", NULL);
		if (dialog.DoModal() != IDOK)
		{
			return false;
		}
		filename = dialog.GetPathName();	// eg. {"Q:\quake\baseq3\models\players\ste_assimilate_test\ste_assimilate_test.cfg"}
	}
	else
	{
		filename = ((CAssimilateApp*)AfxGetApp())->GetQuakeDir();
		filename+= GetPath();
		filename.MakeLower();
		filename.Replace('\\', '/');
		int loc = filename.Find(m_name);//"/root");
		if (loc>=0)
		{
			filename = filename.Left(loc+strlen(m_name));
		}
		// dup the dirname to use as the model name... (eg "/.../.../klingon" becomes "/.../.../klingon/klingon"
		filename += "/"; filename += sANIMATION_CFG_NAME;	
	}
	CTxtFile* file = CTxtFile::Create(filename);
	if (file == NULL || !file->IsValid())
	{
		ErrorBox(va("Error creating file \"%s\"!",filename));
		return false;
	}

	// new bit, check for the existance of an animation.pre file, which means export this in Q3 format (rather than trek)

	CString strQ3FormatCheckName(filename);
	Filename_RemoveFilename(strQ3FormatCheckName);
	strQ3FormatCheckName += "\\";
	strQ3FormatCheckName += sANIMATION_PRE_NAME;
	strQ3FormatCheckName.Replace("/","\\");

	bool bExportFormatIsQuake3Multiplayer = //FileExists(strQ3FormatCheckName);
											((CAssimilateApp*)AfxGetApp())->GetMultiPlayerMode();	

	CString strPrePend;
	if (bExportFormatIsQuake3Multiplayer)
	{
		// multi-player format, check for optional animation.pre file...

		FILE *fhPRE = fopen(strQ3FormatCheckName, "rt");
		
		if (fhPRE)
		{
			// read all the lines in this file and just write them straight to the output file...

			char sLine[16384];
			char *psLine;
			CString strTrimmed;

			while ((psLine = fgets( sLine, sizeof(sLine), fhPRE ))!=NULL)
			{
				strTrimmed = psLine;
				strTrimmed.Replace("\n","");
				strTrimmed.TrimRight();
				strTrimmed.TrimLeft();

				file->Writeln(strTrimmed);
			}

			if (ferror(fhPRE))
			{
				ErrorBox(va("Error during reading of file \"%s\"!\n\n( this shouldn't happen )",(LPCSTR)strQ3FormatCheckName));
			}

			fclose(fhPRE);
		}		

		file->Writeln("");
		file->Writeln("//");
		file->Writeln("// Format:  targetFrame, frameCount, loopFrame, frameSpeed");
		file->Writeln("//");
	}
	else
	{
		// single-player format...

		CString commentLine;
		CTime time = CTime::GetCurrentTime();
		commentLine.Format("// %s %d frames; %d sequences; updated %s", filename, m_totFrames, GetTotSequences(), time.Format("%H:%M %A, %B %d, %Y"));
		file->Writeln(commentLine);

		// the Writeln functions I have to call don't handle "\n" chars properly because of being opened in binary mode
		//	(sigh), so I have to explicitly call the Writeln() functions to output CRs... :-(

		file->Writeln("//");
		file->Writeln("// Format:  enum, targetFrame, frameCount, loopFrame, frameSpeed");	
		file->Writeln("//");
	}

	CSequence* curSequence = m_sequences;
	while(curSequence != NULL)
	{
		curSequence->WriteExternal(this, file, bExportFormatIsQuake3Multiplayer);
		curSequence = curSequence->GetNext();
	}
	file->Delete();

	if (HasGLA())
	{
		_unlink(filename);	// zap it, since it's meaningless here (only has one seq/enum: the whole GLA)
	}
	else
	{
		bCFGWritten = true;
	}

	return true;
}
Example #22
0
bool CItem::HasUncPath() const
{
	CString path = GetPath();
	return (path.GetLength() >= 2 && path.Left(2) == _T("\\\\"));
}
JBoolean
CBNewProjectSaveFileDialog::OKToDeactivate()
{
	if (!JXSaveFileDialog::OKToDeactivate())
		{
		return kJFalse;
		}
	else if (Cancelled())
		{
		return kJTrue;
		}

	const CBBuildManager::MakefileMethod method = GetMakefileMethod();
	if (method == CBBuildManager::kManual)
		{
		return kJTrue;
		}

	// ask if OK to replace Make.files

	if (method == CBBuildManager::kMakemake)
		{
		const JString makeFilesName = CBBuildManager::GetMakeFilesName(GetPath());
		if (JFileExists(makeFilesName) &&
			!OKToReplaceFile(makeFilesName, JGetString("CBName")))
			{
			return kJFalse;
			}
		}

	// ask if OK to replace CMakeLists.txt

	if (method == CBBuildManager::kCMake)
		{
		JString projFileName, projRoot, projSuffix;
		GetFileName(&projFileName);
		JSplitRootAndSuffix(projFileName, &projRoot, &projSuffix);

		const JString cmakeInputName = CBBuildManager::GetCMakeInputName(GetPath(), projRoot);
		if (JFileExists(cmakeInputName) &&
			!OKToReplaceFile(cmakeInputName, JGetString("CBName")))
			{
			return kJFalse;
			}
		}

	// ask if OK to replace .pro

	if (method == CBBuildManager::kQMake)
		{
		JString projFileName, projRoot, projSuffix;
		GetFileName(&projFileName);
		JSplitRootAndSuffix(projFileName, &projRoot, &projSuffix);

		const JString qmakeInputName = CBBuildManager::GetQMakeInputName(GetPath(), projRoot);
		if (JFileExists(qmakeInputName) &&
			!OKToReplaceFile(qmakeInputName, JGetString("CBName")))
			{
			return kJFalse;
			}
		}

	// ask if OK to replace existing Makefile

	JPtrArray<JString> makefileList(JPtrArrayT::kDeleteAll);
	CBBuildManager::GetMakefileNames(GetPath(), &makefileList);

	const JSize count = makefileList.GetElementCount();
	for (JIndex i=1; i<=count; i++)
		{
		const JString* fullName = makefileList.NthElement(i);
		if (JFileExists(*fullName) &&
			!OKToReplaceFile(*fullName, CBBuildManager::GetMakefileMethodName(GetMakefileMethod())))
			{
			return kJFalse;
			}
		}

	return kJTrue;
}
Example #24
0
File: prim.cpp Project: JT-a/USD
bool 
UsdPrim::RemoveProperty(const TfToken &propName) 
{
    SdfPath propPath = GetPath().AppendProperty(propName);
    return _GetStage()->_RemoveProperty(propPath);
}
Example #25
0
VError VFolder::CopyContentsTo( const VFolder& inDestinationFolder, FileCopyOptions inOptions) const
{
	VError err = VE_OK;
	if (!inDestinationFolder.Exists())
	{
		// this easy case should be handled by system implementation
		err = inDestinationFolder.Create();
	}
	else if (IsSameFolder( &inDestinationFolder) || inDestinationFolder.GetPath().IsChildOf( GetPath()))
	{
		StThrowFileError errThrow( this, VE_CANNOT_COPY_ON_ITSELF);
		errThrow->SetString( "destination", inDestinationFolder.GetPath().GetPath());
		err = errThrow.GetError();
	}

	if (err == VE_OK)
	{
		bool ok = true;
		
		for( VFolderIterator folderIterator( this, FI_WANT_FOLDERS | FI_WANT_INVISIBLES) ; folderIterator.IsValid() && ok ; ++folderIterator)
		{
			VError err2 = folderIterator->CopyTo( inDestinationFolder, NULL, inOptions);
			if (err == VE_OK)
				err = err2;
			ok = (err == VE_OK) | ((inOptions & FCP_ContinueOnError) != 0);
		}
		
		for( VFileIterator fileIterator( this, FI_WANT_FILES | FI_WANT_INVISIBLES) ; fileIterator.IsValid() && ok ; ++fileIterator)
		{
			VError err2 = fileIterator->CopyTo( inDestinationFolder, NULL, inOptions);
			if (err == VE_OK)
				err = err2;
			ok = (err == VE_OK) | ((inOptions & FCP_ContinueOnError) != 0);
		}
	}
	
	return err;
}
Example #26
0
File: prim.cpp Project: JT-a/USD
void
UsdPrim::Load() const
{
    _GetStage()->Load(GetPath());
}
Example #27
0
bool CFLTKEditor::HighlightLinePos(const char *pcFilename, int iInputPos)
{
	if (iInputPos < 0)
		return false;

	int iTextPos, iLineStart, iLineEnd;
	char pcSearchName[300], *pcPoint;
	string sName;

	strncpy(pcSearchName, pcFilename, 299);
	if ((pcPoint = strstr(pcSearchName, ".clu")))
	{
		*pcPoint = 0;
	}

//	if (GetFilename().size() == 0)
		sName = GetPath() + GetName();
//	else
//		sName = GetFilename();

	if (pcSearchName != sName)
	{
		int i, iCount = m_mEditorData.Count();

		for (i = 0; i < iCount; i++)
		{
			//sName = m_mEditorData[i].m_sFilename;
			//if (sName.size() == 0)
			//{
				sName = m_mEditorData[i].m_sPath + m_mEditorData[i].m_sName;
			//}

			if (sName == pcSearchName)
			{
				SetCurEditor(i);
				m_pFileChoice->value(i);
				break;
			}
		}

		// File not opened yet
		if (i == iCount)
		{
			sName = pcSearchName;
			sName = sName + ".clu";
			CFLTKEditor::New();
			CFLTKEditor::LoadFile(sName.c_str());
			UpdateFileList();
		}
	}

	//iTextPos = GetTextBuffer()->skip_lines(0, iLine-1);
	iTextPos = iInputPos + 1;
	if (iTextPos >= GetTextBuffer()->length())
		iTextPos = GetTextBuffer()->length()-2;

	iLineStart = GetTextBuffer()->line_start(iTextPos);
	iLineEnd = GetTextBuffer()->line_end(iTextPos);
	GetTextBuffer()->select(iLineStart, iLineEnd);

	GetEditor()->insert_position(iTextPos);
	GetEditor()->show_insert_position();

	GetTextBuffer()->call_modify_callbacks();

	return true;
}
Example #28
0
File: prim.cpp Project: JT-a/USD
void
UsdPrim::Unload() const
{
    _GetStage()->Unload(GetPath());
}
Example #29
0
bool File::OpenInternal(const String& fileName, FileMode mode, bool fromPackage)
{
    Close();

    compressed_ = false;
    readSyncNeeded_ = false;
    writeSyncNeeded_ = false;

    FileSystem* fileSystem = GetSubsystem<FileSystem>();
    if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
    {
        ATOMIC_LOGERRORF("Access denied to %s", fileName.CString());
        return false;
    }

    if (fileName.Empty())
    {
        ATOMIC_LOGERROR("Could not open file with empty name");
        return false;
    }

#ifdef __ANDROID__
    if (ATOMIC_IS_ASSET(fileName))
    {
        if (mode != FILE_READ)
        {
            ATOMIC_LOGERROR("Only read mode is supported for Android asset files");
            return false;
        }

        assetHandle_ = SDL_RWFromFile(ATOMIC_ASSET(fileName), "rb");
        if (!assetHandle_)
        {
            ATOMIC_LOGERRORF("Could not open Android asset file %s", fileName.CString());
            return false;
        }
        else
        {
            fileName_ = fileName;
            mode_ = mode;
            position_ = 0;
            if (!fromPackage)
            {
                size_ = SDL_RWsize(assetHandle_);
                offset_ = 0;
            }
            checksum_ = 0;
            return true;
        }
    }
#endif

#ifdef _WIN32
    handle_ = _wfopen(GetWideNativePath(fileName).CString(), openMode[mode]);
#else
    handle_ = fopen(GetNativePath(fileName).CString(), openMode[mode]);
#endif

    // If file did not exist in readwrite mode, retry with write-update mode
    if (mode == FILE_READWRITE && !handle_)
    {
#ifdef _WIN32
        handle_ = _wfopen(GetWideNativePath(fileName).CString(), openMode[mode + 1]);
#else
        handle_ = fopen(GetNativePath(fileName).CString(), openMode[mode + 1]);
#endif
    }

    if (!handle_)
    {
        ATOMIC_LOGERRORF("Could not open file %s", fileName.CString());
        return false;
    }

    if (!fromPackage)
    {
        fseek((FILE*)handle_, 0, SEEK_END);
        long size = ftell((FILE*)handle_);
        fseek((FILE*)handle_, 0, SEEK_SET);
        if (size > M_MAX_UNSIGNED)
        {
            ATOMIC_LOGERRORF("Could not open file %s which is larger than 4GB", fileName.CString());
            Close();
            size_ = 0;
            return false;
        }
        size_ = (unsigned)size;
        offset_ = 0;
    }

    fileName_ = fileName;
    mode_ = mode;
    position_ = 0;
    checksum_ = 0;

    return true;
}
Example #30
0
// this function is called a *lot* of times (as I learned after seeing from
// profiler output that it is called ~12000 times from Mahogany start up code!)
// so it is important to optimize it - in particular, avoid using generic
// string functions here and do everything manually because it is faster
//
// I still kept the old version to be able to check that the optimized code has
// the same output as the non optimized version.
void wxRegConfig::SetPath(const wxString& strPath)
{
    // remember the old path
    wxString strOldPath = m_strPath;

#ifdef WX_DEBUG_SET_PATH // non optimized version kept here for testing
    wxString m_strPathAlt;

    {
        wxArrayString aParts;

        // because GetPath() returns "" when we're at root, we must understand
        // empty string as "/"
        if ( strPath.IsEmpty() || (strPath[0] == wxCONFIG_PATH_SEPARATOR) ) {
            // absolute path
            wxSplitPath(aParts, strPath);
        }
        else {
            // relative path, combine with current one
            wxString strFullPath = GetPath();
            strFullPath << wxCONFIG_PATH_SEPARATOR << strPath;
            wxSplitPath(aParts, strFullPath);
        }

        // recombine path parts in one variable
        wxString strRegPath;
        m_strPathAlt.Empty();
        for ( size_t n = 0; n < aParts.Count(); n++ ) {
            strRegPath << '\\' << aParts[n];
            m_strPathAlt << wxCONFIG_PATH_SEPARATOR << aParts[n];
        }
    }
#endif // 0

    // check for the most common case first
    if ( strPath.empty() )
    {
        m_strPath = wxCONFIG_PATH_SEPARATOR;
    }
    else // not root
    {
        // construct the full path
        wxString strFullPath;
        if ( strPath[0u] == wxCONFIG_PATH_SEPARATOR )
        {
            // absolute path
            strFullPath = strPath;
        }
        else // relative path
        {
            strFullPath.reserve(2*m_strPath.length());

            strFullPath << m_strPath;
            if ( strFullPath.Len() == 0 ||
                 strFullPath.Last() != wxCONFIG_PATH_SEPARATOR )
                strFullPath << wxCONFIG_PATH_SEPARATOR;
            strFullPath << strPath;
        }

        // simplify it: we need to handle ".." here

        // count the total number of slashes we have to know if we can go upper
        size_t totalSlashes = 0;

        // position of the last slash to be able to backtrack to it quickly if
        // needed, but we set it to -1 if we don't have a valid position
        //
        // we only remember the last position which means that we handle ".."
        // quite efficiently but not "../.." - however the latter should be
        // much more rare, so it is probably ok
        int posLastSlash = -1;

        const wxChar *src = strFullPath.c_str();
        size_t len = strFullPath.length();
        const wxChar *end = src + len;

        wxStringBufferLength buf(m_strPath, len);
        wxChar *dst = buf;
        wxChar *start = dst;

        for ( ; src < end; src++, dst++ )
        {
            if ( *src == wxCONFIG_PATH_SEPARATOR )
            {
                // check for "/.."

                // note that we don't have to check for src < end here as
                // *end == 0 so can't be '.'
                if ( src[1] == _T('.') && src[2] == _T('.') &&
                     (src + 3 == end || src[3] == wxCONFIG_PATH_SEPARATOR) )
                {
                    if ( !totalSlashes )
                    {
                        wxLogWarning(_("'%s' has extra '..', ignored."),
                                     strFullPath.c_str());
                    }
                    else // return to the previous path component
                    {
                        // do we already have its position?
                        if ( posLastSlash == -1 )
                        {
                            // no, find it: note that we are sure to have one
                            // because totalSlashes > 0 so we don't have to
                            // check the boundary condition below

                            // this is more efficient than strrchr()
                            dst--;
                            while ( *dst != wxCONFIG_PATH_SEPARATOR )
                            {
                                dst--;
                            }
                        }
                        else // the position of last slash was stored
                        {
                            // go directly there
                            dst = start + posLastSlash;

                            // invalidate posLastSlash
                            posLastSlash = -1;
                        }

                        // we must have found a slash one way or another!
                        wxASSERT_MSG( *dst == wxCONFIG_PATH_SEPARATOR,
                                      _T("error in wxRegConfig::SetPath") );

                        // stay at the same position
                        dst--;

                        // we killed one
                        totalSlashes--;
                    }

                    // skip both dots
                    src += 2;
                }
                else // not "/.."
                {
                    if ( (dst == start) || (dst[-1] != wxCONFIG_PATH_SEPARATOR) )
                    {
                        *dst = wxCONFIG_PATH_SEPARATOR;

                        posLastSlash = dst - start;

                        totalSlashes++;
                    }
                    else // previous char was a slash too
                    {
                        // squeeze several subsequent slashes into one: i.e.
                        // just ignore this one
                        dst--;
                    }
                }
            }
            else // normal character
            {
                // just copy
                *dst = *src;
            }
        }

        // NUL terminate the string
        if ( dst[-1] == wxCONFIG_PATH_SEPARATOR && (dst != start + 1) )
        {
            // if it has a trailing slash we remove it unless it is the only
            // string character
            dst--;
        }

        *dst = _T('\0');
        buf.SetLength(dst - start);
    }

#ifdef WX_DEBUG_SET_PATH
    wxASSERT( m_strPath == m_strPathAlt );
#endif

    if ( m_strPath == strOldPath )
        return;

    // registry APIs want backslashes instead of slashes
    wxString strRegPath;
    if ( !m_strPath.empty() )
    {
        size_t len = m_strPath.length();

        const wxChar *src = m_strPath.c_str();
        wxStringBufferLength buf(strRegPath, len);
        wxChar *dst = buf;

        const wxChar *end = src + len;
        for ( ; src < end; src++, dst++ )
        {
            if ( *src == wxCONFIG_PATH_SEPARATOR )
                *dst = _T('\\');
            else
                *dst = *src;
        }

        buf.SetLength(len);
    }

    // this is not needed any longer as we don't create keys unnecessarily any
    // more (now it is done on demand, i.e. only when they're going to contain
    // something)
#if 0
    // as we create the registry key when SetPath(key) is done, we can be left
    // with plenty of empty keys if this was only done to try to read some
    // value which, in fact, doesn't exist - to prevent this from happening we
    // automatically delete the old key if it was empty
    if ( m_keyLocal.Exists() && LocalKey().IsEmpty() )
    {
        m_keyLocal.DeleteSelf();
    }
#endif // 0

    // change current key(s)
    m_keyLocal.SetName(m_keyLocalRoot, strRegPath);

    if ( GetStyle() & wxCONFIG_USE_GLOBAL_FILE )
    {
      m_keyGlobal.SetName(m_keyGlobalRoot, strRegPath);

      wxLogNull nolog;
      m_keyGlobal.Open(wxRegKey::Read);
    }
}