Ejemplo n.º 1
0
        public static void GetObjectInfos(string fileName, Dictionary <string, List <ObjectInfo> > infosByListName)
        {
            string levelName;
            string categoryName;

            string levelNameWithSuffix = Path.GetFileName(fileName);

            if (fileName.EndsWith(SM3DWorldZone.MAP_SUFFIX))
            {
                levelName    = levelNameWithSuffix.Remove(levelNameWithSuffix.Length - SM3DWorldZone.MAP_SUFFIX.Length);
                categoryName = "Map";
            }
            else if (fileName.EndsWith(SM3DWorldZone.DESIGN_SUFFIX))
            {
                levelName    = levelNameWithSuffix.Remove(levelNameWithSuffix.Length - SM3DWorldZone.DESIGN_SUFFIX.Length);
                categoryName = "Design";
            }
            else if (fileName.EndsWith(SM3DWorldZone.SOUND_SUFFIX))
            {
                levelName    = levelNameWithSuffix.Remove(levelNameWithSuffix.Length - SM3DWorldZone.SOUND_SUFFIX.Length);
                categoryName = "Sound";
            }
            else
            {
                return;
            }

            SarcData sarc = SARC.UnpackRamN(YAZ0.Decompress(fileName));

            GetObjectInfos(infosByListName, levelName, categoryName, sarc);
        }
Ejemplo n.º 2
0
        public static bool TryOpen(string filename, out StageList stageList)
        {
            stageList = null;

            SarcData sarc = SARC.UnpackRamN(YAZ0.Decompress(filename));

            BymlFileData byml;

            if (sarc.Files.ContainsKey("StageList.byml"))
            {
                byml = ByamlFile.LoadN(new MemoryStream(sarc.Files["StageList.byml"]), true, ByteOrder.BigEndian);
            }
            else
            {
                throw new Exception("Failed to find the StageList");
            }


            if (!byml.RootNode.TryGetValue("WorldList", out dynamic worldList))
            {
                return(false);
            }


            List <World> worlds = new List <World>();

            for (int i = 0; i < worldList.Count; i++)
            {
                worlds.Add(new World(worldList[i]));
            }

            stageList = new StageList(filename, worlds, byml.byteOrder);

            return(true);
        }
Ejemplo n.º 3
0
        public static void ExtractAllUBARS()
        {
            string barsDirectory  = GlobalDirectory.barsDirectoryU;
            string bfwavDirectory = GlobalDirectory.bfwavDirectoryU;
            string wavDirectory   = GlobalDirectory.wavDirectoryU;

            Directory.CreateDirectory(barsDirectory);
            string[] barsFilepaths = Directory.GetFiles(barsDirectory, "*.bars");

            foreach (string barsFilepath in barsFilepaths)
            {
                string barsFile      = Path.GetFileNameWithoutExtension(barsFilepath);
                string characterName = string.Empty;

                if (Utilities.StringStartsWithAny(barsFile, /*"MenuDriver_", */ "SNDG_M_"))
                {
                    characterName = barsFile.Remove(0, 7);
                }
                else if (Utilities.StringStartsWithAny(barsFile, /*"OpenDriver_", */ "SNDG_N_"))
                {
                    characterName = barsFile.Remove(0, 7);
                }
                else if (Utilities.StringStartsWithAny(barsFile, /*"Driver_", */ "SNDG_"))
                {
                    characterName = barsFile.Remove(0, 5);
                }

                Directory.CreateDirectory(bfwavDirectory + characterName);
                SARC.extract(barsFilepath, bfwavDirectory + characterName);
            }
            ConvertBFWAVtoWAVForGeneration(bfwavDirectory, wavDirectory);
        }
Ejemplo n.º 4
0
        public StageList(string input)
        {
            Filename = input;

            BymlFileData Input;
            SarcData     Data = SARC.UnpackRamN(YAZ0.Decompress(input));

            if (Data.Files.ContainsKey("StageList.byml"))
            {
                Input = ByamlFile.LoadN(new MemoryStream(Data.Files["StageList.byml"]), true, ByteOrder.BigEndian);
            }
            else
            {
                throw new Exception("Failed to find the StageList");
            }

            List <dynamic> temp = Input.RootNode["WorldList"];

            for (int i = 0; i < temp.Count; i++)
            {
                Worlds.Add(new World(temp[i]));
            }

            //File.WriteAllBytes("Original.byml",Data.Files["StageList.byml"]);
        }
