private void SavePackages()
        {
            //The user is influenced to believe a Save event will only
            //save the ActivePackage but really it will save all of them.
            //Code is in place to prevent the user from editing one package then
            //trying to load another without saving the first.

            //At this point the XmlRootData object is stale and needs to be
            //repopulated with the Packages collection.
            XmlPackageData.Descendants("Package").Remove();

            //But the ActivePackage may have its Web Resources modified and they
            //need to be added back to the ActivePackage.
            if (ActivePackage != null)
            {
                ActivePackage.Elements("WebResourceInfo").Remove();
                ActivePackage.Add(WebResourceInfos.ToArray());
            }

            XmlPackageData.Element("Packages").Add(Packages.ToArray());

            XmlPackageData.Save(PACKAGES_FILENAME);

            IsActivePackageDirty = false;
        }
Example #2
0
        /// <summary>
        /// Exports the given asset
        /// </summary>
        /// <param name="asset"></param>
        private void ExportAsset(Asset asset)
        {
            try
            {
                Log(string.Format("Exporting {0}", Path.GetFileNameWithoutExtension(asset.Name)), "INFO");

                switch (asset.Type)
                {
                case "Mesh":
                    ExportModel(asset.PackageEntry, Path.Combine("exported_files", asset.Name));
                    break;

                case "Texture":
                    ExportImage(asset.PackageEntry, Path.Combine("exported_files", asset.Name));
                    break;

                case "MotionList":
                    ExportMotionList(asset.PackageEntry, Path.Combine("exported_files", asset.Name));
                    break;

                default:
                    ExportUnknownFile(asset.PackageEntry, Path.Combine("exported_files", asset.Name));
                    break;
                }

                Log(string.Format("Exported {0}", Path.GetFileNameWithoutExtension(asset.Name)), "INFO");
            }
            catch (Exception e)
            {
#if DEBUG
                File.WriteAllBytes("BAD_BUFFER.dat", ActivePackage.LoadEntry(asset.PackageEntry));
#endif
                Log(string.Format("Error has occured while exporting {0}: {1}", Path.GetFileNameWithoutExtension(asset.Name), e), "ERROR");
            }
        }
Example #3
0
        /// <summary>
        /// Exports a Motion List Asset
        /// </summary>
        private string ExportMotionList(Package.Entry entry, string name)
        {
            var scale   = float.TryParse(Settings["ModelScale", "1.0"], out var val) ? val : 1.0f;
            var motions = MotionList.Convert(ActivePackage.LoadEntry(entry));

            var path   = name.Split('.')[0];
            var folder = Path.Combine(path, motions.Item1);

            var result = path;

            Directory.CreateDirectory(folder);

            foreach (var motion in motions.Item2)
            {
                var motionPath = Path.Combine(folder, motion.Item1);

                if (Settings["ExportSEAnim", "Yes"] == "Yes")
                {
                    motion.Item2.Scale(scale);
                    motion.Item2.ToSEAnim(motionPath + ".seanim");
                }
            }

            return(result);
        }
        //Misc
        private void ShowBrowseFolderDialog()
        {
            System.Windows.Forms.FolderBrowserDialog dlgWRFolder = new System.Windows.Forms.FolderBrowserDialog()
            {
                Description         = "Select the folder containing the potential Web Resource files",
                ShowNewFolderButton = false
            };
            if (dlgWRFolder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                IsActivePackageDirty = false;

                //Because Web Resources are relative to the root path,
                //all the current Web ResourceInfos should be cleared
                WebResourceInfos.Clear();
                WebResourceInfosSelected.Clear();

                //Change the rootpath and notify all bindings
                ActivePackage.Attribute("rootPath").Value = dlgWRFolder.SelectedPath;
                OnPropertyChanged("ActivePackage");

                //Auto-save
                SavePackages();

                //Display new files
                SearchAndPopulateFiles();
            }
        }
        private void SearchAndPopulateFiles()
        {
            if (ActivePackage == null)
            {
                return;
            }

            string searchText = FileSearchText; //Find all files

            string rootPath = ActivePackage.Attribute("rootPath").Value;

            DiscoverFiles(rootPath, searchText);
        }
        private XElement ConvertFileInfoToWebResourceInfo(FileInfo fi)
        {
            var    x    = fi.Extension.Split('.');
            string type = x[x.Length - 1].ToLower();

            String name = fi.FullName.Replace(ActivePackage.Attribute("rootPath").Value.Replace("/", "\\"), String.Empty);

            XElement newWebResourceInfo = new XElement("WebResourceInfo",
                                                       new XAttribute("name", name.Replace("\\", "/")),
                                                       new XAttribute("filePath", name),
                                                       new XAttribute("displayName", fi.Name),
                                                       new XAttribute("type", type),
                                                       new XAttribute("description", String.Empty));

            return(newWebResourceInfo);
        }
