/// <summary> /// Crée une copie de sauvegarde du fichier spécifié /// </summary> /// <param name="fileName">nom de fichier à sauvegarder</param> private void _BackupFile(string fileName) { // According to file type... if (Regex.IsMatch(fileName, BNK.FILENAME_PATTERN, RegexOptions.IgnoreCase)) { // Fichier BNK -> on crée une copie de sauvegarde par la méthode personnalisée // Chargement du fichier BNK BNK leBNK = TduFile.GetFile(fileName) as BNK; if (leBNK != null) { // Backup leBNK.MakeBackup(); } } else if (Regex.IsMatch(fileName, TduFile.BACKUP_FILENAME_PATTERN, RegexOptions.IgnoreCase)) { // Backup -> sauvegarde inutile string message = string.Format(_ERROR_BACKUP_OF_BACKUP, fileName); MessageBoxes.ShowWarning(this, message); } else { // Pour les autres fichiers on effectue la sauvegarde par défaut Tools.BackupFile(fileName, fileName + "." + LibraryConstants.EXTENSION_BACKUP); } }
/// <summary> /// Creates backup copy of replaced packed file /// </summary> /// <param name="bnkFilePath"></param> /// <param name="packedFileName"></param> /// <param name="backupFolder"></param> private static void _BackupFile(string bnkFilePath, string packedFileName, string backupFolder) { FileInfo fi = new FileInfo(bnkFilePath); // BUG_84: suffix added to folder string backupSubFolder = string.Concat(fi.Name, _SUFFIX_PACKED); string destinationFileName = string.Concat(backupFolder, @"\", backupSubFolder, @"\", packedFileName); // If backup file already exists, it is kept if (!File.Exists(destinationFileName)) { // Loading Bnk to extract file BNK bnk = TduFile.GetFile(bnkFilePath) as BNK; if (bnk == null || !bnk.Exists) { throw new Exception("Invalid BNK file: " + bnkFilePath); } fi = new FileInfo(destinationFileName); if (fi.Directory == null) { throw new Exception("Invalid file name: " + destinationFileName); } if (!Directory.Exists(fi.Directory.FullName)) { Directory.CreateDirectory(fi.Directory.FullName); } string packedFilePath = bnk.GetPackedFilesPaths(packedFileName)[0]; bnk.ExtractPackedFile(packedFilePath, destinationFileName, false); } }
/// <summary> /// Prepares a packed file for viewing/editing. can be used as stand-alone to get files without creating any task. /// </summary> /// <param name="bnk">BNK file</param> /// <param name="packedFilePath">Path of packed file to prepare</param> /// <returns>Full path of extracted file</returns> public string PrepareFile(BNK bnk, string packedFilePath) { string returnPath = null; if (bnk == null || string.IsNullOrEmpty(packedFilePath)) { return(returnPath); } // Working folder string workFolder = File2.SetTemporaryFolder(null, LibraryConstants.FOLDER_TEMP, true); if (workFolder == null) { throw new Exception(ERROR_CODE_TEMP_FOLDER); } // Extracting packed file into working folder string packedFileName = bnk.GetPackedFileName(packedFilePath); returnPath = string.Format(@"{0}\{1}", workFolder, packedFileName); bnk.ExtractPackedFile(packedFilePath, returnPath, false); // Removing attributes on file File.SetAttributes(returnPath, FileAttributes.Normal); return(returnPath); }
/// <summary> /// Loads the whole database in specified location and returns edit tasks /// </summary> /// <param name="databasePath"></param> /// <param name="culture"></param> /// <param name="isReadOnly"></param> /// <param name="returnedTasks"></param> /// <returns></returns> public static Dictionary <DB.Topic, TduFile[]> LoadDatabase(string databasePath, DB.Culture culture, bool isReadOnly, out Dictionary <DB.Topic, EditHelper.Task[]> returnedTasks) { Dictionary <DB.Topic, TduFile[]> returnedData = new Dictionary <DB.Topic, TduFile[]>(); returnedTasks = new Dictionary <DB.Topic, EditHelper.Task[]>(); if (!string.IsNullOrEmpty(databasePath)) { if (Directory.Exists(databasePath)) { // Opening main BNK string dbBnkFile = databasePath + @"\" + DB.GetBNKFileName(DB.Culture.Global); BNK dbBnk = TduFile.GetFile(dbBnkFile) as BNK; if (dbBnk == null) { throw new Exception("Unable to load BNK: " + dbBnkFile); } // Opening resource BNK string resBnkFile = databasePath + @"\" + DB.GetBNKFileName(culture); BNK resBnk = TduFile.GetFile(resBnkFile) as BNK; if (resBnk == null) { throw new Exception("Unable to load BNK: " + resBnk); } // Loading topics and resources foreach (DB.Topic anotherTopic in Enum.GetValues(typeof(DB.Topic))) { if (anotherTopic != DB.Topic.None) { EditHelper.Task[] loadedTasks; TduFile[] loadedFiles = LoadTopicForEdit(anotherTopic, culture, dbBnk, resBnk, out loadedTasks); returnedData.Add(anotherTopic, loadedFiles); if (!isReadOnly) { returnedTasks.Add(anotherTopic, loadedTasks); } } } } else { throw new Exception("Specified database path doesn't exist: " + databasePath); } } return(returnedData); }
/// <summary> /// Creates a new task and returns a copy instance /// </summary> /// <param name="parentBNK">Parent BNK file</param> /// <param name="packedFilePath">Path of packed file under edit</param> /// <param name="isFurtive">true to prevent this task to be displayed in GUI, else false</param> /// <returns>Added task instance</returns> public Task AddTask(BNK parentBNK, string packedFilePath, bool isFurtive) { Task editTask = new Task(); if (parentBNK == null) { return(editTask); } // New task editTask.parentBNK = parentBNK; editTask.editedPackedFilePath = packedFilePath; editTask.startDate = DateTime.Now; if (_SameTaskExists(editTask)) { throw new Exception(ERROR_CODE_TASK_EXISTS); } // Preparing edit... editTask.isFurtive = isFurtive; editTask.extractedFile = _PrepareFile(editTask); if (editTask.extractedFile == null) { throw new Exception(ERROR_CODE_EXTRACT_FAILED); } // BUG_48: Preparing tracking... editTask.trackedFile = TduFile.GetTrackedFileName(editTask.extractedFile); // Original write time if (editTask.extractedFile.Equals(editTask.trackedFile)) { FileInfo fi = new FileInfo(editTask.extractedFile); editTask.trackedLastFileWriteTime = fi.LastWriteTime; } else { // If tracked file name is different from extracted one, this data is set after first tracking // Because at the moment tracked file may not be ready editTask.trackedLastFileWriteTime = DateTime.MinValue; } editTask.isValid = true; // Change in task list _Tasks.Add(editTask); NotifyAll(); return(editTask); }
public void LoadBnkFileForXenonPlatform_ShouldNotCrash() { // GIVEN string bankFile = FileTesting.CreateFileFromResource("TDUModdingLibraryTests.Resources.banks.xenon." + ResourceFile, Path.Combine(_tempPath, ResourceFile)); // WHEN BNK bnk = TduFile.GetFile(bankFile) as BNK; // THEN Assert.NotNull(bnk); }
private void BuildData() { bnk = new BNK(BnkFile.FullName); for (int i = 0; i != bnk.WemList.Count; i++) { TreeNode node = new TreeNode(bnk.WemList[i].Name); node.Name = bnk.WemList[i].ID.ToString(); node.Tag = bnk.WemList[i]; TreeView_Wems.Nodes.Add(node); } }
/// <summary> /// Réalise la conversion multiple /// </summary> private void _MultipleConvert() { // Vérifications if (string.IsNullOrEmpty(sourceBNKTextBox.Text) || string.IsNullOrEmpty(targetFolderTextBox.Text)) { return; } Cursor = Cursors.WaitCursor; // Parcours des fichiers et extraction des 2DB BNK bnkFile = TduFile.GetFile(sourceBNKTextBox.Text) as BNK; if (bnkFile == null) { throw new Exception(_ERROR_INVALID_BNK_FILE); } Collection <string> textureFiles = bnkFile.GetPackedFilesPathsByExtension(LibraryConstants.EXTENSION_2DB_FILE); string tempFolder = File2.SetTemporaryFolder(null, LibraryConstants.FOLDER_TEMP, true); foreach (string anotherFilePath in textureFiles) { // 1.Extraction depuis le BNK vers le dossier temporaire bnkFile.ExtractPackedFile(anotherFilePath, tempFolder, true); // 2.Conversion des fichiers 2DB>DDS string fileName = tempFolder + @"\" + bnkFile.GetPackedFileName(anotherFilePath); FileInfo fi = new FileInfo(fileName); string newFileName = targetFolderTextBox.Text + @"\" + File2.ChangeExtensionOfFilename(fi.Name, LibraryConstants.EXTENSION_DDS_FILE); // If file already exists, it is renamed Tools.RenameIfNecessary(newFileName, LibraryConstants.SUFFIX_OLD_FILE); GraphicsConverters._2DBToDDS(fileName, newFileName); } // EVO 32 string message = string.Format(_STATUS_SUCCESS_MULTIPLE, textureFiles.Count); StatusBarLogManager.ShowEvent(this, message); // On efface le champ source sourceBNKTextBox.Text = ""; // Mise à jour de l'emplacement des 2DB _2DBLocationLink.Text = tempFolder; Cursor = Cursors.Default; }
/// <summary> /// Prépare le chargement d'une catégorie depuis la base de données courante /// </summary> /// <param name="category">Type de données recherché</param> /// <param name="culture">Code pays</param> private void _LoadFromCurrentDatabase(DB.Topic category, DB.Culture culture) { // Localisation du fichier BNK string bnkPath = Program.ApplicationSettings.TduMainFolder + LibraryConstants.FOLDER_DB + DB.GetBNKFileName(culture); BNK bnk = TduFile.GetFile(bnkPath) as BNK; if (bnk != null && bnk.Exists) { string fileName = DB.GetFileName(culture, category); string filePath = bnk.GetPackedFilesPaths(fileName)[0]; // EVO_91: using edit support from ModdingLibrary EditHelper.Task currentTask = EditHelper.Instance.AddTask(bnk, filePath, true); _EditedFile = currentTask.extractedFile; } }
/// <summary> /// Loads the whole specified topic for edit mode and returns corresponding TduFiles and EditTasks /// </summary> /// <param name="topic"></param> /// <param name="culture"></param> /// <param name="bnkFile"></param> /// <param name="rBnkFile"></param> /// <param name="returnedTasks"></param> /// <returns></returns> public static TduFile[] LoadTopicForEdit(DB.Topic topic, DB.Culture culture, BNK bnkFile, BNK rBnkFile, out EditHelper.Task[] returnedTasks) { TduFile[] returnedFiles = new TduFile[2]; returnedTasks = new EditHelper.Task[2]; if (bnkFile != null && bnkFile.Exists) { // Getting files string dbFilePath = bnkFile.GetPackedFilesPaths(DB.GetFileName(DB.Culture.Global, topic))[0]; returnedTasks[0] = EditHelper.Instance.AddTask(bnkFile, dbFilePath, true); if (culture != DB.Culture.Global && rBnkFile != null && rBnkFile.Exists) { string dbrFilePath = rBnkFile.GetPackedFilesPaths(DB.GetFileName(culture, topic))[0]; returnedTasks[1] = EditHelper.Instance.AddTask(rBnkFile, dbrFilePath, true); } // Loading these files DB main = TduFile.GetFile(returnedTasks[0].extractedFile) as DB; if (main == null || !main.Exists) { throw new Exception(topic + " main database loading failure."); } returnedFiles[0] = main; // Resource (optional) if (returnedTasks[1].isValid) { DBResource resource = TduFile.GetFile(returnedTasks[1].extractedFile) as DBResource; if (resource == null || !resource.Exists) { throw new Exception(string.Concat(topic, "-", culture, " resource database loading failure.")); } returnedFiles[1] = resource; } } return(returnedFiles); }
public void ExtractPackedFile_WhenFileTarget_ShouldCreateFileAtRightLocation() { // GIVEN string bankFile = FileTesting.CreateFileFromResource("TDUModdingLibraryTests.Resources.banks.pc." + ResourceFile, Path.Combine(_tempPath, ResourceFile)); BNK bnk = TduFile.GetFile(bankFile) as BNK; Assert.NotNull(bnk); string packedFilePath = @"D:\Eden-Prog\Games\TestDrive\Resources\4Build\PC\EURO\Vehicules\Cars\Mercedes\CLK_55\.2DM\CLK_55"; // WHEN string expectedFilePath = Path.Combine(_tempPath, "extracted.CLK_55.2DM"); bnk.ExtractPackedFile(packedFilePath, expectedFilePath, false); // THEN Assert.IsTrue(File.Exists(expectedFilePath)); }
/// <summary> /// Replaces packed file in TDU installed files by previous backup /// </summary> /// <param name="bnkFilePath"></param> /// <param name="packedFileName"></param> /// <param name="backupFolder"></param> private static void _UninstallPackedFile(string bnkFilePath, string packedFileName, string backupFolder) { FileInfo fi = new FileInfo(bnkFilePath); // BUG_84: suffix added to folder string backupSubFolder = string.Concat(fi.Name, InstallPackedFileI._SUFFIX_PACKED); string backupFileName = string.Concat(backupFolder, @"\", backupSubFolder, @"\", packedFileName); // Replaces file in BNK BNK bnk = TduFile.GetFile(bnkFilePath) as BNK; if (bnk == null || !bnk.Exists) { throw new Exception("Invalid BNK file: " + bnkFilePath); } string packedFilePath = bnk.GetPackedFilesPaths(packedFileName)[0]; bnk.ReplacePackedFile(packedFilePath, backupFileName); }
static BankInfoOutputObject GetBankInfoOutput(BNK bankFile) { var outputObject = new BankInfoOutputObject((int)bankFile.Size, (int)bankFile.Year); var packedFilesInformations = new List <PackedFileInfoOutputObject>(); foreach (var packedFilePath in bankFile.GetPackedFilesPaths(null)) { var packedFileShortName = bankFile.GetPackedFileName(packedFilePath); var packedFileSize = bankFile.GetPackedFileSize(packedFilePath); var packedFileTypeDescription = bankFile.GetPackedFileTypeDescription(packedFilePath); var packedFilesInfo = new PackedFileInfoOutputObject(packedFileShortName, packedFilePath, packedFileSize, packedFileTypeDescription); packedFilesInformations.Add(packedFilesInfo); } outputObject.PackedFiles.AddRange(packedFilesInformations); return(outputObject); }
/// <summary> /// Loads specified BNK file into BNK Manager /// </summary> /// <param name="selectedFile"></param> private void _LoadBnkFile(string selectedFile) { // Vérification : si le fichier n'est pas déjà chargé if (_CurrentBnkFile == null || !selectedFile.Equals(_CurrentBnkFile.FileName)) { // Chargement du fichier BNK StatusBarLogManager.ShowEvent(this, _STATUS_BNK_LOADING); _CurrentBnkFile = TduFile.GetFile(selectedFile) as BNK; if (_CurrentBnkFile != null) { // Mise à jour des listes SetBnkContentsChanged(); // No selection in packed list contentListView.SelectedItems.Clear(); contentTreeView.SelectedNode = null; } } }
/// <summary> /// Loads the whole specified topic in current database for read-only mode /// </summary> /// <param name="topic"></param> /// <param name="culture"></param> /// <returns>Array of database loaded TduFile. Index 0 is the main (encrypted) file, index 1 is the resource one</returns> public static TduFile[] LoadTopicForReadOnly(DB.Topic topic, DB.Culture culture) { TduFile[] returnedFiles = new TduFile[2]; // Loading BNKs string databaseFolder = LibraryConstants.GetSpecialFolder(LibraryConstants.TduSpecialFolder.Database); string mainBnkFile = string.Concat(databaseFolder, DB.GetBNKFileName(DB.Culture.Global)); string resourceBnkFile = string.Concat(databaseFolder, DB.GetBNKFileName(culture)); BNK mainBnk = TduFile.GetFile(mainBnkFile) as BNK; BNK resourceBnk = TduFile.GetFile(resourceBnkFile) as BNK; // Getting read-only files if (mainBnk != null && resourceBnk != null) { string dbPackedFileName = DB.GetFileName(DB.Culture.Global, topic); string fileName = EditHelper.Instance.PrepareFile(mainBnk, mainBnk.GetPackedFilesPaths(dbPackedFileName)[0]); string dbrPackedFileName = DB.GetFileName(culture, topic); string resourceFileName = EditHelper.Instance.PrepareFile(resourceBnk, resourceBnk.GetPackedFilesPaths(dbrPackedFileName)[0]); // Loading these files DB main = TduFile.GetFile(fileName) as DB; DBResource resource = TduFile.GetFile(resourceFileName) as DBResource; if (main == null || !main.Exists) { throw new Exception(topic + " main database failure."); } if (resource == null || !resource.Exists) { throw new Exception(string.Concat(topic, "-", culture, " resource database failure.")); } // Filling array returnedFiles[0] = main; returnedFiles[1] = resource; } return(returnedFiles); }
/// <summary> /// Handles database loading /// </summary> private void _LoadDatabase() { DB.Culture currentCulture = Program.ApplicationSettings.GetCurrentCulture(); string resourceBNKFileName = DB.GetBNKFileName(currentCulture); BNK resourceBNK = TduFile.GetFile(Tools.TduPath + LibraryConstants.FOLDER_DB + resourceBNKFileName) as BNK; if (resourceBNK != null) { // Extracting Houses resource string packedFileName = DB.GetFileName(currentCulture, DB.Topic.Houses); string packedFilePath = resourceBNK.GetPackedFilesPaths(packedFileName)[0]; string tempLocation = File2.SetTemporaryFolder(null, LibraryConstants.FOLDER_TEMP, true); resourceBNK.ExtractPackedFile(packedFilePath, tempLocation, true); // Loading resource _HousesResource = TduFile.GetFile(tempLocation + @"\" + packedFileName) as DBResource; if (_HousesResource == null) { throw new Exception("Error while loading database resources (Houses) !"); } } }
private void bnkListView_SelectedIndexChanged(object sender, EventArgs e) { if (bnkListView.SelectedItems.Count == 1) { Cursor = Cursors.WaitCursor; string selectedFile = CurrentFolder + bnkListView.SelectedItems[0].Text; try { // Selon l'extension... on ne gère que les fichiers BNK sur simple clic if (Regex.IsMatch(selectedFile, BNK.FILENAME_PATTERN, RegexOptions.IgnoreCase)) { // Fichier BNK -> on affiche le contenu en partie inférieure _LoadBnkFile(selectedFile); } else { // Effacement de la liste contenue dans le BNK Manager _ClearContentLists(); StatusBarLogManager.ShowEvent(this, _STATUS_NO_BNK_SELECTED); _CurrentBnkFile = null; } Cursor = Cursors.Default; } catch (Exception ex) { string message = string.Format(_ERROR_LOAD_BNK_FAILED, selectedFile); Exception newEx = new Exception(message, ex); _CurrentBnkFile = null; MessageBoxes.ShowError(this, newEx); } } }
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { int id = listBox1.SelectedIndex; int count = 0; if (id >= 0 && DIR != null) { if (DIR.Entries[id].sFileName.Contains("bnk")) { using (Stream stream = new MemoryStream(DIR.Entries[id].Data, false)) { reader = new BinaryReader(stream); BNK bnk = new BNK(reader, ref Sprites, ref Frames); BinaryWriter Writer = new BinaryWriter(new MemoryStream()); foreach (Frame spr in Frames) { listBox2.Items.Add("Sprite" + count); Bitmap bmp = Frames[id].ToBitmap(ref Writer, new byte[4], false, Sprites[id].CropL, Sprites[id].CropU, Sprites[id].CropR, Sprites[id].CropD); bmp.Save("newimage" + count + ".bmp"); count++; } label4.Text = Sprites.Count.ToString(); label7.Text = Frames.Count.ToString(); } } else if (DIR.Entries[id].sFileName.Contains("img")) { IMG img = new IMG(new MemoryStream(DIR.Entries[id].Data, false)); pictureBox1.BackgroundImage = img.Bitmap; } else if (DIR.Entries[id].sFileName.Contains("spr")) { using (Stream stream = new MemoryStream(DIR.Entries[id].Data, false)) { reader = new BinaryReader(stream); SPR spr = new SPR(reader, ref Sprites, ref Frames); BinaryWriter Writer = new BinaryWriter(new MemoryStream()); foreach (Frame sp in Frames) { listBox2.Items.Add("Sprite" + count); Bitmap bmp = sp.ToBitmap(ref Writer, new byte[4], true, sp.CropL, sp.CropU, sp.CropR, sp.CropD); sp.Bitmap = bmp; bmp.Save("newimage" + count + ".bmp"); count++; } label4.Text = Sprites.Count.ToString(); label7.Text = Frames.Count.ToString(); } } } }
/// <summary> /// What the instruction should do /// </summary> protected override void _Process() { // Checking parameters string fileName = _GetParameter(PatchInstructionParameter.ParameterName.resourceFileName); string id = _GetParameter(PatchInstructionParameter.ParameterName.databaseId); // Modifying corresponding topic DB.Topic currentTopic = (DB.Topic)Enum.Parse(typeof(DB.Topic), fileName); EditHelper.Task dbTask = new EditHelper.Task(); string bnkFilePath = ""; try { string dbFileName = null; // 1. Creating edit task try { bnkFilePath = string.Concat(LibraryConstants.GetSpecialFolder(LibraryConstants.TduSpecialFolder.Database), DB.GetBNKFileName(DB.Culture.Global)); BNK databaseBNK = TduFile.GetFile(bnkFilePath) as BNK; if (databaseBNK != null) { dbFileName = DB.GetFileName(DB.Culture.Global, currentTopic); dbTask = EditHelper.Instance.AddTask(databaseBNK, databaseBNK.GetPackedFilesPaths(dbFileName)[0], true); } } catch (Exception ex) { throw new Exception("Unable to create edit task on BNK file: " + bnkFilePath, ex); } // 2. Getting TduFile DB db; try { db = TduFile.GetFile(dbTask.extractedFile) as DB; if (db == null || !db.Exists) { throw new Exception("Extracted db file not found!"); } } catch (Exception ex) { throw new Exception("Unable to gain access to DB contents: " + dbFileName, ex); } // 3. Removing values in DB file DatabaseHelper.DeleteFromTopicWhereIdentifier(db, id); // 4. Saving try { db.Save(); EditHelper.Instance.ApplyChanges(dbTask); } catch (Exception ex) { throw new Exception("Unable to save BNK file: " + bnkFilePath, ex); } } finally { // Cleaning up EditHelper.Instance.RemoveTask(dbTask); } }
/// <summary> /// What the instruction should do /// </summary> protected override void _Process() { // Checking parameters string fileName = _GetParameter(PatchInstructionParameter.ParameterName.resourceFileName); string values = _GetParameter(PatchInstructionParameter.ParameterName.resourceValues); // Modifying corresponding topic DB.Topic currentTopic = (DB.Topic)Enum.Parse(typeof(DB.Topic), fileName); EditHelper.Task dbTask = new EditHelper.Task(); string bnkFilePath = ""; try { string dbFileName = null; // 1. Creating edit task try { bnkFilePath = string.Concat(LibraryConstants.GetSpecialFolder(LibraryConstants.TduSpecialFolder.Database), DB.GetBNKFileName(DB.Culture.Global)); BNK databaseBNK = TduFile.GetFile(bnkFilePath) as BNK; if (databaseBNK != null) { dbFileName = DB.GetFileName(DB.Culture.Global, currentTopic); dbTask = EditHelper.Instance.AddTask(databaseBNK, databaseBNK.GetPackedFilesPaths(dbFileName)[0], true); } } catch (Exception ex) { throw new Exception("Unable to create edit task on BNK file: " + bnkFilePath, ex); } // 2. Getting TduFile DB db; try { db = TduFile.GetFile(dbTask.extractedFile) as DB; if (db == null || !db.Exists) { throw new Exception("Extracted db file not found!"); } } catch (Exception ex) { throw new Exception("Unable to gain access to DB contents: " + dbFileName, ex); } // 3. Setting values in DB file // One identifier (primary key: REF) or 2 identifiers (2 first columns) List <Couple <string> > couples = Tools.ParseCouples(values); string[] idArray = new string[couples.Count]; int counter = 0; // Parsing couples foreach (Couple <string> couple in couples) { string id = couple.FirstValue; string value = couple.SecondValue; // Does id exist ? if (db.EntriesByPrimaryKey.ContainsKey(id)) { // Already exists > modify it DatabaseHelper.UpdateAllCellsFromTopicWherePrimaryKey(db, id, value); Log.Info("Entry updating completed: " + id + " - " + value); } else { // Does not exist > create it DatabaseHelper.InsertAllCellsIntoTopic(db, value); Log.Info("Entry adding completed: " + value); } idArray[counter++] = id; } // 4. Saving try { db.Save(); EditHelper.Instance.ApplyChanges(dbTask); } catch (Exception ex) { throw new Exception("Unable to save BNK file: " + bnkFilePath, ex); } } finally { // Cleaning up EditHelper.Instance.RemoveTask(dbTask); } }
/// <summary> /// Returns the right TDUFile according to specified file. /// </summary> /// <param name="fileName">file name, without path</param> /// <returns>null if file is from an unsupported type</returns> public static TduFile GetFile(string fileName) { TduFile tduFile = new Regular(); FileInfo fi = new FileInfo(fileName); // New mapping management // Cameras if (Regex.IsMatch(fileName, Cameras.FILENAME_PATTERN, RegexOptions.IgnoreCase)) { if (fi.Exists) { tduFile = new Cameras(fileName); } else { tduFile = new Cameras(); } } // AIConfig else if (Regex.IsMatch(fileName, AIConfig.FILENAME_PATTERN, RegexOptions.IgnoreCase)) { if (fi.Exists) { tduFile = new AIConfig(fileName); } else { tduFile = new AIConfig(); } } // DB else if (Regex.IsMatch(fileName, DB.FILENAME_PATTERN, RegexOptions.IgnoreCase)) { if (fi.Exists) { tduFile = new DB(fileName); } else { tduFile = new DB(); } } // BNK else if (Regex.IsMatch(fileName, BNK.FILENAME_PATTERN, RegexOptions.IgnoreCase)) { tduFile = new BNK(fileName); } // DDS else if (Regex.IsMatch(fileName, DDS.FILENAME_PATTERN, RegexOptions.IgnoreCase)) { if (fi.Exists) { tduFile = new DDS(fileName); } else { tduFile = new DDS(); } } // 2DB else if (Regex.IsMatch(fileName, _2DB.FILENAME_PATTERN, RegexOptions.IgnoreCase) || Regex.IsMatch(fileName, _2DB.FILENAME_OLD_PATTERN, RegexOptions.IgnoreCase)) { if (fi.Exists) { tduFile = new _2DB(fileName); } else { tduFile = new _2DB(); } } // MAP else if (Regex.IsMatch(fileName, MAP.FILENAME_PATTERN, RegexOptions.IgnoreCase)) { if (fi.Exists) { tduFile = new MAP(fileName); } else { tduFile = new MAP(); } } // XMB else if (Regex.IsMatch(fileName, XMB.FILENAME_PATTERN, RegexOptions.IgnoreCase)) { if (fi.Exists) { tduFile = new XMB(fileName); } else { tduFile = new XMB(); } } // WAV + XMB_WAV else if (Regex.IsMatch(fileName, XMB_WAV.FILENAME_PATTERN, RegexOptions.IgnoreCase)) { try { if (fi.Exists) { tduFile = new XMB_WAV(fileName); } else { tduFile = new XMB_WAV(); } } catch (FormatException) { // standard WAV file } } // PCH else if (Regex.IsMatch(fileName, PCH.FILENAME_PATTERN, RegexOptions.IgnoreCase)) { tduFile = new PCH(fileName); } // DB Resources else if (Regex.IsMatch(fileName, DBResource.FILENAME_PATTERN, RegexOptions.IgnoreCase)) { if (fi.Exists) { tduFile = new DBResource(fileName); } else { tduFile = new DBResource(); } } // DFE else if (Regex.IsMatch(fileName, DFE.FILENAME_PATTERN, RegexOptions.IgnoreCase)) { tduFile = new DFE(fileName); } // IGE else if (Regex.IsMatch(fileName, IGE.FILENAME_PATTERN, RegexOptions.IgnoreCase)) { tduFile = new IGE(fileName); } // Regular by default else { tduFile = new Regular(); } // To update common information tduFile._FinalizeLoading(fileName); return(tduFile); }
/// <summary> /// Loads vehicle data from database and reference /// </summary> /// <param name="slotRef">Reference of vehicle slot to load</param> private void _LoadVehicleData(string slotRef) { if (string.IsNullOrEmpty(slotRef)) { return; } Cursor = Cursors.WaitCursor; try { StatusBarLogManager.ShowEvent(this, _STATUS_LOADING_VEHICLE); // Cleaning tasks _ClearCurrentTasks(); _CurrentVehicle = slotRef; _CurrentSlotName = VehicleSlotsHelper.SlotReferenceReverse[slotRef]; // Loading database DB.Culture currentCulture = Program.ApplicationSettings.GetCurrentCulture(); EditHelper.Task[] currentTasks; string dbBnkFile = Program.ApplicationSettings.TduMainFolder + LibraryConstants.FOLDER_DB + DB.GetBNKFileName(DB.Culture.Global); BNK bnkFile = TduFile.GetFile(dbBnkFile) as BNK; string resourceBnkFile = Program.ApplicationSettings.TduMainFolder + LibraryConstants.FOLDER_DB + DB.GetBNKFileName(currentCulture); BNK rBnkFile = TduFile.GetFile(resourceBnkFile) as BNK; // 1.CarRims TduFile[] currentFiles = DatabaseHelper.LoadTopicForEdit(DB.Topic.CarRims, DB.Culture.Global, bnkFile, rBnkFile, out currentTasks); _CurrentCarRimsTask = currentTasks[0]; _CarRimsTable = currentFiles[0] as DB; // 2.Rims currentFiles = DatabaseHelper.LoadTopicForEdit(DB.Topic.Rims, currentCulture, bnkFile, rBnkFile, out currentTasks); _CurrentRimsTask = currentTasks[0]; _CurrentRimsResourceTask = currentTasks[1]; _RimsTable = currentFiles[0] as DB; _RimsResource = currentFiles[1] as DBResource; // 3.CarPhysicsData currentFiles = DatabaseHelper.LoadTopicForEdit(DB.Topic.CarPhysicsData, currentCulture, bnkFile, rBnkFile, out currentTasks); _CurrentPhysicsTask = currentTasks[0]; _CurrentPhysicsResourceTask = currentTasks[1]; _PhysicsTable = currentFiles[0] as DB; _PhysicsResource = currentFiles[1] as DBResource; // 4.Brands currentFiles = DatabaseHelper.LoadTopicForEdit(DB.Topic.Brands, currentCulture, bnkFile, rBnkFile, out currentTasks); _CurrentBrandsTask = currentTasks[0]; _CurrentBrandsResourceTask = currentTasks[1]; _BrandsTable = currentFiles[0] as DB; _BrandsResource = currentFiles[1] as DBResource; // 5.CarShops currentFiles = DatabaseHelper.LoadTopicForEdit(DB.Topic.CarShops, currentCulture, bnkFile, rBnkFile, out currentTasks); _CurrentCarShopsTask = currentTasks[0]; _CurrentCarShopsResourceTask = currentTasks[1]; _CarShopsTable = currentFiles[0] as DB; _CarShopsResource = currentFiles[1] as DBResource; // 6.CarPacks currentFiles = DatabaseHelper.LoadTopicForEdit(DB.Topic.CarPacks, DB.Culture.Global, bnkFile, rBnkFile, out currentTasks); _CurrentCarPacksTask = currentTasks[0]; _CarPacksTable = currentFiles[0] as DB; // 7.Colors currentFiles = DatabaseHelper.LoadTopicForEdit(DB.Topic.CarColors, currentCulture, bnkFile, rBnkFile, out currentTasks); _CurrentCarColorsTask = currentTasks[0]; _CurrentCarColorsResourceTask = currentTasks[1]; _CarColorsTable = currentFiles[0] as DB; _CarColorsResource = currentFiles[1] as DBResource; // 8.Interior currentFiles = DatabaseHelper.LoadTopicForEdit(DB.Topic.Interior, currentCulture, bnkFile, rBnkFile, out currentTasks); _CurrentInteriorTask = currentTasks[0]; _CurrentInteriorResourceTask = currentTasks[1]; _InteriorTable = currentFiles[0] as DB; _InteriorResource = currentFiles[1] as DBResource; // 9.Colors id reference ColorsHelper.InitIdReference(_CarColorsResource, _InteriorResource); // 10.Cameras string camBinFile = LibraryConstants.GetSpecialFile(LibraryConstants.TduSpecialFile.CamerasBin); _CameraData = TduFile.GetFile(camBinFile) as Cameras; /* GUI */ // Install Tab _InitializeInstallContents(); // Camera-IK Tab _RefreshCameraIKContents(); // Datasheet tab _InitializeDatasheetContents(); // Dealers tab _InitializeDealersContents(); // Tuner tab _InitializeTunerContents(); // Physics tab _InitializePhysicsContents(); // Colors tab _InitializeColorsContents(); // Modification flags _IsDatabaseModified = false; _IsCameraModified = false; // Clearing state vars _CurrentAvailabilitySpot = null; _CurrentTuningBrand = null; // Vehicle name display _UpdateSlotAndModName(); // Tabs are enabled vehicleEditTabControl.Enabled = true; StatusBarLogManager.ShowEvent(this, _STATUS_VEHICLE_READY); } catch (Exception ex) { // All tasks must be cleaned _ClearCurrentTasks(); // Processing special error messages if (EditHelper.ERROR_CODE_TASK_EXISTS.Equals(ex.Message)) { MessageBoxes.ShowError(this, new Exception(_ERROR_LOADING_VEHICLE_CONFLICT, ex)); } else { MessageBoxes.ShowError(this, new Exception(_ERROR_LOADING_VEHICLE, ex)); } StatusBarLogManager.ShowEvent(this, ""); } Cursor = Cursors.Default; }
/// <summary> /// Manages the drop event for all picture boxes /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _ManageDragDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { Cursor = Cursors.WaitCursor; // Testing dropped file string[] fileList = (string[])e.Data.GetData(DataFormats.FileDrop); string bnkFileName = fileList[0]; try { BNK bnkFile = TduFile.GetFile(bnkFileName) as BNK; if (bnkFile == null || !bnkFile.Exists) { throw new Exception(); } } catch (Exception ex) { MessageBoxes.ShowError(this, new Exception(_ERROR_DROP_BNK_INVALID, ex)); } // According to sender if (sender == extModelBox) { _InstallExtModelFile = bnkFileName; extModelCheckBox.Checked = true; } else if (sender == intModelBox) { _InstallIntModelFile = bnkFileName; intModelCheckBox.Checked = true; } else if (sender == rimsFrontBox) { _InstallFrontRimsFile = bnkFileName; rimsFrontCheckBox.Checked = true; } else if (sender == rimsRearBox) { _InstallRearRimsFile = bnkFileName; rimsRearCheckBox.Checked = true; } else if (sender == gaugesLowBox) { _InstallLowGaugesFile = bnkFileName; gaugesLowCheckBox.Checked = true; } else if (sender == gaugesHighBox) { _InstallHighGaugesFile = bnkFileName; gaugesHighCheckBox.Checked = true; } else if (sender == soundBox) { _InstallSoundFile = bnkFileName; soundCheckBox.Checked = true; } StatusBarLogManager.ShowEvent(this, _STATUS_SETTING_BNK_OK); Cursor = Cursors.Default; } }
/// <summary> /// What the instruction should do /// </summary> protected override void _Process() { // Checking parameter string vehicleRef = _GetParameter(PatchInstructionParameter.ParameterName.vehicleDatabaseId); // Modifying corresponding topic EditHelper.Task dbTask = new EditHelper.Task(); string bnkFilePath = ""; try { string dbFileName = null; // 1. Creating edit task try { bnkFilePath = string.Concat(LibraryConstants.GetSpecialFolder(LibraryConstants.TduSpecialFolder.Database), DB.GetBNKFileName(DB.Culture.Global)); BNK databaseBNK = TduFile.GetFile(bnkFilePath) as BNK; if (databaseBNK != null) { dbFileName = DB.GetFileName(DB.Culture.Global, DB.Topic.CarShops); dbTask = EditHelper.Instance.AddTask(databaseBNK, databaseBNK.GetPackedFilesPaths(dbFileName)[0], true); } } catch (Exception ex) { throw new Exception("Unable to create edit task on BNK file: " + bnkFilePath, ex); } // 2. Getting TduFile DB db; try { db = TduFile.GetFile(dbTask.extractedFile) as DB; if (db == null || !db.Exists) { throw new Exception("Extracted db file not found!"); } } catch (Exception ex) { throw new Exception("Unable to gain access to DB contents: " + dbFileName, ex); } // 3. Setting values in DB file DatabaseHelper.RemoveValueFromAnyColumn(db, vehicleRef, DatabaseConstants.COMPACT1_PHYSICS_DB_RESID); Log.Info("Entry updating completed: " + vehicleRef); // 4. Saving try { db.Save(); EditHelper.Instance.ApplyChanges(dbTask); } catch (Exception ex) { throw new Exception("Unable to save BNK file: " + bnkFilePath, ex); } } finally { // Cleaning up EditHelper.Instance.RemoveTask(dbTask); } }
/// <summary> /// What the instruction should do /// </summary> protected override void _Process() { // Parameters string vehicleName = _GetParameter(PatchInstructionParameter.ParameterName.slotFullName); string cameraId = _GetParameter(PatchInstructionParameter.ParameterName.cameraIKIdentifier); // Loading reference VehicleSlotsHelper.InitReference(PatchHelper.CurrentPath); // Checking validity if (!VehicleSlotsHelper.SlotReference.ContainsKey(vehicleName)) { throw new Exception("Specified vehicle name is not supported: " + vehicleName); } if (!VehicleSlotsHelper.CamReference.ContainsKey(cameraId)) { throw new Exception("Specified camera identifier is not supported: " + cameraId); } // Edit task EditHelper.Task task = new EditHelper.Task(); try { try { string bnkFileName = string.Concat(LibraryConstants.GetSpecialFolder(LibraryConstants.TduSpecialFolder.Database), DB.GetBNKFileName(DB.Culture.Global)); BNK dbBnkFile = TduFile.GetFile(bnkFileName) as BNK; if (dbBnkFile != null) { string dbFilePath = dbBnkFile.GetPackedFilesPaths(DB.GetFileName(DB.Culture.Global, DB.Topic.CarPhysicsData))[0]; task = EditHelper.Instance.AddTask(dbBnkFile, dbFilePath, true); } } catch (Exception ex) { throw new Exception("Unable to get TDU database contents in DB.BNK.", ex); } // Opens packed file DB physicsDB = TduFile.GetFile(task.extractedFile) as DB; if (physicsDB == null) { throw new Exception("Unable to get CarPhysicsData information."); } // Changes camera try { string vehicleRef = VehicleSlotsHelper.SlotReference[vehicleName]; VehicleSlotsHelper.ChangeCameraById(vehicleRef, cameraId, physicsDB); } catch (Exception ex) { throw new Exception("Unable to use new camera set: " + cameraId + " for " + vehicleName, ex); } // Saving try { physicsDB.Save(); EditHelper.Instance.ApplyChanges(task); EditHelper.Instance.RemoveTask(task); } catch (Exception ex) { throw new Exception("Unable to save and replace file in BNK.", ex); } } finally { EditHelper.Instance.RemoveTask(task); } }
/// <summary> /// What the instruction should do /// </summary> protected override void _Process() { // Checking parameters string fileName = _GetParameter(PatchInstructionParameter.ParameterName.resourceFileName); string values = _GetParameter(PatchInstructionParameter.ParameterName.resourceValues); // For each language file DB.Topic currentTopic = (DB.Topic)Enum.Parse(typeof(DB.Topic), fileName); for (int i = 0; i < 8; i++) { DB.Culture currentCulture = (DB.Culture)Enum.Parse(typeof(DB.Culture), i.ToString()); EditHelper.Task resourceTask = new EditHelper.Task(); string bnkFilePath = ""; string resourceFileName = null; // 1. Creating edit task try { bnkFilePath = string.Concat(LibraryConstants.GetSpecialFolder(LibraryConstants.TduSpecialFolder.Database), DB.GetBNKFileName(currentCulture)); BNK databaseBNK = TduFile.GetFile(bnkFilePath) as BNK; if (databaseBNK != null) { resourceFileName = DB.GetFileName(currentCulture, currentTopic); resourceTask = EditHelper.Instance.AddTask(databaseBNK, databaseBNK.GetPackedFilesPaths(resourceFileName)[0], true); } } catch (Exception ex) { throw new Exception("Unable to create edit task on BNK file: " + bnkFilePath, ex); } // 2. Getting TduFile DBResource resource; try { resource = TduFile.GetFile(resourceTask.extractedFile) as DBResource; if (resource == null || !resource.Exists) { throw new Exception("Extracted resource db file not found!"); } } catch (Exception ex) { throw new Exception("Unable to gain access to DB contents: " + resourceFileName, ex); } // 3. Setting values in DB file List <Couple <string> > couples = Tools.ParseCouples(values); // Parsing couples foreach (Couple <string> couple in couples) { string id = couple.FirstValue; string value = couple.SecondValue; // Does id exist ? DBResource.Entry currentEntry = resource.GetEntryFromId(id); if (currentEntry.isValid) { // Already exists > modify it currentEntry.value = value; resource.UpdateEntry(currentEntry); Log.Info("Entry succesfully updated : " + id + " - " + value); } else { // Does not exist > create it currentEntry.isValid = true; currentEntry.id = new ResourceIdentifier(id, currentTopic); currentEntry.value = value; currentEntry.index = resource.EntryList.Count + 1; resource.InsertEntry(currentEntry); Log.Info("Entry succesfully added : " + id + " - " + value); } } // 4. Saving try { resource.Save(); EditHelper.Instance.ApplyChanges(resourceTask); } catch (Exception ex) { throw new Exception("Unable to save BNK file: " + bnkFilePath, ex); } // 5. Cleaning up EditHelper.Instance.RemoveTask(resourceTask); } }
/// <summary> /// What the instruction should do /// </summary> protected override void _Process() { // Checking parameter string vehicleRef = _GetParameter(PatchInstructionParameter.ParameterName.vehicleDatabaseId); string spotAndSlots = _GetParameter(PatchInstructionParameter.ParameterName.resourceValues); // Modifying corresponding topic EditHelper.Task dbTask = new EditHelper.Task(); string bnkFilePath = ""; try { string dbFileName = null; // 1. Creating edit task try { bnkFilePath = string.Concat(LibraryConstants.GetSpecialFolder(LibraryConstants.TduSpecialFolder.Database), DB.GetBNKFileName(DB.Culture.Global)); BNK databaseBNK = TduFile.GetFile(bnkFilePath) as BNK; if (databaseBNK != null) { dbFileName = DB.GetFileName(DB.Culture.Global, DB.Topic.CarShops); dbTask = EditHelper.Instance.AddTask(databaseBNK, databaseBNK.GetPackedFilesPaths(dbFileName)[0], true); } } catch (Exception ex) { throw new Exception("Unable to create edit task on BNK file: " + bnkFilePath, ex); } // 2. Getting TduFile DB db; try { db = TduFile.GetFile(dbTask.extractedFile) as DB; if (db == null || !db.Exists) { throw new Exception("Extracted db file not found!"); } } catch (Exception ex) { throw new Exception("Unable to gain access to DB contents: " + dbFileName, ex); } // 3. Setting values in DB file // One identifier (primary key: REF) List <Couple <string> > couples = Tools.ParseCouples(spotAndSlots); // Parsing couples foreach (Couple <string> couple in couples) { string spotRef = couple.FirstValue; string[] slots = couple.SecondValue.Split(new string[] { Tools.SYMBOL_VALUE_SEPARATOR3 }, StringSplitOptions.RemoveEmptyEntries); // Does id exist ? if (db.EntriesByPrimaryKey.ContainsKey(spotRef)) { // Already exists > modify it foreach (string anotherSlot in slots) { string slotColumnName = string.Format(DatabaseConstants.SLOT_CARSHOPS_PATTERN_DB_COLUMN, anotherSlot); DatabaseHelper.UpdateCellFromTopicWherePrimaryKey(db, slotColumnName, spotRef, vehicleRef); } Log.Info("Entry updating completed for spot: " + spotRef + " - " + couple.SecondValue); } else { Log.Error("Specified location does not exist! " + spotRef, null); } } Log.Info("Entry updating completed for vehicle: " + vehicleRef); // 4. Saving try { db.Save(); EditHelper.Instance.ApplyChanges(dbTask); } catch (Exception ex) { throw new Exception("Unable to save BNK file: " + bnkFilePath, ex); } } finally { // Cleaning up EditHelper.Instance.RemoveTask(dbTask); } }
/// <summary> /// Met à jour la liste de fichiers dans le répertoire courant /// </summary> /// <param name="selectedNode">Noeud sélectionné</param> /// <param name="keepSelection">true to keep previous item selected in file list</param> private void _RefreshFileList(TreeNode selectedNode, bool keepSelection) { // ANO 15 : sauvegarde de la sélection de fichier courante if (keepSelection) { ListView2.StoreSelectedIndex(bnkListView); } // Effacement des listes et contexte bnkListView.Items.Clear(); _ClearContentLists(); _CurrentBnkFile = null; // Mise à jour statuts bnkStatusLabel.Text = bnkStatusLabelCountSize.Text = ""; StatusBarLogManager.ShowEvent(this, _STATUS_NO_BNK_SELECTED); if (selectedNode == null) { return; } try { Cursor = Cursors.WaitCursor; string currentFolder = (string)selectedNode.Tag; DirectoryInfo di = new DirectoryInfo(currentFolder); FileInfo[] fileList = di.GetFiles(); long totalSize = 0; foreach (FileInfo anotherBnk in fileList) { // File name check bool isNameValid = false; foreach (string anotherPattern in _ALLOWED_FILENAME_PATTERNS) { if (Regex.IsMatch(anotherBnk.Name, anotherPattern, RegexOptions.IgnoreCase)) { isNameValid = true; break; } } if (isNameValid) { // On ajoute l'élément ListViewItem newItem = new ListViewItem(anotherBnk.Name) { ImageIndex = _GetImageIndexFromFilename(anotherBnk.Name) }; // L'image dépend de l'extension // EVO_42 : nouvelles icônes string typeDesc = TduFile.GetTypeDescription(anotherBnk.Name); // EVO_57 : Infos supplémentaires pour la vue détaillée // Taille long currentSize = anotherBnk.Length; newItem.SubItems.Add(currentSize.ToString()); totalSize += currentSize; // Type newItem.SubItems.Add(typeDesc); // Tooltip ! newItem.ToolTipText = string.Format(_TOOLTIP_STD_FILE, typeDesc, anotherBnk.Length); bnkListView.Items.Add(newItem); } } // Mise à jour statut bnkStatusLabel.Text = currentFolder; if (bnkListView.Items.Count == 0) { bnkStatusLabelCountSize.Text = _STATUS_COUNT_SIZE_NO; } else { bnkStatusLabelCountSize.Text = string.Format(_STATUS_COUNT_SIZE_CONTENTS, bnkListView.Items.Count, totalSize); } // Rétablit le fichier sélectionné if (keepSelection) { ListView2.RestoreSelectedIndex(bnkListView); // ANO_21 : le contenu du BNK est à actualiser bnkListView_SelectedIndexChanged(this, new EventArgs()); } Cursor = Cursors.Default; } catch (Exception ex) { MessageBoxes.ShowError(this, ex); } }