Ejemplo n.º 5
0
        public void Save()
        {
            byte[] tmp = ToByaml();
            //File.WriteAllBytes("Test.byml", tmp);
            //BymlFileData Output = new BymlFileData() { Version = 1, SupportPaths = false, byteOrder = Syroot.BinaryData.Endian.Big };

            //Dictionary<string, dynamic> FinalRoot = new Dictionary<string, dynamic>();
            //List<dynamic> worlds = new List<dynamic>();

            //for (int i = 0; i < Worlds.Count; i++)
            //    worlds.Add(Worlds[i].ToByaml());

            //FinalRoot.Add("WorldList",worlds);
            //Output.RootNode = FinalRoot;
            SarcData Data = new SarcData()
            {
                byteOrder = ByteOrder.BigEndian, Files = new Dictionary <string, byte[]>()
            };

            Data.Files.Add("StageList.byml", tmp);
            Tuple <int, byte[]> x = SARC.PackN(Data);

            File.WriteAllBytes(Filename, YAZ0.Compress(x.Item2));
            //File.WriteAllBytes("Broken.byml", Data.Files["StageList.byml"]);
        }
Ejemplo n.º 6
0
        static bool DiffSzs(string[] args)
        {
            if (args.Length != 4)
            {
                Console.Error.WriteLine("Error: Wrong number of arguments.");
                return(false);
            }

            var original = args[1];
            var edited   = args[2];
            var outName  = args[3];

            var options = new LayoutDiff.DiffOptions {
                HideOnlineButton = args.Any(x => x == "--hide-online")
            };

            try
            {
                var res = LayoutDiff.Diff(
                    SARC.Unpack(ManagedYaz0.Decompress(File.ReadAllBytes(original))),
                    SARC.Unpack(ManagedYaz0.Decompress(File.ReadAllBytes(edited))),
                    options
                    );

                File.WriteAllBytes(outName, res.Item1.AsByteArray());

                Console.WriteLine(res.Item2);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"There was an error:\r\n{ex}");
            }

            return(true);
        }
Ejemplo n.º 7
0
 public SARCFileAdd(SARC Archive, string fileName)
 {
     InitializeComponent();
     calculatedHash     = 0;
     this.Archive       = Archive;
     fileNameLabel.Text = "File: " + fileName;
 }
Ejemplo n.º 8
0
        private void OpenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                var gamePath = System.IO.Path.GetFullPath(System.IO.Path.GetDirectoryName(ofd.FileName) + "\\..\\..\\..\\");

                Program.GamePath = gamePath;

                scene = new WorldMapScene(
                    SARC.UnpackRamN(Yaz0.Decompress(File.ReadAllBytes(ofd.FileName))),
                    System.IO.Path.GetFileName(ofd.FileName));

                gL_ControlModern1.MainDrawable = scene;

                scene.SelectionChanged      += Scene_SelectionChanged;
                scene.ObjectsMoved          += Scene_ObjectsMoved;
                sceneListView1.SelectedItems = scene.SelectedObjects;
                sceneListView1.RootLists.Clear();
                sceneListView1.RootLists.Add("Map", scene.WorldMapObjects);

                foreach (var route in scene.Routes)
                {
                    sceneListView1.RootLists.Add(route.Name, route.RoutePoints);
                }

                sceneListView1.UpdateComboBoxItems();
                sceneListView1.SetRootList("Map");
            }

            sceneListView1.Refresh();
        }
Ejemplo n.º 9
0
 public static void ReloadModel(string ModelName)
 {
     if (cache.ContainsKey(ModelName))
     {
         cache.Remove(ModelName);
         Submit(ModelName, new MemoryStream(SARC.UnpackRamN(new MemoryStream(YAZ0.Decompress(Program.TryGetPathViaProject("ObjectData", ModelName + ".szs")))).Files[ModelName + ".bfres"]));
     }
 }
Ejemplo n.º 10
0
        public static void ExtractNxTheme(string theme, string path)
        {
            var data = SARC.UnpackRamN(ManagedYaz0.Decompress(File.ReadAllBytes(theme)));

            foreach (var f in data.Files.Where(x => x.Key != "info.json"))
            {
                File.WriteAllBytes(Path.Combine(path, f.Key), f.Value);
            }
        }