Example #7
0
        /// <summary>
        /// Exports the Image Asset
        /// </summary>
        private string ExportImage(Package.Entry entry, string name)
        {
            var path   = name.Split('.')[0];
            var result = path + ".png";

            bool requiresExport = false;

            // Determine if we should even bother loading
            foreach (var format in ImageFormats)
            {
                // PNG is default
                if (Settings["Export" + format.ToUpper(), format == "png" ? "Yes" : "No"] == "Yes")
                {
                    // Set our path to the last exported type
                    result = path + "." + format;

                    if (!File.Exists(path + "." + format))
                    {
                        requiresExport = true;
                    }
                }
            }

            if (requiresExport)
            {
                using (var image = Texture.Convert(ActivePackage.LoadEntry(entry)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(path));

                    foreach (var format in ImageFormats)
                    {
                        if (Settings["Export" + format.ToUpper(), format == "png" ? "Yes" : "No"] == "Yes" && !File.Exists(path + "." + format))
                        {
                            // Everything besides DDS we need to decompress & convert
                            if (format != "dds")
                            {
                                image.ConvertImage(ScratchImage.DXGIFormat.R8G8B8A8UNORM);
                            }

                            image.Save(path + "." + format);
                        }
                    }
                }
            }

            return(result);
        }
Example #8
0
 public override void HandleInput(DateTime time, string input)
 {
     ThrowIfNotInitialized();
     InputEnabled = false;
     if (!string.IsNullOrEmpty(input.Trim()))
     {
         if (!ActivePackage.HandleInput(time, input))
         {
             SayInfoLineIfDebug("Input handled by HOME package.");
             if (!HomePackage.HandleInput(time, input))
             {
                 SayCouldNotUnderstand(input);
             }
         }
     }
     Prompt();
 }
        private void CreateWebResource(XElement webResourceInfo)
        {
            try
            {
                //Create the Web Resource.
                WebResource wr = new WebResource()
                {
                    Content     = getEncodedFileContents(ActivePackage.Attribute("rootPath").Value + webResourceInfo.Attribute("filePath").Value),
                    DisplayName = webResourceInfo.Attribute("displayName").Value,
                    Description = webResourceInfo.Attribute("description").Value,
                    LogicalName = WebResource.EntityLogicalName,
                    Name        = GetWebResourceFullNameIncludingPrefix(webResourceInfo)
                };

                wr.WebResourceType = new OptionSetValue((int)ResourceExtensions.ConvertStringExtension(webResourceInfo.Attribute("type").Value));

                //Special cases attributes for different web resource types.
                switch (wr.WebResourceType.Value)
                {
                case (int)ResourceExtensions.WebResourceType.Silverlight:
                    wr.SilverlightVersion = "4.0";
                    break;
                }

                // ActivePublisher.CustomizationPrefix + "_/" + ActivePackage.Attribute("name").Value + webResourceInfo.Attribute("name").Value.Replace("\\", "/"),
                Guid theGuid = _serviceProxy.Create(wr);

                //If not the "Default Solution", create a SolutionComponent to assure it gets
                //associated with the ActiveSolution. Web Resources are automatically added
                //as SolutionComponents to the Default Solution.
                if (ActiveSolution.UniqueName != "Default")
                {
                    AddSolutionComponentRequest scRequest = new AddSolutionComponentRequest();
                    scRequest.ComponentType      = (int)componenttype.WebResource;
                    scRequest.SolutionUniqueName = ActiveSolution.UniqueName;
                    scRequest.ComponentId        = theGuid;
                    var response = (AddSolutionComponentResponse)_serviceProxy.Execute(scRequest);
                }
            }
            catch (Exception e)
            {
                AddMessage("Error: " + e.Message);
                return;
            }
        }
        private string GetWebResourceFullNameIncludingPrefix(XElement webResourceInfo)
        {
            //The Web Resource name always starts with the Publisher's Prefix
            //i.e., "new_"
            string name = ActivePublisher.CustomizationPrefix + "_";

            //Check to see if the user has chosen to add the Package Name as part of the
            //prefix.
            if (!String.IsNullOrWhiteSpace(ActivePackage.Attribute("isNamePrefix").Value) &&
                Boolean.Parse(ActivePackage.Attribute("isNamePrefix").Value) == true)
            {
                name += "/" + ActivePackage.Attribute("name").Value;
            }

            //Finally add the name on to the prefix
            name += webResourceInfo.Attribute("name").Value;

            return(name);
        }
 private void UpdateWebResource(XElement webResourceInfo, WebResource existingResource)
 {
     try
     {
         //These are the only 3 things that should (can) change.
         WebResource wr = new WebResource()
         {
             Content     = getEncodedFileContents(ActivePackage.Attribute("rootPath").Value + webResourceInfo.Attribute("filePath").Value),
             DisplayName = webResourceInfo.Attribute("displayName").Value,
             Description = webResourceInfo.Attribute("description").Value
         };
         wr.WebResourceId = existingResource.WebResourceId;
         _serviceProxy.Update(wr);
     }
     catch (Exception e)
     {
         AddMessage("Error: " + e.Message);
         return;
     }
 }
        private void LoadWebResourceInfos()
        {
            if (ActivePackage == null)
            {
                return;
            }

            //As always, clear the collection first.
            WebResourceInfos.Clear();
            WebResourceInfosSelected.Clear();

            var webResourceInfos = ActivePackage.Elements("WebResourceInfo");

            if (webResourceInfos != null)
            {
                foreach (var wr in webResourceInfos)
                {
                    WebResourceInfos.Add(wr);
                }
            }
        }