Ejemplo n.º 11
0
        public static void ExportCollisionFromObject(string ObjectDataFolder)
        {
            var opn = new OpenFileDialog()
            {
                InitialDirectory = Directory.Exists(ObjectDataFolder) ? ObjectDataFolder : null,
                Filter           = "szs file | *.szs",
                Title            = "Select an Object which has a collision model"
            };

            if (opn.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            var szs = SARC.UnpackRam(YAZ0.Decompress(opn.FileName));

            foreach (string name in szs.Keys)
            {
                if (name.EndsWith(".kcl"))
                {
                    List <Color> typeColors = null;

                    string attributeFileName = Path.GetFileNameWithoutExtension(name) + "Attribute.byml";
                    if (szs.ContainsKey(attributeFileName))
                    {
                        typeColors = GetKCLColors(szs[attributeFileName]);
                    }

                    var sav = new SaveFileDialog()
                    {
                        FileName = name + ".obj",
                        Filter   = "obj file|*.obj"
                    };
                    if (sav.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }

                    var mod = new MarioKart.MK7.KCL(szs[name]).ToOBJ().toWritableObj();

                    if (typeColors != null)
                    {
                        for (int i = 0; i < mod.Materials.Count; i++)
                        {
                            if (i >= typeColors.Count)
                            {
                                break;
                            }
                            mod.Materials[i].Colors.normal.X = typeColors[i].R / 255f;
                            mod.Materials[i].Colors.normal.Y = typeColors[i].G / 255f;
                            mod.Materials[i].Colors.normal.Z = typeColors[i].B / 255f;
                        }
                    }

                    mod.WriteObj(sav.FileName);
                }
            }
        }
Ejemplo n.º 12
0
        public void Load(string filename)
        {
            FileInfo = new FileInfo(filename);

            if (FileInfo.Exists)
            {
                _sarc = new SARC(FileInfo.OpenRead());
            }
        }
Ejemplo n.º 13
0
        public void Load(string filename)
        {
            FileInfo = new FileInfo(filename);

            using (var br = new BinaryReaderX(FileInfo.OpenRead()))
            {
                br.ReadBytes(4);
                _sarc = new SARC(new MemoryStream(ZLib.Decompress(new MemoryStream(br.ReadBytes((int)FileInfo.Length - 4)))));
            }
        }
Ejemplo n.º 14
0
 public static SarcData LoadAsSarcData(this string path)
 {
     if (File.Exists(path))
     {
         return(SARC.UnpackRamN(path.ReadBytes()));
     }
     else
     {
         throw new FileNotFoundException();
     }
 }
Ejemplo n.º 15
0
        public LoadResult Load(string filename)
        {
            FileInfo = new FileInfo(filename);
            if (!FileInfo.Exists)
            {
                return(LoadResult.FileNotFound);
            }

            _sarc = new SARC(FileInfo.OpenRead());
            return(LoadResult.Success);
        }
Ejemplo n.º 16
0
        public void Save()
        {
            //byte[] tmp = ToByaml();
            //File.WriteAllBytes("Test.byml", tmp);
            BymlFileData Output = new BymlFileData()
            {
                Version = 1, SupportPaths = false, byteOrder = ByteOrder
            };

            Dictionary <string, dynamic> FinalRoot = new Dictionary <string, dynamic>();
            List <dynamic> worlds = new List <dynamic>();

            for (int i = 0; i < Worlds.Count; i++)
            {
                worlds.Add(Worlds[i].ToByaml());
            }

            FinalRoot.Add("WorldList", worlds);
            Output.RootNode = FinalRoot;



            SarcData Data = new SarcData()
            {
                byteOrder = ByteOrder, Files = new Dictionary <string, byte[]>()
            };

            Data.Files.Add("StageList.byml", ByamlFile.SaveN(Output));
            Tuple <int, byte[]> x = SARC.PackN(Data);


            if (Filename.StartsWith(Program.GamePath) && !string.IsNullOrEmpty(Program.ProjectPath))
            {
                switch (MessageBox.Show(
                            Program.CurrentLanguage.GetTranslation("SaveStageListInProjectText") ?? "Would you like to save the StageList.szs to your ProjectPath instead of your BaseGame?",
                            Program.CurrentLanguage.GetTranslation("SaveStageListInProjectHeader") ?? "Save in ProjectPath",
                            MessageBoxButtons.YesNoCancel))
                {
                case DialogResult.Yes:
                    Directory.CreateDirectory(Path.Combine(Program.ProjectPath, "SystemData"));
                    Filename = Path.Combine(Program.ProjectPath, "SystemData", "StageList.szs");
                    break;

                case DialogResult.No:
                    break;

                case DialogResult.Cancel:
                    return;
                }
            }

            File.WriteAllBytes(Filename, YAZ0.Compress(x.Item2));
            //File.WriteAllBytes("Broken.byml", Data.Files["StageList.byml"]);
        }
Ejemplo n.º 17
0
 byte[] BfresFromSzs(string fileName)
 {
     if (File.Exists($"{GameFolder}ObjectData\\{fileName}.szs"))
     {
         var SzsFiles = SARC.UnpackRam(YAZ0.Decompress($"{GameFolder}ObjectData\\{fileName}.szs"));
         if (SzsFiles.ContainsKey(fileName + ".bfres"))
         {
             return(SzsFiles[fileName + ".bfres"]);
         }
     }
     return(null);
 }
Ejemplo n.º 18
0
        public LoadResult Load(string filename)
        {
            FileInfo = new FileInfo(filename);
            if (!FileInfo.Exists)
            {
                return(LoadResult.FileNotFound);
            }

            using (var br = new BinaryReaderX(File.OpenRead(filename)))
            {
                br.ReadBytes(4);
                _sarc = new SARC(new MemoryStream(ZLib.Decompress(br.ReadBytes((int)FileInfo.Length - 4))));
                return(LoadResult.Success);
            }
        }
Ejemplo n.º 19
0
        public static void GetObjectInfos(string fileName, Dictionary <string, List <ObjectInfo> > infosByListName)
        {
            string levelName;
            string categoryName;

            string fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);

            if (fileNameWithoutExt.EndsWith("Map1"))
            {
                levelName    = fileNameWithoutExt.Remove(fileNameWithoutExt.Length - 4);
                categoryName = "Map";
            }
            else if (fileNameWithoutExt.EndsWith("Design1"))
            {
                levelName    = fileNameWithoutExt.Remove(fileNameWithoutExt.Length - 7);
                categoryName = "Design";
            }
            else if (fileNameWithoutExt.EndsWith("Sound1"))
            {
                levelName    = fileNameWithoutExt.Remove(fileNameWithoutExt.Length - 6);
                categoryName = "Sound";
            }
            else
            {
                return;
            }

            SarcData sarc = SARC.UnpackRamN(YAZ0.Decompress(fileName));

            Dictionary <long, ObjectInfo> objectInfosByReference = new Dictionary <long, ObjectInfo>();

            ByamlIterator byamlIter = new ByamlIterator(new MemoryStream(sarc.Files[levelName + categoryName + ".byml"]));

            foreach (DictionaryEntry entry in byamlIter.IterRootDictionary())
            {
                if (!infosByListName.ContainsKey(entry.Key))
                {
                    continue;
                }

                List <ObjectInfo> objectInfos = new List <ObjectInfo>();

                foreach (ArrayEntry obj in entry.IterArray())
                {
                    objectInfos.Add(ParseObjectInfo(obj, objectInfosByReference, infosByListName, entry.Key));
                }
            }
        }
Ejemplo n.º 20
0
        private void extractSARCArchiveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                using (var ofd = new OpenFileDialog())
                {
                    if (ofd.ShowDialog(this) != DialogResult.OK)
                    {
                        return;
                    }

                    using (var stream = ofd.OpenFile())
                    {
                        var arch = new SARC(stream);

                        using (var fbd = new FolderBrowserDialog())
                        {
                            fbd.SelectedPath = Path.GetDirectoryName(ofd.FileName);

                            if (fbd.ShowDialog(this) != DialogResult.OK)
                            {
                                return;
                            }

                            var path = fbd.SelectedPath + Path.DirectorySeparatorChar;

                            foreach (var node in arch.SfatNodes)
                            {
                                var fullPath = path + node.copied_name.Replace('/', Path.DirectorySeparatorChar);
                                Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
                                using (var fileOutput = new FileStream(fullPath, FileMode.Create, FileAccess.Write))
                                    fileOutput.Write(node.copied_data, 0, node.copied_data.Length);
                            }

                            // Open folder in Explorer
                            Process.Start(fbd.SelectedPath);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 21
0
        public static void GetObjectInfosCombined(string fileName,
                                                  Dictionary <string, List <ObjectInfo> > MAPinfosByListName,
                                                  Dictionary <string, List <ObjectInfo> > DESIGNinfosByListName,
                                                  Dictionary <string, List <ObjectInfo> > SOUNDinfosByListName)
        {
            string levelName;

            string levelNameWithSuffix = Path.GetFileName(fileName);

            levelName = levelNameWithSuffix.Remove(levelNameWithSuffix.Length - SM3DWorldZone.COMBINED_SUFFIX.Length);


            SarcData sarc = SARC.UnpackRamN(YAZ0.Decompress(fileName));

            GetObjectInfos(MAPinfosByListName, levelName, "Map", sarc);
            GetObjectInfos(DESIGNinfosByListName, levelName, "Design", sarc);
            GetObjectInfos(SOUNDinfosByListName, levelName, "Sound", sarc);
        }
Ejemplo n.º 22
0
        private void MaterialTexturesAssumption(string name)
        {
            SarcData src = SARC.Unpack(ManagedYaz0.Decompress(System.IO.File.ReadAllBytes(name)));

            foreach (var val in src.Files.Where(x => x.Key.EndsWith(".bflyt")))
            {
                var(n, f) = val;

                SwitchThemes.Common.Bflyt.BflytFile ff = new SwitchThemes.Common.Bflyt.BflytFile(f);

                if (ff.Mat1 != null)
                {
                    foreach (var m in ff.Mat1.Materials)
                    {
                        Assert.AreEqual(m.Textures.Length, m.TextureTransformations.Length);
                    }
                }
            }
        }
Ejemplo n.º 23
0
        private void materialRaisedButton1_Click(object sender, EventArgs e)
        {
            if (CommonSzs == null)
            {
                return;
            }
            SaveFileDialog sav = new SaveFileDialog()
            {
                Filter = "szs file|*.szs",
            };

            if (sav.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            var sarc = SARC.PackN(CommonSzs);

            File.WriteAllBytes(sav.FileName, ManagedYaz0.Compress(sarc.Item2, 3, (int)sarc.Item1));
        }
Ejemplo n.º 24
0
        static async Task Main(string[] args)
        {
            var pathTest = @"E:\Messageold";

            var sw = new Stopwatch();

            sw.Start();

            var filesIn = Directory.GetFiles(pathTest, "*EUen*.zs");

            var dataOut = new Dictionary <string, byte[]>();


            foreach (var file in filesIn)
            {
                var d = await File.ReadAllBytesAsync(file);

                using var decompress = new ZstdNet.Decompressor();
                var unzip = decompress.Unwrap(d);

                var files = SARC.Extract(unzip);

                foreach (var filem in files)
                {
                    var dat = filem.Value.Sorted.SelectMany(s => Encoding.Unicode.GetBytes($"{s.Key},{s.Value}\r\n")).ToArray();
                    dataOut.Add(file.Replace(pathTest, "") + "\\" + filem.Key, dat);
                }
            }

            await using var zipToOpen = new MemoryStream();
            using var archive         = new ZipArchive(zipToOpen, ZipArchiveMode.Create, true);
            foreach (var file in dataOut)
            {
                var zipArchiveEntry = archive.CreateEntry(file.Key.TrimStart('\\'), CompressionLevel.NoCompression);
                await using var zipStream = zipArchiveEntry.Open();
                await zipStream.WriteAsync(file.Value, 0, file.Value.Length);
            }

            var time = sw.ElapsedMilliseconds;

            await File.WriteAllBytesAsync(@"D:\MessageTest\zip.zip", zipToOpen.ToArray());
        }
Ejemplo n.º 25
0
        SarcData SelectFile(ref TextBox target, string name = null)
        {
            if (name is null)
            {
                OpenFileDialog opn = new OpenFileDialog()
                {
                    Filter = "szs files|*.szs"
                };
                if (opn.ShowDialog() != DialogResult.OK)
                {
                    return(null);
                }
                name = opn.FileName;
            }
            target.Text = name;
            var sarc = SARC.Unpack(ManagedYaz0.Decompress(File.ReadAllBytes(target.Text)));

            EnableResidentMenuCheckbox(sarc);
            return(sarc);
        }
Ejemplo n.º 26
0
        public static byte[] Make(SarcData input, DDSLoadResult dds, PatchTemplate targetPatch, LayoutPatch layout)
        {
            if (layout != null)
            {
                var layoutres = SwitchThemesCommon.PatchLayouts(input, layout.Files);
                if (layoutres == BflytFile.PatchResult.Fail)
                {
                    Window.Alert("One of the target files for the selected layout patch is missing in the SZS, you are probably using an already patched SZS or the wrong layout");
                    return(null);
                }
                else if (layoutres == BflytFile.PatchResult.CorruptedFile)
                {
                    Window.Alert("A layout in this SZS is missing a pane required for the selected layout patch, you are probably using an already patched SZS or the wrong layout");
                    return(null);
                }
            }

            if (SwitchThemesCommon.PatchBntx(input, dds, targetPatch) == BflytFile.PatchResult.Fail)
            {
                Window.Alert(
                    "Can't build this theme: the szs you opened doesn't contain some information needed to patch the bntx," +
                    "without this information it is not possible to rebuild the bntx." +
                    "You should use an original or at least working szs");
                return(null);
            }
            var res = SwitchThemesCommon.PatchBgLayouts(input, targetPatch);

            if (res == BflytFile.PatchResult.Fail)
            {
                Window.Alert("Couldn't patch this file, it might have been already modified or it's from an unsupported system version.");
                return(null);
            }
            else if (res == BflytFile.PatchResult.CorruptedFile)
            {
                Window.Alert("This file has been already patched with another tool and is not compatible, you should get an unmodified layout.");
                return(null);
            }
            var sarc = SARC.PackN(input);

            return(ManagedYaz0.Compress(sarc.Item2, 1, (int)sarc.Item1));
        }
Ejemplo n.º 27
0
        private void ProcessSzs(string name)
        {
            SarcData src = SARC.Unpack(ManagedYaz0.Decompress(Util.ReadData($"Source/{name}.szs")));
            SarcData exp = SARC.Unpack(ManagedYaz0.Decompress(Util.ReadData($"Expected/{name}.szs")));

            string lyt = Util.Exists($"Source/{name}.json") ? Util.ReadString($"Source/{name}.json") : null;

            SzsPatcher patcher = new SzsPatcher(src);

            Assert.IsTrue(patcher.PatchMainBG(DDS));

            if (lyt != null)
            {
                var l = LayoutPatch.LoadTemplate(lyt);
                patcher.PatchLayouts(l);
            }

            var final = patcher.GetFinalSarc();

            CompareSarc(final, exp);
        }
Ejemplo n.º 28
0
            public CachedModel(ResFile bfres, string textureArc)
            {
                if (LoadTextures && textureArc != null && File.Exists(Program.TryGetPathViaProject("ObjectData", textureArc + ".szs")))
                {
                    SarcData objArc = SARC.UnpackRamN(YAZ0.Decompress(Program.TryGetPathViaProject("ObjectData", textureArc + ".szs")));

                    if (!texArcCache.ContainsKey(textureArc))
                    {
                        Dictionary <string, int> arc = new Dictionary <string, int>();
                        texArcCache.Add(textureArc, arc);
                        foreach (KeyValuePair <string, TextureShared> textureEntry in new ResFile(new MemoryStream(objArc.Files[textureArc + ".bfres"])).Textures)
                        {
                            arc.Add(textureEntry.Key, UploadTexture(textureEntry.Value));
                        }
                    }
                }

                Model mdl = bfres.Models[0];

                vaos = new VertexArrayObject[mdl.Shapes.Count];
                indexBufferLengths = new int[mdl.Shapes.Count];
                textures           = new int[mdl.Shapes.Count];
                wrapModes          = new (int, int)[mdl.Shapes.Count];
Ejemplo n.º 29
0
        static bool SZSFromArgs(string[] args)
        {
            string GetArg(string start)
            {
                var a = args.Where(x => x.StartsWith(start + "=")).FirstOrDefault();

                if (a == null)
                {
                    return(null);
                }
                else
                {
                    return(a.Split('=')[1]);
                }
            }

            if (args.Length < 2)
            {
                return(false);
            }

            string Target      = args[1];
            var    CommonSzs   = SARCExt.SARC.UnpackRamN(ManagedYaz0.Decompress(File.ReadAllBytes(Target)));
            var    targetPatch = SzsPatcher.DetectSarc(CommonSzs, DefaultTemplates.templates);

            if (targetPatch == null)
            {
                Console.WriteLine("Unknown szs file");
                return(false);
            }

            string Image = args.Where(x => x.EndsWith(".dds") || x.EndsWith(".jpg") || x.EndsWith(".png") || x.EndsWith("jpeg")).FirstOrDefault();

            if (Image == null || !File.Exists(Image))
            {
                Console.WriteLine("No image file !");
                return(false);
            }
            string Layout = args.Where(x => x.EndsWith(".json")).FirstOrDefault();

            string Output = GetArg("out");

            if (Output == null || Output == "")
            {
                return(false);
            }

            if (!Image.EndsWith(".dds"))
            {
                if (Form1.ImageToDDS(Image, Path.GetTempPath()))
                {
                    Image = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Image) + ".dds");
                }
                else
                {
                    return(false);
                }
            }

            try
            {
                var res     = true;
                var Patcher = new SzsPatcher(CommonSzs, DefaultTemplates.templates);

                if (Image != null)
                {
                    res = Patcher.PatchMainBG(File.ReadAllBytes(Image));
                    if (!res)
                    {
                        Console.WriteLine("Couldn't patch this file, it might have been already modified or it's from an unsupported system version.");
                        return(false);
                    }
                }

                void ProcessAppletIcons(List <TextureReplacement> l)
                {
                    foreach (var a in l)
                    {
                        string path = GetArg(a.NxThemeName);
                        if (!path.EndsWith(".dds") && !Form1.IcontoDDS(ref path))
                        {
                            path = null;
                        }
                        if (path != null)
                        {
                            if (!Patcher.PatchAppletIcon(File.ReadAllBytes(path), a.NxThemeName))
                            {
                                Console.WriteLine($"Applet icon patch for {a.NxThemeName} failed");
                            }
                        }
                    }
                }

                if (TextureReplacement.NxNameToList.ContainsKey(targetPatch.NXThemeName))
                {
                    ProcessAppletIcons(TextureReplacement.NxNameToList[targetPatch.NXThemeName]);
                }

                if (Layout != null)
                {
                    Patcher.EnableAnimations = true;
                    var l         = LayoutPatch.LoadTemplate(File.ReadAllText(Layout));
                    var layoutres = Patcher.PatchLayouts(l, targetPatch.NXThemeName, targetPatch);
                    if (!layoutres)
                    {
                        Console.WriteLine("One of the target files for the selected layout patch is missing in the SZS, you are probably using an already patched SZS");
                        return(false);
                    }
                    layoutres = Patcher.PatchAnimations(l.Anims);
                }

                CommonSzs = Patcher.GetFinalSarc();
                var sarc = SARC.PackN(CommonSzs);

                File.WriteAllBytes(Output, ManagedYaz0.Compress(sarc.Item2, 3, (int)sarc.Item1));
                GC.Collect();

                if (Patcher.PatchTemplate.RequiresCodePatch)
                {
                    Console.WriteLine("The file has been patched successfully but due to memory limitations this szs requires an extra code patch to be applied to the home menu, if you use NXThemesInstaller to install this it will be done automatically, otherwise you need to manually copy the patches from https://github.com/exelix11/SwitchThemeInjector/tree/master/SwitchThemesNX/romfs to the exefs patches directory of your cfw");
                }
                else
                {
                    Console.WriteLine("Done");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }

            return(true);
        }
Ejemplo n.º 30
0
 public SARCViewer(SARC Archive)
 {
     this.Archive = Archive;
     Root = Archive.ToFileSystem();
     InitializeComponent();
 }
Ejemplo n.º 31
0
        /// <summary>
        /// Process data in an input file that contains a layout.
        /// </summary>
        /// <param name="filename"></param>
        bool ProcessData(string filename, byte[] inData)
        {
            EndianBinaryReader reader = null;

            // now we need to decide what they just opened
            if (inData == null && filename != "")
            {
                reader = new EndianBinaryReader(File.Open(filename, FileMode.Open), Encoding.GetEncoding(932));
            }
            else
            {
                reader = new EndianBinaryReader(inData);
            }

            string magic = "";

            // we have a Yaz0 compressed file
            if (reader.ReadStringFrom(0, 4) == "Yaz0")
            {
                // we have to close our reader so we can properly read this file as a Yaz0 stream
                reader.Close();

                MemoryStream ms = null;

                if (inData == null)
                {
                    ms = new Yaz0(File.Open(filename, FileMode.Open));
                }
                else
                {
                    ms = new Yaz0(new MemoryStream(inData));
                }

                reader = new EndianBinaryReader(ms);
                magic  = reader.ReadStringFrom(0, 4);
            }
            // we have a LZ compressed file
            else if (reader.ReadByteFrom(0) == 0x11)
            {
                LZ77   lzFile = new LZ77(ref reader);
                byte[] lzData = lzFile.getData();
                // close our current reader to open a new one with our input data
                reader.Close();
                reader = new EndianBinaryReader(lzData);
                magic  = reader.ReadStringFrom(0, 4);
            }
            // no compression
            else
            {
                // it is not yaz0 compressed, so we see the magic
                magic = reader.ReadStringFrom(0, 4);
            }

            // now we have to check our magic to see what kind of file it is
            switch (magic)
            {
            case "darc":
                mArchive = new DARC(ref reader);
                break;

            case "NARC":
                mArchive = new NARC(ref reader);
                break;

            case "SARC":
                mArchive = new SARC(ref reader);
                break;

            case "RARC":
                reader.SetEndianess(Endianess.Big);
                mArchive = new RARC(ref reader);
                break;

            case "U?8-":
                reader.SetEndianess(Endianess.Big);
                mArchive = new U8(ref reader);
                break;

            default:
                MessageBox.Show("Error. Unsupported format with magic: " + magic);
                break;
            }

            string layoutType = "";

            // some files have their string table nullified, which makes the names obfuscated
            // I've only seen this in SARCs from MK7, but there's probably more
            if (mArchive != null)
            {
                if (mArchive.isStringTableObfuscated())
                {
                    MessageBox.Show("This file has obfuscated file names. The editor attempted to find layout files, but cannot supply names.");
                }
            }

            reader.Close();

            if (mArchive == null)
            {
                MessageBox.Show("Format not supported.");
                return(false);
            }

            // the only familiar format with archives in archives is SARC and RARC
            if (mArchive.getType() == ArchiveType.SARC || mArchive.getType() == ArchiveType.RARC)
            {
                List <string> names = mArchive.getArchiveFileNames();

                if (names.Count != 0)
                {
                    DialogResult res = MessageBox.Show("This archive has another archive inside of it.\nDo you wish to choose one of the found archives to select a layout?", "Internal Archive", MessageBoxButtons.YesNo);

                    if (res == DialogResult.Yes)
                    {
                        LayoutChooser archiveChooser = new LayoutChooser();
                        archiveChooser.insertEntries(names);
                        archiveChooser.ShowDialog();

                        // if this worked, we dont need to do anything
                        bool result = ProcessData(archiveChooser.getSelectedFile(), mArchive.getDataByName(archiveChooser.getSelectedFile()));

                        if (result)
                        {
                            return(true);
                        }
                        else
                        {
                            MessageBox.Show("Failed to get the internal file.");
                            return(false);
                        }
                    }
                }
            }

            // get all of our needed files
            mLayoutFiles     = mArchive.getLayoutFiles();
            mLayoutAnimFiles = mArchive.getLayoutAnimations();
            mLayoutImages    = mArchive.getLayoutImages();
            mLayoutControls  = mArchive.getLayoutControls();

            if (mLayoutFiles.Count == 0)
            {
                MessageBox.Show("This file contains no layouts.");
                return(false);
            }

            LayoutChooser layoutChooser = new LayoutChooser();

            layoutChooser.insertEntries(new List <string>(mLayoutFiles.Keys));
            layoutChooser.ShowDialog();

            string selectedFile = layoutChooser.getSelectedFile();

            if (selectedFile == null)
            {
                return(false);
            }

            string[] sections = selectedFile.Split('/');
            mMainRoot = "";

            // remove "lyt" part and the file name
            // this will be our main root of the entire opened file
            for (int i = 0; i < sections.Length - 2; i++)
            {
                mMainRoot += sections[i] + "/";
            }

            if (layoutType == "")
            {
                layoutType = Path.GetExtension(selectedFile);
            }

            // now we have to init a layout reader
            EndianBinaryReader layoutReader = null;

            byte[] data;

            switch (layoutType)
            {
            case ".brlyt":
                data         = mLayoutFiles[selectedFile];
                layoutReader = new EndianBinaryReader(data);
                mMainLayout  = new BRLYT(ref layoutReader);
                layoutReader.Close();
                break;

            case ".bclyt":
                data         = mLayoutFiles[selectedFile];
                layoutReader = new EndianBinaryReader(data);
                mMainLayout  = new BCLYT(ref layoutReader);
                break;

            case ".bflyt":
                data         = mLayoutFiles[selectedFile];
                layoutReader = new EndianBinaryReader(data);
                mMainLayout  = new BFLYT(ref layoutReader);
                break;

            case ".blo":
                data         = mLayoutFiles[selectedFile];
                layoutReader = new EndianBinaryReader(data);

                if (layoutReader.ReadStringFrom(4, 4) == "blo1")
                {
                    mMainLayout = new BLO1(ref layoutReader);
                }
                else
                {
                    mMainLayout = new BLO2(ref layoutReader);
                }
                break;

            default:
                MessageBox.Show("This format is not supported yet.");
                break;
            }

            layoutReader.Close();

            if (mMainLayout == null)
            {
                return(false);
            }

            // set our propertygrid with our LYT object
            mainPropertyGrid.SelectedObject = mMainLayout.getLayoutParams();

            if (mMainLayout.getRootPanel() == null)
            {
                MessageBox.Show("Error, the root pane in this layout is not specified.");
                return(false);
            }

            LayoutBase pane  = null;
            LayoutBase group = null;

            // now we have to grab our root panel, which is different on each console
            // so we have to specifically get the one we want
            // the same applies to our root group
            pane = mMainLayout.getRootPanel();

            // this should be RootPane
            TreeNode n1 = new TreeNode
            {
                Tag  = pane,
                Name = pane.mName,
                Text = pane.mName,
            };

            panelList.Nodes.Add(n1);
            fillNodes(pane.getChildren());

            // now for our groups
            group = mMainLayout.getRootGroup();

            if (group != null)
            {
                TreeNode n1_1 = new TreeNode
                {
                    Tag  = group,
                    Name = group.mName,
                    Text = group.mName,
                };

                panelList.Nodes.Add(n1_1);
                fillNodes(group.getChildren());
            }

            // now for textures and fonts
            // but it is possible for either one to not exist
            if (mMainLayout.containsTextures())
            {
                foreach (string str in mMainLayout.getTextureNames())
                {
                    texturesList.Items.Add(str);
                }
            }

            if (mMainLayout.containsFonts())
            {
                foreach (string str in mMainLayout.getFontNames())
                {
                    fontsList.Items.Add(str);
                }
            }

            // and our materials
            if (mMainLayout.containsMaterials())
            {
                foreach (string str in mMainLayout.getMaterialNames())
                {
                    materialList.Items.Add(str);
                }
            }

            // this draws the border of the layout
            mMainLayout.draw();

            layoutViewer.Refresh();

            return(true);
        }