Example #13
0
        /// <summary>
        /// Opens file dialog to open a package
        /// </summary>
        private void OpenFileClick(object sender, RoutedEventArgs e)
        {
            ViewModel.Assets.ClearAssets();
            ActivePackage?.Dispose();
            ActivePackage = null;
            GC.Collect();

            var dialog = new OpenFileDialog()
            {
                Title  = "Tyrant | Open File",
                Filter = "Package files (*.pak)|*.pak|All files (*.*)|*.*"
            };

            if (dialog.ShowDialog() == true)
            {
                if (Path.GetExtension(dialog.FileName).ToLower() == ".pak")
                {
                    LoadPackage(dialog.FileName);
                }
            }
        }
Example #14
0
        /// <summary>
        /// Loads a Package
        /// </summary>
        public void LoadPackage(string path)
        {
            try
            {
                ViewModel.Assets.ClearAssets();
                ActivePackage?.Dispose();
                ActivePackage = new Package(path);

                List <Asset> results = new List <Asset>(ActivePackage.Entries.Count);

                foreach (var entry in ActivePackage.Entries)
                {
                    if (Cache.Entries.TryGetValue(entry.Key, out var name))
                    {
                        string type = "Unknown";

                        if (name.Contains(".tex."))
                        {
                            if (Settings["ShowTextures", "Yes"] == "Yes")
                            {
                                type = "Texture";
                            }
                            else
                            {
                                continue;
                            }
                        }
                        else if (name.Contains(".mesh."))
                        {
                            if (Settings["ShowModels", "Yes"] == "Yes")
                            {
                                type = "Mesh";
                            }
                            else
                            {
                                continue;
                            }
                        }
                        else if (name.Contains(".motlist."))
                        {
                            if (Settings["ShowAnims", "Yes"] == "Yes")
                            {
                                type = "MotionList";
                            }
                            else
                            {
                                continue;
                            }
                        }
                        else if (name.Contains(".mot."))
                        {
                            if (Settings["ShowAnims", "Yes"] == "Yes")
                            {
                                type = "Motion";
                            }
                            else
                            {
                                continue;
                            }
                        }
                        //else if (name.Contains(".bnk.") && Settings["ShowSounds", "Yes"] == "Yes")
                        //    type = "SoundBank";
                        else if (Settings["ShowAll", "No"] == "Yes")
                        {
                            type = "Unknown";
                        }
                        else
                        {
                            continue;
                        }

                        results.Add(new Asset(name, type, entry.Value));
                    }
                    else if (Settings["ShowAll", "No"] == "Yes")
                    {
                        results.Add(new Asset("asset_" + entry.Key.ToString("x"), "Unknown", entry.Value));
                    }
                }

                ViewModel.Assets.AddAssets(results.OrderBy(x => x.Name).OrderBy(x => x.Type));
            }
            catch (Exception e)
            {
                ActivePackage?.Dispose();
                ActivePackage = null;

                MessageBox.Show(string.Format("An error occured while loading the package:\n\n{0}", e), "Tryant | Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Example #15
0
        private void ExportUnknownFile(Package.Entry entry, string name)
        {
            Directory.CreateDirectory(Path.GetDirectoryName(name));

            File.WriteAllBytes(name, ActivePackage.LoadEntry(entry));
        }
Example #16
0
        /// <summary>
        /// Exports a Model Asset
        /// </summary>
        private void ExportModel(Package.Entry entry, string name)
        {
            var scale  = float.TryParse(Settings["ModelScale", "1.0"], out var val) ? val : 1.0f;
            var models = Mesh.Convert(ActivePackage.LoadEntry(entry));

            var path = name.Split('.')[0];

            var materials = new Dictionary <string, Model.Material>();

            // Attempt to load the materials file
            foreach (var prefix in FileSuffixes)
            {
                if (ActivePackage.Entries.TryGetValue(MurMur3.Calculate(Encoding.Unicode.GetBytes(path.Replace("exported_files\\", "") + prefix)), out var result))
                {
                    try
                    {
                        materials = MaterialDefs.Convert(ActivePackage.LoadEntry(result), prefix.Split('.').Last());
                        break;
                    }
                    catch
                    {
                        continue;
                    }
                }
            }


            var folder = Path.GetDirectoryName(path);

            Directory.CreateDirectory(folder);

            for (int mdl = 0; mdl < models.Count; mdl++)
            {
                for (int lod = 0; lod < models[mdl].Count; lod++)
                {
                    // Must generate for formats that need it
                    models[mdl][lod].GenerateGlobalBoneData();
                    models[mdl][lod].Scale(scale);

                    foreach (var material in models[mdl][lod].Materials)
                    {
                        if (materials.TryGetValue(material.Name, out var fileMtl))
                        {
                            material.Images   = fileMtl.Images;
                            material.Settings = fileMtl.Settings;

                            // Determine image keys as they change depending on shader/type
                            if (material.Images.ContainsKey("BaseMetalMap"))
                            {
                                material.DiffuseMapName = "BaseMetalMap";
                            }
                            else if (material.Images.ContainsKey("BaseMap"))
                            {
                                material.DiffuseMapName = "BaseMap";
                            }

                            if (material.Images.ContainsKey("NormalRoughnessMap"))
                            {
                                material.NormalMapName = "NormalRoughnessMap";
                            }
                            else if (material.Images.ContainsKey("NormalMap"))
                            {
                                material.NormalMapName = "NormalMap";
                            }
                        }
                    }

                    foreach (var material in models[mdl][lod].Materials)
                    {
                        if (Settings["ExportMaterialInfo", "Yes"] == "Yes")
                        {
                            ExportMaterialInfo(material, Path.Combine(folder, material.Name + ".txt"));
                        }

                        if (Settings["ExportImagesWithModel", "Yes"] == "Yes")
                        {
                            ExportMaterialImages(material, folder);
                        }
                    }

                    var result = Path.Combine(folder, string.Format("{0}_model{1}_lod{2}", Path.GetFileNameWithoutExtension(path), mdl, lod));

                    foreach (var format in ModelFormats)
                    {
                        // PNG is default
                        if (Settings["Export" + format.ToUpper(), format == "semodel" ? "Yes" : "No"] == "Yes")
                        {
                            models[mdl][lod].Save(result + "." + format);
                        }
                    }
                }
            }
        }
Example #17
0
 /// <summary>
 /// Handles cleaning up on close
 /// </summary>
 private void MainWindowClosing(object sender, CancelEventArgs e)
 {
     ActivePackage?.Dispose();
     Settings.Save("Settings.tcfg");
 }