public void CanSerializeAndDeserialize() { byte value = byte.MaxValue; ByteConverter converter = new ByteConverter(); byte[] bytes = converter.Serialize(value); byte valueFromBytes = converter.Deserialize(bytes); Assert.Equal(valueFromBytes, value); }
protected object DoDeserialize(Type type, byte[] buff, ref int offset) { int num; object obj2; int num3; int num4; if (type == typeof(object)) { return(null); } if (type == typeof(Font)) { SimpleFont font = (SimpleFont)this.DoDeserialize(typeof(SimpleFont), buff, ref offset); if (font == null) { return(null); } return(font.GetFont()); } if (ByteConverter.SupportType(type)) { return(ByteConverter.Parse(type, buff, ref offset)); } if (type == typeof(Color)) { Color color = Color.FromArgb(buff[offset], buff[offset + 1], buff[offset + 2]); offset += 3; return(color); } if (type == typeof(string)) { int count = ByteConverter.Parse <int>(buff, ref offset); string str = null; if (count == 0) { return(string.Empty); } if (count > -1) { str = Encoding.UTF8.GetString(buff, offset, count); offset += count; } return(str); } if (type == typeof(byte[])) { num = ByteConverter.Parse <int>(buff, ref offset); byte[] dst = null; if (num > -1) { dst = new byte[num]; Buffer.BlockCopy(buff, offset, dst, 0, num); offset += num; } return(dst); } if ((type == typeof(Image)) || type.IsSubclassOf(typeof(Image))) { num = ByteConverter.Parse <int>(buff, ref offset); Image image = null; if (num > -1) { bool flag = BitConverter.ToBoolean(buff, offset); offset++; if (flag) { image = (Image)SerializeHelper.DeserializeBytes(buff, offset, num); } else { byte[] buffer2 = new byte[num]; Buffer.BlockCopy(buff, offset, buffer2, 0, num); image = ImageHelper.Convert(buffer2); } offset += num; } return(image); } if (type.IsGenericType && ((type.GetGenericTypeDefinition() == typeof(IList <>)) || (type.GetGenericTypeDefinition() == typeof(List <>)))) { num3 = ByteConverter.Parse <int>(buff, ref offset); IList list = null; if (num3 > -1) { Type type2 = type.GetGenericArguments()[0]; list = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(new Type[] { type2 })); for (num4 = 0; num4 < num3; num4++) { object obj3 = this.DoDeserialize(type2, buff, ref offset); list.Add(obj3); } } return(list); } if (type.IsGenericType && ((type.GetGenericTypeDefinition() == typeof(IDictionary <,>)) || (type.GetGenericTypeDefinition() == typeof(Dictionary <,>)))) { num3 = ByteConverter.Parse <int>(buff, ref offset); IDictionary dictionary = null; if (num3 > -1) { Type type3 = type.GetGenericArguments()[0]; Type type4 = type.GetGenericArguments()[1]; dictionary = (IDictionary)Activator.CreateInstance(typeof(Dictionary <,>).MakeGenericType(new Type[] { type3, type4 })); for (num4 = 0; num4 < num3; num4++) { object key = this.DoDeserialize(type3, buff, ref offset); object obj5 = this.DoDeserialize(type4, buff, ref offset); dictionary.Add(key, obj5); } } return(dictionary); } if (type.IsArray) { throw new Exception(string.Format("CompactSerializer don't support Type {0} ! ", type)); } try { obj2 = this.DoDeserializeComplicatedType(type, buff, ref offset); } catch (Exception exception) { throw new SerializeException(string.Format("{0} -- on Deserializing Type {1} ! BufferLen:{2} ,Offset:{3}", new object[] { exception.Message, type, buff.Length, (int)offset }), exception); } return(obj2); }
public void Test_ToArray() { byte[] value = ByteConverter.ToArray(IntPtr.Zero, 4); Assert.AreEqual(null, value); }
public static int SplitDLLFile(string datafilename, string inifilename, string projectFolderName) { #if !DEBUG try #endif { byte[] datafile = File.ReadAllBytes(datafilename); IniData inifile = IniSerializer.Deserialize <IniData>(inifilename); uint imageBase = HelperFunctions.SetupEXE(ref datafile).Value; Dictionary <string, int> exports; { int ptr = BitConverter.ToInt32(datafile, BitConverter.ToInt32(datafile, 0x3c) + 4 + 20 + 96); GCHandle handle = GCHandle.Alloc(datafile, GCHandleType.Pinned); IMAGE_EXPORT_DIRECTORY dir = (IMAGE_EXPORT_DIRECTORY)Marshal.PtrToStructure( Marshal.UnsafeAddrOfPinnedArrayElement(datafile, ptr), typeof(IMAGE_EXPORT_DIRECTORY)); handle.Free(); exports = new Dictionary <string, int>(dir.NumberOfFunctions); int nameaddr = dir.AddressOfNames; int ordaddr = dir.AddressOfNameOrdinals; for (int i = 0; i < dir.NumberOfNames; i++) { string name = datafile.GetCString(BitConverter.ToInt32(datafile, nameaddr), System.Text.Encoding.ASCII); int addr = BitConverter.ToInt32(datafile, dir.AddressOfFunctions + (BitConverter.ToInt16(datafile, ordaddr) * 4)); exports.Add(name, addr); nameaddr += 4; ordaddr += 2; } } ModelFormat modelfmt = 0; LandTableFormat landfmt = 0; string modelext = null; string landext = null; switch (inifile.Game) { case Game.SADX: modelfmt = ModelFormat.BasicDX; landfmt = LandTableFormat.SADX; modelext = ".sa1mdl"; landext = ".sa1lvl"; break; case Game.SA2B: modelfmt = ModelFormat.Chunk; landfmt = LandTableFormat.SA2; modelext = ".sa2mdl"; landext = ".sa2lvl"; break; } int itemcount = 0; List <string> labels = new List <string>(); Dictionary <string, string> anilabels = new Dictionary <string, string>(); ModelAnimationsDictionary models = new ModelAnimationsDictionary(); DllIniData output = new DllIniData() { Name = inifile.ModuleName, Game = inifile.Game }; Stopwatch timer = new Stopwatch(); timer.Start(); foreach (KeyValuePair <string, FileInfo> item in inifile.Files) { if (string.IsNullOrEmpty(item.Key)) { continue; } FileInfo data = item.Value; string type = data.Type; string name = item.Key; output.Exports[name] = type; int address = exports[name]; string fileOutputPath = ""; if (data.Filename != null) { fileOutputPath = string.Concat(projectFolderName, data.Filename); Console.WriteLine(name + " -> " + fileOutputPath); Directory.CreateDirectory(Path.GetDirectoryName(fileOutputPath)); } else { Console.WriteLine(name); } switch (type) { case "landtable": { LandTable land = new LandTable(datafile, address, imageBase, landfmt) { Description = name }; DllItemInfo info = new DllItemInfo() { Export = name, Label = land.Name }; output.Items.Add(info); if (!labels.Contains(land.Name)) { land.SaveToFile(fileOutputPath, landfmt); output.Files[data.Filename] = new FileTypeHash("landtable", HelperFunctions.FileHash(fileOutputPath)); labels.AddRange(land.GetLabels()); } } break; case "battlelandtable": { LandTable land = new LandTable(datafile, address, imageBase, LandTableFormat.SA2B) { Description = name }; DllItemInfo info = new DllItemInfo() { Export = name, Label = land.Name }; output.Items.Add(info); if (!labels.Contains(land.Name)) { land.SaveToFile(fileOutputPath, LandTableFormat.SA2B); output.Files[data.Filename] = new FileTypeHash("landtable", HelperFunctions.FileHash(fileOutputPath)); labels.AddRange(land.GetLabels()); } } break; case "landtablearray": for (int i = 0; i < data.Length; i++) { int ptr = BitConverter.ToInt32(datafile, address); if (ptr != 0) { ptr = (int)(ptr - imageBase); string idx = name + "[" + i.ToString(NumberFormatInfo.InvariantInfo) + "]"; LandTable land = new LandTable(datafile, ptr, imageBase, landfmt) { Description = idx }; DllItemInfo info = new DllItemInfo() { Export = name, Index = i, Label = land.Name }; output.Items.Add(info); if (!labels.Contains(land.Name)) { string outputFN = Path.Combine(fileOutputPath, i.ToString(NumberFormatInfo.InvariantInfo) + landext); string fileName = Path.Combine(data.Filename, i.ToString(NumberFormatInfo.InvariantInfo) + landext); land.SaveToFile(outputFN, landfmt); output.Files[fileName] = new FileTypeHash("landtable", HelperFunctions.FileHash(outputFN)); labels.AddRange(land.GetLabels()); } } address += 4; } break; case "model": { NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, modelfmt, new Dictionary <int, Attach>()); DllItemInfo info = new DllItemInfo() { Export = name, Label = mdl.Name }; output.Items.Add(info); if (!labels.Contains(mdl.Name)) { models.Add(new ModelAnimations(data.Filename, name, mdl, modelfmt)); labels.AddRange(mdl.GetLabels()); } } break; case "morph": { BasicAttach dummy = new BasicAttach(datafile, address, imageBase, modelfmt == ModelFormat.BasicDX); NJS_OBJECT mdl = new NJS_OBJECT() { Attach = dummy }; DllItemInfo info = new DllItemInfo() { Export = name, Label = dummy.Name }; output.Items.Add(info); if (!labels.Contains(dummy.Name)) { models.Add(new ModelAnimations(data.Filename, name, mdl, modelfmt)); labels.AddRange(mdl.GetLabels()); } } break; case "modelarray": for (int i = 0; i < data.Length; i++) { int ptr = BitConverter.ToInt32(datafile, address); if (ptr != 0) { ptr = (int)(ptr - imageBase); NJS_OBJECT mdl = new NJS_OBJECT(datafile, ptr, imageBase, modelfmt, new Dictionary <int, Attach>()); string idx = name + "[" + i.ToString(NumberFormatInfo.InvariantInfo) + "]"; DllItemInfo info = new DllItemInfo() { Export = name, Index = i, Label = mdl.Name }; output.Items.Add(info); if (!labels.Contains(mdl.Name)) { string fn = Path.Combine(data.Filename, i.ToString(NumberFormatInfo.InvariantInfo) + modelext); models.Add(new ModelAnimations(fn, idx, mdl, modelfmt)); labels.AddRange(mdl.GetLabels()); } } address += 4; } break; case "modelsarray": for (int i = 0; i < data.Length; i++) { int ptr = BitConverter.ToInt32(datafile, address); if (ptr != 0) { ptr = (int)(ptr - imageBase); BasicAttach dummy = new BasicAttach(datafile, ptr, imageBase, modelfmt == ModelFormat.BasicDX); NJS_OBJECT mdl = new NJS_OBJECT() { Attach = dummy }; string idx = name + "[" + i.ToString(NumberFormatInfo.InvariantInfo) + "]"; DllItemInfo info = new DllItemInfo() { Export = name, Index = i, Label = dummy.Name }; output.Items.Add(info); if (!labels.Contains(dummy.Name)) { string fn = Path.Combine(data.Filename, i.ToString(NumberFormatInfo.InvariantInfo) + modelext); models.Add(new ModelAnimations(fn, idx, mdl, ModelFormat.BasicDX)); labels.AddRange(mdl.GetLabels()); } } address += 4; } break; case "basicmodel": { NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.Basic, new Dictionary <int, Attach>()); DllItemInfo info = new DllItemInfo() { Export = name, Label = mdl.Name }; output.Items.Add(info); if (!labels.Contains(mdl.Name)) { models.Add(new ModelAnimations(data.Filename, name, mdl, ModelFormat.Basic)); labels.AddRange(mdl.GetLabels()); } } break; case "basicmodelarray": for (int i = 0; i < data.Length; i++) { int ptr = BitConverter.ToInt32(datafile, address); if (ptr != 0) { ptr = (int)(ptr - imageBase); NJS_OBJECT mdl = new NJS_OBJECT(datafile, ptr, imageBase, ModelFormat.Basic, new Dictionary <int, Attach>()); string idx = name + "[" + i.ToString(NumberFormatInfo.InvariantInfo) + "]"; DllItemInfo info = new DllItemInfo() { Export = name, Index = i, Label = mdl.Name }; output.Items.Add(info); if (!labels.Contains(mdl.Name)) { string fn = Path.Combine(data.Filename, i.ToString(NumberFormatInfo.InvariantInfo) + ".sa1mdl"); models.Add(new ModelAnimations(fn, idx, mdl, ModelFormat.Basic)); labels.AddRange(mdl.GetLabels()); } } address += 4; } break; case "basicdxmodel": { NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.BasicDX, new Dictionary <int, Attach>()); DllItemInfo info = new DllItemInfo() { Export = name, Label = mdl.Name }; output.Items.Add(info); if (!labels.Contains(mdl.Name)) { models.Add(new ModelAnimations(data.Filename, name, mdl, ModelFormat.BasicDX)); labels.AddRange(mdl.GetLabels()); } } break; case "basicdxmodelarray": for (int i = 0; i < data.Length; i++) { int ptr = BitConverter.ToInt32(datafile, address); if (ptr != 0) { ptr = (int)(ptr - imageBase); NJS_OBJECT mdl = new NJS_OBJECT(datafile, ptr, imageBase, ModelFormat.BasicDX, new Dictionary <int, Attach>()); string idx = name + "[" + i.ToString(NumberFormatInfo.InvariantInfo) + "]"; DllItemInfo info = new DllItemInfo() { Export = name, Index = i, Label = mdl.Name }; output.Items.Add(info); if (!labels.Contains(mdl.Name)) { string fn = Path.Combine(data.Filename, i.ToString(NumberFormatInfo.InvariantInfo) + ".sa1mdl"); models.Add(new ModelAnimations(fn, idx, mdl, ModelFormat.BasicDX)); labels.AddRange(mdl.GetLabels()); } } address += 4; } break; case "chunkmodel": { NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.Chunk, new Dictionary <int, Attach>()); DllItemInfo info = new DllItemInfo() { Export = name, Label = mdl.Name }; output.Items.Add(info); if (!labels.Contains(mdl.Name)) { models.Add(new ModelAnimations(data.Filename, name, mdl, ModelFormat.Chunk)); labels.AddRange(mdl.GetLabels()); } } break; case "chunkmodelarray": for (int i = 0; i < data.Length; i++) { int ptr = BitConverter.ToInt32(datafile, address); if (ptr != 0) { ptr = (int)(ptr - imageBase); NJS_OBJECT mdl = new NJS_OBJECT(datafile, ptr, imageBase, ModelFormat.Chunk, new Dictionary <int, Attach>()); string idx = name + "[" + i.ToString(NumberFormatInfo.InvariantInfo) + "]"; DllItemInfo info = new DllItemInfo() { Export = name, Index = i, Label = mdl.Name }; output.Items.Add(info); if (!labels.Contains(mdl.Name)) { string fn = Path.Combine(data.Filename, i.ToString(NumberFormatInfo.InvariantInfo) + ".sa2mdl"); models.Add(new ModelAnimations(fn, idx, mdl, ModelFormat.Chunk)); labels.AddRange(mdl.GetLabels()); } } address += 4; } break; case "actionarray": for (int i = 0; i < data.Length; i++) { int ptr = BitConverter.ToInt32(datafile, address); if (ptr != 0) { ptr = (int)(ptr - imageBase); NJS_ACTION ani = new NJS_ACTION(datafile, ptr, imageBase, modelfmt, new Dictionary <int, Attach>()); string nm = item.Key + "_" + i; bool saveani = false; if (!anilabels.ContainsKey(ani.Animation.Name)) { anilabels.Add(ani.Animation.Name, nm); ani.Animation.Name = nm; saveani = true; } else { nm = anilabels[ani.Animation.Name]; } DllItemInfo info = new DllItemInfo() { Export = name, Index = i, Label = nm, Field = "motion" }; output.Items.Add(info); info = new DllItemInfo() { Export = name, Index = i, Label = ani.Model.Name, Field = "object" }; output.Items.Add(info); string outputFN = Path.Combine(fileOutputPath, i.ToString(NumberFormatInfo.InvariantInfo) + ".saanim"); string fn = Path.Combine(data.Filename, i.ToString(NumberFormatInfo.InvariantInfo) + ".saanim"); if (saveani) { ani.Animation.Save(outputFN); output.Files[fn] = new FileTypeHash("animation", HelperFunctions.FileHash(outputFN)); } if (models.Contains(ani.Model.Name)) { ModelAnimations mdl = models[ani.Model.Name]; System.Text.StringBuilder sb = new System.Text.StringBuilder(260); PathRelativePathTo(sb, Path.GetFullPath(Path.Combine(projectFolderName, mdl.Filename)), 0, Path.GetFullPath(outputFN), 0); mdl.Animations.Add(sb.ToString()); // this is where the problem is } else { string mfn = Path.ChangeExtension(fn, modelext); string outputmfn = Path.Combine(projectFolderName, mfn); string animationName = Path.GetFileName(outputFN); ModelFile.CreateFile(outputmfn, ani.Model, new[] { animationName }, null, $"{name}[{i}]->object", null, modelfmt); output.Files[mfn] = new FileTypeHash("model", HelperFunctions.FileHash(outputmfn)); } } address += 4; } break; case "motionarray": { int[] nodecounts = data.CustomProperties["nodecounts"].Split(',').Select(a => int.Parse(a)).ToArray(); for (int i = 0; i < data.Length; i++) { int ptr = BitConverter.ToInt32(datafile, address); if (ptr != 0) { ptr = (int)(ptr - imageBase); NJS_MOTION ani = new NJS_MOTION(datafile, ptr, imageBase, nodecounts[i]); string nm = item.Key + "_" + i; bool saveani = false; if (!anilabels.ContainsKey(ani.Name)) { anilabels.Add(ani.Name, nm); ani.Name = nm; saveani = true; } else { nm = anilabels[ani.Name]; } DllItemInfo info = new DllItemInfo() { Export = name, Index = i, Label = nm }; output.Items.Add(info); if (saveani) { string outputFN = Path.Combine(fileOutputPath, i.ToString(NumberFormatInfo.InvariantInfo) + ".saanim"); string fn = Path.Combine(data.Filename, i.ToString(NumberFormatInfo.InvariantInfo) + ".saanim"); ani.Save(outputFN); output.Files[fn] = new FileTypeHash("animation", HelperFunctions.FileHash(outputFN)); } } address += 4; } } break; case "texlist": if (output.TexLists == null) { output.TexLists = new TexListContainer(); } output.TexLists.Add((uint)(address + imageBase), new DllTexListInfo(name, null)); break; case "texlistarray": if (output.TexLists == null) { output.TexLists = new TexListContainer(); } for (int i = 0; i < data.Length; i++) { uint ptr = BitConverter.ToUInt32(datafile, address); if (ptr != 0 && !output.TexLists.ContainsKey(ptr)) { output.TexLists.Add(ptr, new DllTexListInfo(name, i)); } address += 4; } break; case "animindexlist": { Directory.CreateDirectory(fileOutputPath); List <string> hashes = new List <string>(); int i = ByteConverter.ToInt16(datafile, address); while (i != -1) { new NJS_MOTION(datafile, datafile.GetPointer(address + 4, imageBase), imageBase, ByteConverter.ToInt16(datafile, address + 2)) .Save(fileOutputPath + "/" + i.ToString(NumberFormatInfo.InvariantInfo) + ".saanim"); hashes.Add(i.ToString(NumberFormatInfo.InvariantInfo) + ":" + HelperFunctions.FileHash(fileOutputPath + "/" + i.ToString(NumberFormatInfo.InvariantInfo) + ".saanim")); address += 8; i = ByteConverter.ToInt16(datafile, address); } output.DataItems.Add(new DllDataItemInfo() { Type = type, Export = name, Filename = data.Filename, MD5Hash = string.Join("|", hashes.ToArray()) }); } break; case "charaobjectdatalist": { Directory.CreateDirectory(fileOutputPath); List <CharaObjectData> result = new List <CharaObjectData>(); List <string> hashes = new List <string>(); for (int i = 0; i < data.Length; i++) { string chnm = charaobjectnames[i]; CharaObjectData chara = new CharaObjectData(); NJS_OBJECT model = new NJS_OBJECT(datafile, (int)(BitConverter.ToInt32(datafile, address) - imageBase), imageBase, ModelFormat.Chunk, new Dictionary <int, Attach>()); chara.MainModel = model.Name; NJS_MOTION anim = new NJS_MOTION(datafile, (int)(BitConverter.ToInt32(datafile, address + 4) - imageBase), imageBase, model.CountAnimated()); chara.Animation1 = anim.Name; anim.Save(Path.Combine(fileOutputPath, $"{chnm} Anim 1.saanim")); hashes.Add($"{chnm} Anim 1.saanim:" + HelperFunctions.FileHash(Path.Combine(fileOutputPath, $"{chnm} Anim 1.saanim"))); anim = new NJS_MOTION(datafile, (int)(BitConverter.ToInt32(datafile, address + 8) - imageBase), imageBase, model.CountAnimated()); chara.Animation2 = anim.Name; anim.Save(Path.Combine(fileOutputPath, $"{chnm} Anim 2.saanim")); hashes.Add($"{chnm} Anim 2.saanim:" + HelperFunctions.FileHash(Path.Combine(fileOutputPath, $"{chnm} Anim 2.saanim"))); anim = new NJS_MOTION(datafile, (int)(BitConverter.ToInt32(datafile, address + 12) - imageBase), imageBase, model.CountAnimated()); chara.Animation3 = anim.Name; anim.Save(Path.Combine(fileOutputPath, $"{chnm} Anim 3.saanim")); hashes.Add($"{chnm} Anim 3.saanim:" + HelperFunctions.FileHash(Path.Combine(fileOutputPath, $"{chnm} Anim 3.saanim"))); ModelFile.CreateFile(Path.Combine(fileOutputPath, $"{chnm}.sa2mdl"), model, new[] { $"{chnm} Anim 1.saanim", $"{chnm} Anim 2.saanim", $"{chnm} Anim 3.saanim" }, null, null, null, ModelFormat.Chunk); hashes.Add($"{chnm}.sa2mdl:" + HelperFunctions.FileHash(Path.Combine(fileOutputPath, $"{chnm}.sa2mdl"))); int ptr = BitConverter.ToInt32(datafile, address + 16); if (ptr != 0) { model = new NJS_OBJECT(datafile, (int)(ptr - imageBase), imageBase, ModelFormat.Chunk, new Dictionary <int, Attach>()); chara.AccessoryModel = model.Name; chara.AccessoryAttachNode = "object_" + (BitConverter.ToInt32(datafile, address + 20) - imageBase).ToString("X8"); ModelFile.CreateFile(Path.Combine(fileOutputPath, $"{chnm} Accessory.sa2mdl"), model, null, null, null, null, ModelFormat.Chunk); hashes.Add($"{chnm} Accessory.sa2mdl:" + HelperFunctions.FileHash(Path.Combine(fileOutputPath, $"{chnm} Accessory.sa2mdl"))); } ptr = BitConverter.ToInt32(datafile, address + 24); if (ptr != 0) { model = new NJS_OBJECT(datafile, (int)(ptr - imageBase), imageBase, ModelFormat.Chunk, new Dictionary <int, Attach>()); chara.SuperModel = model.Name; anim = new NJS_MOTION(datafile, (int)(BitConverter.ToInt32(datafile, address + 28) - imageBase), imageBase, model.CountAnimated()); chara.SuperAnimation1 = anim.Name; anim.Save(Path.Combine(fileOutputPath, $"Super {chnm} Anim 1.saanim")); hashes.Add($"Super {chnm} Anim 1.saanim:" + HelperFunctions.FileHash(Path.Combine(fileOutputPath, $"Super {chnm} Anim 1.saanim"))); anim = new NJS_MOTION(datafile, (int)(BitConverter.ToInt32(datafile, address + 32) - imageBase), imageBase, model.CountAnimated()); chara.SuperAnimation2 = anim.Name; anim.Save(Path.Combine(fileOutputPath, $"Super {chnm} Anim 2.saanim")); hashes.Add($"Super {chnm} Anim 2.saanim:" + HelperFunctions.FileHash(Path.Combine(fileOutputPath, $"Super {chnm} Anim 2.saanim"))); anim = new NJS_MOTION(datafile, (int)(BitConverter.ToInt32(datafile, address + 36) - imageBase), imageBase, model.CountAnimated()); chara.SuperAnimation3 = anim.Name; anim.Save(Path.Combine(fileOutputPath, $"Super {chnm} Anim 3.saanim")); hashes.Add($"Super {chnm} Anim 3.saanim:" + HelperFunctions.FileHash(Path.Combine(fileOutputPath, $"Super {chnm} Anim 3.saanim"))); ModelFile.CreateFile(Path.Combine(fileOutputPath, $"Super {chnm}.sa2mdl"), model, new[] { $"Super {chnm} Anim 1.saanim", $"Super {chnm} Anim 2.saanim", $"Super {chnm} Anim 3.saanim" }, null, null, null, ModelFormat.Chunk); hashes.Add($"Super {chnm}.sa2mdl:" + HelperFunctions.FileHash(Path.Combine(fileOutputPath, $"Super {chnm}.sa2mdl"))); } chara.Unknown1 = BitConverter.ToInt32(datafile, address + 40); chara.Rating = BitConverter.ToInt32(datafile, address + 44); chara.DescriptionID = BitConverter.ToInt32(datafile, address + 48); chara.TextBackTexture = BitConverter.ToInt32(datafile, address + 52); chara.Unknown5 = BitConverter.ToSingle(datafile, address + 56); result.Add(chara); address += 60; } IniSerializer.Serialize(result, Path.Combine(fileOutputPath, "info.ini")); hashes.Add("info.ini:" + HelperFunctions.FileHash(Path.Combine(fileOutputPath, "info.ini"))); output.DataItems.Add(new DllDataItemInfo() { Type = type, Export = name, Filename = data.Filename, MD5Hash = string.Join("|", hashes.ToArray()) }); } break; case "kartspecialinfolist": { Directory.CreateDirectory(fileOutputPath); List <KartSpecialInfo> result = new List <KartSpecialInfo>(); List <string> hashes = new List <string>(); for (int i = 0; i < data.Length; i++) { KartSpecialInfo kart = new KartSpecialInfo { ID = ByteConverter.ToInt32(datafile, address) }; NJS_OBJECT model = new NJS_OBJECT(datafile, (int)(BitConverter.ToInt32(datafile, address + 4) - imageBase), imageBase, ModelFormat.Chunk, new Dictionary <int, Attach>()); kart.Model = model.Name; ModelFile.CreateFile(Path.Combine(fileOutputPath, $"{i}.sa2mdl"), model, null, null, null, null, ModelFormat.Chunk); hashes.Add($"{i}.sa2mdl:" + HelperFunctions.FileHash(Path.Combine(fileOutputPath, $"{i}.sa2mdl"))); int ptr = BitConverter.ToInt32(datafile, address + 8); if (ptr != 0) { model = new NJS_OBJECT(datafile, (int)(ptr - imageBase), imageBase, ModelFormat.Chunk, new Dictionary <int, Attach>()); kart.LowModel = model.Name; ModelFile.CreateFile(Path.Combine(fileOutputPath, $"{i} Low.sa2mdl"), model, null, null, null, null, ModelFormat.Chunk); hashes.Add($"{i} Low.sa2mdl:" + HelperFunctions.FileHash(Path.Combine(fileOutputPath, $"{i} Low.sa2mdl"))); } kart.TexList = ByteConverter.ToUInt32(datafile, address + 12); kart.Unknown1 = ByteConverter.ToInt32(datafile, address + 16); kart.Unknown2 = ByteConverter.ToInt32(datafile, address + 20); kart.Unknown3 = ByteConverter.ToInt32(datafile, address + 24); result.Add(kart); address += 0x1C; } IniSerializer.Serialize(result, Path.Combine(fileOutputPath, "info.ini")); hashes.Add("info.ini:" + HelperFunctions.FileHash(Path.Combine(fileOutputPath, "info.ini"))); output.DataItems.Add(new DllDataItemInfo() { Type = type, Export = name, Filename = data.Filename, MD5Hash = string.Join("|", hashes.ToArray()) }); } break; case "chaomotiontable": { Directory.CreateDirectory(fileOutputPath); List <ChaoMotionTableEntry> result = new List <ChaoMotionTableEntry>(); List <string> hashes = new List <string>(); int nodeCount = int.Parse(data.CustomProperties["nodecount"]); Dictionary <int, string> mtns = new Dictionary <int, string>(); for (int i = 0; i < data.Length; i++) { ChaoMotionTableEntry cmte = new ChaoMotionTableEntry(); int mtnaddr = (int)(ByteConverter.ToInt32(datafile, address) - imageBase); if (!mtns.ContainsKey(mtnaddr)) { NJS_MOTION motion = new NJS_MOTION(datafile, mtnaddr, imageBase, nodeCount, shortrot: true); cmte.Motion = motion.Name; mtns.Add(mtnaddr, motion.Name); motion.Save(Path.Combine(fileOutputPath, $"{i}.saanim")); hashes.Add($"{i}.saanim:" + HelperFunctions.FileHash(Path.Combine(fileOutputPath, $"{i}.saanim"))); } else { cmte.Motion = mtns[mtnaddr]; } cmte.Flag1 = ByteConverter.ToUInt16(datafile, address + 4); cmte.Pose = ByteConverter.ToUInt16(datafile, address + 6); cmte.TransitionID = ByteConverter.ToInt32(datafile, address + 8); cmte.Flag2 = ByteConverter.ToUInt32(datafile, address + 12); cmte.StartFrame = ByteConverter.ToSingle(datafile, address + 16); cmte.EndFrame = ByteConverter.ToSingle(datafile, address + 20); cmte.PlaySpeed = ByteConverter.ToSingle(datafile, address + 24); result.Add(cmte); address += 0x1C; } IniSerializer.Serialize(result, Path.Combine(fileOutputPath, "info.ini")); hashes.Add("info.ini:" + HelperFunctions.FileHash(Path.Combine(fileOutputPath, "info.ini"))); output.DataItems.Add(new DllDataItemInfo() { Type = type, Export = name, Filename = data.Filename, MD5Hash = string.Join("|", hashes.ToArray()) }); } break; } itemcount++; } foreach (ModelAnimations item in models) { string modelOutputPath = string.Concat(projectFolderName, item.Filename); //string modelOutputPath = item.Filename; ModelFile.CreateFile(modelOutputPath, item.Model, item.Animations.ToArray(), null, item.Name, null, item.Format); string type = "model"; switch (item.Format) { case ModelFormat.Basic: type = "basicmodel"; break; case ModelFormat.BasicDX: type = "basicdxmodel"; break; case ModelFormat.Chunk: type = "chunkmodel"; break; } output.Files[item.Filename] = new FileTypeHash(type, HelperFunctions.FileHash(modelOutputPath)); } IniSerializer.Serialize(output, Path.Combine(projectFolderName, Path.GetFileNameWithoutExtension(datafilename)) + "_data.ini"); timer.Stop(); Console.WriteLine("Split " + itemcount + " items in " + timer.Elapsed.TotalSeconds + " seconds."); Console.WriteLine(); } #if !DEBUG catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); Console.WriteLine("Press any key to exit."); Console.ReadLine(); return((int)SA_Tools.Split.SplitERRORVALUE.UnhandledException); } #endif return((int)SA_Tools.Split.SplitERRORVALUE.Success); }
public GCAttach(byte[] file, int address, uint imageBase, Dictionary <int, string> labels) { if (labels.ContainsKey(address)) { Name = labels[address]; } else { Name = "attach_" + address.ToString("X8"); } // The struct is 36/0x24 bytes long uint vertexAddress = ByteConverter.ToUInt32(file, address) - imageBase; //uint gap = ByteConverter.ToUInt32(file, address + 4); int opaqueAddress = (int)(ByteConverter.ToInt32(file, address + 8) - imageBase); int translucentAddress = (int)(ByteConverter.ToInt32(file, address + 12) - imageBase); int opaqueCount = ByteConverter.ToInt16(file, address + 16); int translucentCount = ByteConverter.ToInt16(file, address + 18); Bounds = new BoundingSphere(file, address + 20); // reading vertex data vertexData = new List <GCVertexSet>(); GCVertexSet vertexSet = new GCVertexSet(file, vertexAddress, imageBase); while (vertexSet.attribute != GCVertexAttribute.Null) { vertexData.Add(vertexSet); vertexAddress += 16; vertexSet = new GCVertexSet(file, vertexAddress, imageBase); } // reading geometry GCIndexAttributeFlags indexFlags = GCIndexAttributeFlags.HasPosition; opaqueMeshes = new List <GCMesh>(); for (int i = 0; i < opaqueCount; i++) { GCMesh mesh = new GCMesh(file, opaqueAddress, imageBase, indexFlags); GCIndexAttributeFlags?t = mesh.IndexFlags; if (t.HasValue) { indexFlags = t.Value; } opaqueMeshes.Add(mesh); opaqueAddress += 16; } translucentMeshes = new List <GCMesh>(); for (int i = 0; i < translucentCount; i++) { GCMesh mesh = new GCMesh(file, translucentAddress, imageBase, indexFlags); GCIndexAttributeFlags?t = mesh.IndexFlags; if (t.HasValue) { indexFlags = t.Value; } translucentMeshes.Add(mesh); translucentAddress += 16; } }
protected DicomValueElement(DicomTag tag, params Tv[] values) : this(tag, ByteConverter.ToByteBuffer <Tv>(values)) { }
private void ReceiveEnemyReconnection(byte[] buffer) { MultiBattle.Instance.enemyNetworkingState = EnemyNetworkingState.Reconnected; CheckChainingPacket(buffer, ByteConverter.ToInt(buffer, SocketInfo.PacketSizeStartIndex)); }
private void ReceiveBattleStart(byte[] buffer) { Debug.Log(LogType.Trace, "ReceiveBattleStart"); CheckChainingPacket(buffer, ByteConverter.ToInt(buffer, SocketInfo.PacketSizeStartIndex)); }
internal async Task ReceiveResponsesAsync() { // bufferSize is the minimum buffer size to rent from ArrayPool<byte>.Shared. We can actually // buffer much more than this value, it is merely the size of the buffer segments which will be used. // When operations larger than this size are encountered, additional segments will be requested from // the pool and retained only until that operation is completed. // // minimumReadSize is the minimum block of data to read into a buffer segment from the stream. If there is // not enough space left in a segment, a new segment will be requested from the pool. This is set to 1500 // to match the default IP MTU on most systems. var reader = PipeReader.Create(_stream, new StreamPipeReaderOptions( bufferSize: 65536, minimumReadSize: 1500)); try { while (true) { ReadResult result = await reader.ReadAsync().ConfigureAwait(false); ReadOnlySequence <byte> buffer = result.Buffer; // Process as many complete operation as we have in the buffer while (TryReadOperation(ref buffer, out IMemoryOwner <byte>?operationResponse)) { try { var opaque = ByteConverter.ToUInt32(operationResponse.Memory.Span.Slice(HeaderOffsets.Opaque)); if (_statesInFlight.TryRemove(opaque, out var state)) { state.Complete(operationResponse); } else { operationResponse.Dispose(); // create orphaned response context // var context = CreateOperationContext(opaque); // send to orphaned response reporter // ClusterOptions.ClientConfiguration.OrphanedResponseLogger.Add(context); } } catch { // Ownership of the buffer was not accepted by state.Complete due to an exception // Make sure we release the buffer operationResponse.Dispose(); throw; } UpdateLastActivity(); } // Tell the reader how much data we've actually consumed, the rest will remain for the next read reader.AdvanceTo(buffer.Start, buffer.End); // Stop reading if there's no more data if (result.IsCompleted) { break; } } HandleDisconnect(new Exception("socket closed.")); } #if NET452 catch (ThreadAbortException) {} #endif catch (ObjectDisposedException) {} catch (SocketException e) { //Dispose has already been thrown by another thread if ((int)e.SocketErrorCode != 10004) { HandleDisconnect(e); } } catch (Exception e) { HandleDisconnect(e); } finally { await reader.CompleteAsync().ConfigureAwait(false); } }
protected Buffer() { m_byteConverter = new ByteConverter(); }
public void ReadWriteDateTime() { DateTime[] values = new DateTime[] { new DateTime(1998, 12, 24, 12, 22, 13), DateTime.Now, DateTime.MinValue, DateTime.MaxValue }; ByteConverter[] endianness = new ByteConverter[] { ByteConverter.Big, ByteConverter.Little, ByteConverter.System }; using (MemoryStream stream = new MemoryStream()) using (BinaryStream binaryStream = new BinaryStream(stream)) { // Prepare test data. foreach (DateTime value in values) { binaryStream.WriteDateTime(value); } foreach (DateTime value in values) { binaryStream.WriteDateTime(value, DateTimeCoding.NetTicks); } foreach (ByteConverter endian in endianness) { foreach (DateTime value in values) { binaryStream.WriteDateTime(value, converter: endian); } } foreach (ByteConverter endian in endianness) { foreach (DateTime value in values) { binaryStream.WriteDateTime(value, DateTimeCoding.NetTicks, endian); } } // Read test data. binaryStream.Position = 0; foreach (DateTime value in values) { Assert.AreEqual(value, binaryStream.ReadDateTime()); } foreach (DateTime value in values) { Assert.AreEqual(value, binaryStream.ReadDateTime(DateTimeCoding.NetTicks)); } foreach (ByteConverter endian in endianness) { foreach (DateTime value in values) { Assert.AreEqual(value, binaryStream.ReadDateTime(converter: endian)); } } foreach (ByteConverter endian in endianness) { foreach (DateTime value in values) { Assert.AreEqual(value, binaryStream.ReadDateTime(DateTimeCoding.NetTicks, endian)); } } // Read test data all at once. binaryStream.Position = 0; CollectionAssert.AreEqual(values, binaryStream.ReadDateTimes(values.Length)); CollectionAssert.AreEqual(values, binaryStream.ReadDateTimes(values.Length, DateTimeCoding.NetTicks)); foreach (ByteConverter endian in endianness) { CollectionAssert.AreEqual(values, binaryStream.ReadDateTimes(values.Length, converter: endian)); } foreach (ByteConverter endian in endianness) { CollectionAssert.AreEqual(values, binaryStream.ReadDateTimes(values.Length, DateTimeCoding.NetTicks, endian)); } } }
public static int SplitFile(string datafilename, string inifilename, string projectFolderName) { try { byte[] datafile = File.ReadAllBytes(datafilename); IniData inifile = IniSerializer.Deserialize <IniData>(inifilename); if (inifile.MD5 != null && inifile.MD5.Count > 0) { string datahash = HelperFunctions.FileHash(datafile); if (!inifile.MD5.Any(h => h.Equals(datahash, StringComparison.OrdinalIgnoreCase))) { Console.WriteLine("The file {0} is not valid for use with the INI {1}.", datafilename, inifilename); return((int)SplitERRORVALUE.InvalidDataMapping); } } ByteConverter.BigEndian = SonicRetro.SAModel.ByteConverter.BigEndian = inifile.BigEndian; Environment.CurrentDirectory = Path.Combine(Environment.CurrentDirectory, Path.GetDirectoryName(datafilename)); if (inifile.Compressed) { datafile = FraGag.Compression.Prs.Decompress(datafile); } uint imageBase = HelperFunctions.SetupEXE(ref datafile) ?? inifile.ImageBase.Value; if (Path.GetExtension(datafilename).Equals(".rel", StringComparison.OrdinalIgnoreCase)) { HelperFunctions.FixRELPointers(datafile); } bool SA2 = inifile.Game == Game.SA2 | inifile.Game == Game.SA2B; ModelFormat modelfmt = 0; LandTableFormat landfmt = 0; switch (inifile.Game) { case Game.SA1: modelfmt = ModelFormat.Basic; landfmt = LandTableFormat.SA1; break; case Game.SADX: modelfmt = ModelFormat.BasicDX; landfmt = LandTableFormat.SADX; break; case Game.SA2: case Game.SA2B: modelfmt = ModelFormat.Chunk; landfmt = LandTableFormat.SA2; break; } int itemcount = 0; Dictionary <string, MasterObjectListEntry> masterobjlist = new Dictionary <string, MasterObjectListEntry>(); Dictionary <string, Dictionary <string, int> > objnamecounts = new Dictionary <string, Dictionary <string, int> >(); Stopwatch timer = new Stopwatch(); timer.Start(); foreach (KeyValuePair <string, SA_Tools.FileInfo> item in inifile.Files) { if (string.IsNullOrEmpty(item.Key)) { continue; } string filedesc = item.Key; SA_Tools.FileInfo data = item.Value; Dictionary <string, string> customProperties = data.CustomProperties; string type = data.Type; int address = data.Address; bool nohash = false; string fileOutputPath = string.Concat(projectFolderName, data.Filename); Console.WriteLine(item.Key + ": " + data.Address.ToString("X") + " → " + fileOutputPath); Directory.CreateDirectory(Path.GetDirectoryName(fileOutputPath)); switch (type) { case "landtable": new LandTable(datafile, address, imageBase, landfmt) { Description = item.Key }.SaveToFile(fileOutputPath, landfmt); break; case "model": { NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, modelfmt, new Dictionary <int, Attach>()); string[] mdlanis = new string[0]; if (customProperties.ContainsKey("animations")) { mdlanis = customProperties["animations"].Split(','); } string[] mdlmorphs = new string[0]; if (customProperties.ContainsKey("morphs")) { mdlmorphs = customProperties["morphs"].Split(','); } ModelFile.CreateFile(fileOutputPath, mdl, mdlanis, null, item.Key, null, modelfmt); } break; case "basicmodel": { NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.Basic, new Dictionary <int, Attach>()); string[] mdlanis = new string[0]; if (customProperties.ContainsKey("animations")) { mdlanis = customProperties["animations"].Split(','); } string[] mdlmorphs = new string[0]; if (customProperties.ContainsKey("morphs")) { mdlmorphs = customProperties["morphs"].Split(','); } ModelFile.CreateFile(fileOutputPath, mdl, mdlanis, null, item.Key, null, ModelFormat.Basic); } break; case "basicdxmodel": { NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.BasicDX, new Dictionary <int, Attach>()); string[] mdlanis = new string[0]; if (customProperties.ContainsKey("animations")) { mdlanis = customProperties["animations"].Split(','); } string[] mdlmorphs = new string[0]; if (customProperties.ContainsKey("morphs")) { mdlmorphs = customProperties["morphs"].Split(','); } ModelFile.CreateFile(fileOutputPath, mdl, mdlanis, null, item.Key, null, ModelFormat.BasicDX); } break; case "chunkmodel": { NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.Chunk, new Dictionary <int, Attach>()); string[] mdlanis = new string[0]; if (customProperties.ContainsKey("animations")) { mdlanis = customProperties["animations"].Split(','); } string[] mdlmorphs = new string[0]; if (customProperties.ContainsKey("morphs")) { mdlmorphs = customProperties["morphs"].Split(','); } ModelFile.CreateFile(fileOutputPath, mdl, mdlanis, null, item.Key, null, ModelFormat.Chunk); } break; case "gcmodel": { NJS_OBJECT mdl = new NJS_OBJECT(datafile, address, imageBase, ModelFormat.GC, new Dictionary <int, Attach>()); string[] mdlanis = new string[0]; if (customProperties.ContainsKey("animations")) { mdlanis = customProperties["animations"].Split(','); } string[] mdlmorphs = new string[0]; if (customProperties.ContainsKey("morphs")) { mdlmorphs = customProperties["morphs"].Split(','); } ModelFile.CreateFile(fileOutputPath, mdl, mdlanis, null, item.Key, null, ModelFormat.GC); } break; case "action": { NJS_ACTION ani = new NJS_ACTION(datafile, address, imageBase, modelfmt, new Dictionary <int, Attach>()); ani.Animation.Name = filedesc; ani.Animation.Save(fileOutputPath); } break; case "animation": new NJS_MOTION(datafile, address, imageBase, int.Parse(customProperties["numparts"], NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo)) { Name = filedesc } .Save(fileOutputPath); break; case "objlist": { ObjectListEntry[] objs = ObjectList.Load(datafile, address, imageBase, SA2); if (inifile.MasterObjectList != null) { foreach (ObjectListEntry obj in objs) { if (!masterobjlist.ContainsKey(obj.CodeString)) { masterobjlist.Add(obj.CodeString, new MasterObjectListEntry(obj)); } if (!objnamecounts.ContainsKey(obj.CodeString)) { objnamecounts.Add(obj.CodeString, new Dictionary <string, int>() { { obj.Name, 1 } }); } else if (!objnamecounts[obj.CodeString].ContainsKey(obj.Name)) { objnamecounts[obj.CodeString].Add(obj.Name, 1); } else { objnamecounts[obj.CodeString][obj.Name]++; } } } objs.Save(fileOutputPath); } break; case "startpos": if (SA2) { SA2StartPosList.Load(datafile, address).Save(fileOutputPath); } else { SA1StartPosList.Load(datafile, address).Save(fileOutputPath); } break; case "texlist": TextureList.Load(datafile, address, imageBase).Save(fileOutputPath); break; case "leveltexlist": new LevelTextureList(datafile, address, imageBase).Save(fileOutputPath); break; case "triallevellist": TrialLevelList.Save(TrialLevelList.Load(datafile, address, imageBase), fileOutputPath); break; case "bosslevellist": BossLevelList.Save(BossLevelList.Load(datafile, address), fileOutputPath); break; case "fieldstartpos": FieldStartPosList.Load(datafile, address).Save(fileOutputPath); break; case "soundtestlist": SoundTestList.Load(datafile, address, imageBase).Save(fileOutputPath); break; case "musiclist": { int muscnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); MusicList.Load(datafile, address, imageBase, muscnt).Save(fileOutputPath); } break; case "soundlist": SoundList.Load(datafile, address, imageBase).Save(fileOutputPath); break; case "stringarray": { int cnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); Languages lang = Languages.Japanese; if (data.CustomProperties.ContainsKey("language")) { lang = (Languages)Enum.Parse(typeof(Languages), data.CustomProperties["language"], true); } StringArray.Load(datafile, address, imageBase, cnt, lang).Save(fileOutputPath); } break; case "nextlevellist": NextLevelList.Load(datafile, address).Save(fileOutputPath); break; case "cutscenetext": { int cnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); new CutsceneText(datafile, address, imageBase, cnt).Save(fileOutputPath, out string[] hashes); data.MD5Hash = string.Join(",", hashes); nohash = true; } break; case "recapscreen": { int cnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); RecapScreenList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath, out string[][] hashes); string[] hash2 = new string[hashes.Length]; for (int i = 0; i < hashes.Length; i++) { hash2[i] = string.Join(",", hashes[i]); } data.MD5Hash = string.Join(":", hash2); nohash = true; } break; case "npctext": { int cnt = int.Parse(customProperties["length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); NPCTextList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath, out string[][] hashes); string[] hash2 = new string[hashes.Length]; for (int i = 0; i < hashes.Length; i++) { hash2[i] = string.Join(",", hashes[i]); } data.MD5Hash = string.Join(":", hash2); nohash = true; } break; case "levelclearflags": LevelClearFlagList.Save(LevelClearFlagList.Load(datafile, address), fileOutputPath); break; case "deathzone": { List <DeathZoneFlags> flags = new List <DeathZoneFlags>(); string path = Path.GetDirectoryName(fileOutputPath); List <string> hashes = new List <string>(); int num = 0; while (ByteConverter.ToUInt32(datafile, address + 4) != 0) { flags.Add(new DeathZoneFlags(datafile, address)); string file = Path.Combine(path, num++.ToString(NumberFormatInfo.InvariantInfo) + (modelfmt == ModelFormat.Chunk ? ".sa2mdl" : ".sa1mdl")); ModelFile.CreateFile(file, new NJS_OBJECT(datafile, datafile.GetPointer(address + 4, imageBase), imageBase, modelfmt, new Dictionary <int, Attach>()), null, null, null, null, modelfmt); hashes.Add(HelperFunctions.FileHash(file)); address += 8; } flags.ToArray().Save(fileOutputPath); hashes.Insert(0, HelperFunctions.FileHash(fileOutputPath)); data.MD5Hash = string.Join(",", hashes.ToArray()); nohash = true; } break; case "skyboxscale": { int cnt = int.Parse(customProperties["count"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); SkyboxScaleList.Load(datafile, address, imageBase, cnt).Save(fileOutputPath); } break; case "stageselectlist": { int cnt = int.Parse(customProperties["count"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); StageSelectLevelList.Load(datafile, address, cnt).Save(fileOutputPath); } break; case "levelrankscores": LevelRankScoresList.Load(datafile, address).Save(fileOutputPath); break; case "levelranktimes": LevelRankTimesList.Load(datafile, address).Save(fileOutputPath); break; case "endpos": SA2EndPosList.Load(datafile, address).Save(fileOutputPath); break; case "animationlist": { int cnt = int.Parse(customProperties["count"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo); SA2AnimationInfoList.Load(datafile, address, cnt).Save(fileOutputPath); } break; case "levelpathlist": { List <string> hashes = new List <string>(); ushort lvlnum = (ushort)ByteConverter.ToUInt32(datafile, address); while (lvlnum != 0xFFFF) { int ptr = ByteConverter.ToInt32(datafile, address + 4); if (ptr != 0) { ptr = (int)((uint)ptr - imageBase); SA1LevelAct level = new SA1LevelAct(lvlnum); string lvldir = Path.Combine(fileOutputPath, level.ToString()); PathList.Load(datafile, ptr, imageBase).Save(lvldir, out string[] lvlhashes); hashes.Add(level.ToString() + ":" + string.Join(",", lvlhashes)); } address += 8; lvlnum = (ushort)ByteConverter.ToUInt32(datafile, address); } data.MD5Hash = string.Join("|", hashes.ToArray()); nohash = true; } break; case "pathlist": { PathList.Load(datafile, address, imageBase).Save(fileOutputPath, out string[] hashes); data.MD5Hash = string.Join(",", hashes.ToArray()); nohash = true; } break; case "stagelightdatalist": SA1StageLightDataList.Load(datafile, address).Save(fileOutputPath); break; case "weldlist": WeldList.Load(datafile, address, imageBase).Save(fileOutputPath); break; case "bmitemattrlist": BlackMarketItemAttributesList.Load(datafile, address, imageBase).Save(fileOutputPath); break; case "creditstextlist": CreditsTextList.Load(datafile, address, imageBase).Save(fileOutputPath); break; case "animindexlist": { Directory.CreateDirectory(fileOutputPath); List <string> hashes = new List <string>(); int i = ByteConverter.ToInt16(datafile, address); while (i != -1) { new NJS_MOTION(datafile, datafile.GetPointer(address + 4, imageBase), imageBase, ByteConverter.ToInt16(datafile, address + 2)) .Save(fileOutputPath + "/" + i.ToString(NumberFormatInfo.InvariantInfo) + ".saanim"); hashes.Add(i.ToString(NumberFormatInfo.InvariantInfo) + ":" + HelperFunctions.FileHash(fileOutputPath + "/" + i.ToString(NumberFormatInfo.InvariantInfo) + ".saanim")); address += 8; i = ByteConverter.ToInt16(datafile, address); } data.MD5Hash = string.Join("|", hashes.ToArray()); nohash = true; } break; case "storysequence": SA2StoryList.Load(datafile, address).Save(fileOutputPath); break; default: // raw binary { byte[] bin = new byte[int.Parse(customProperties["size"], NumberStyles.HexNumber)]; Array.Copy(datafile, address, bin, 0, bin.Length); File.WriteAllBytes(fileOutputPath, bin); } break; } if (!nohash) { data.MD5Hash = HelperFunctions.FileHash(fileOutputPath); } itemcount++; } if (inifile.MasterObjectList != null) { foreach (KeyValuePair <string, MasterObjectListEntry> obj in masterobjlist) { KeyValuePair <string, int> name = new KeyValuePair <string, int>(); foreach (KeyValuePair <string, int> it in objnamecounts[obj.Key]) { if (it.Value > name.Value) { name = it; } } obj.Value.Name = name.Key; obj.Value.Names = objnamecounts[obj.Key].Select((it) => it.Key).ToArray(); } string masterObjectListOutputPath = string.Concat(projectFolderName, inifile.MasterObjectList); IniSerializer.Serialize(masterobjlist, masterObjectListOutputPath); } IniSerializer.Serialize(inifile, Path.Combine(projectFolderName, Path.GetFileNameWithoutExtension(datafilename) + "_data.ini")); timer.Stop(); Console.WriteLine("Split " + itemcount + " items in " + timer.Elapsed.TotalSeconds + " seconds."); Console.WriteLine(); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); Console.WriteLine("Press any key to exit."); Console.ReadLine(); return((int)SplitERRORVALUE.UnhandledException); } return((int)SplitERRORVALUE.Success); }
public void OnSend(Message message) { var response = message as Response; if (response != null) { Console.WriteLine(string.Format("response sent ({0}): {1}", message.Id, ByteConverter.GetString(message.Payload))); } }
public override byte[] GetBytes() { bool bigendianbk = ByteConverter.BigEndian; ByteConverter.BigEndian = Type == PuyoArchiveType.GVMFile; List <byte> result = new List <byte>(); result.AddRange(Type == PuyoArchiveType.PVMFile ? BitConverter.GetBytes(Magic_PVM) : BitConverter.GetBytes(Magic_GVM)); // Create entry list List <byte> entrytable = new List <byte>(); uint firstoffset = 12; for (int i = 0; i < Entries.Count; i++) { entrytable.AddRange(ByteConverter.GetBytes((ushort)i)); byte[] namestring = System.Text.Encoding.ASCII.GetBytes(Path.GetFileNameWithoutExtension(Entries[i].Name)); byte[] namefull = new byte[28]; Array.Copy(namestring, namefull, namestring.Length); entrytable.AddRange(namefull); ushort dimensions = 0; uint gbix = 0; if (Entries[i] is PVMEntry pvme) { PvrTexture pvrt = new PvrTexture(pvme.Data); entrytable.Add((byte)pvrt.PixelFormat); entrytable.Add((byte)pvrt.DataFormat); dimensions |= (ushort)(((byte)Math.Log(pvrt.TextureWidth, 2) - 2) & 0xF); dimensions |= (ushort)((((byte)Math.Log(pvrt.TextureHeight, 2) - 2) & 0xF) << 4); gbix = pvrt.GlobalIndex; } else if (Entries[i] is GVMEntry gvme) { GvrTexture gvrt = new GvrTexture(gvme.Data); entrytable.Add((byte)gvrt.PixelFormat); entrytable.Add((byte)gvrt.DataFormat); dimensions |= (ushort)(((byte)Math.Log(gvrt.TextureWidth, 2) - 2) & 0xF); dimensions |= (ushort)((((byte)Math.Log(gvrt.TextureHeight, 2) - 2) & 0xF) << 4); gbix = gvrt.GlobalIndex; } entrytable.AddRange(ByteConverter.GetBytes(dimensions)); entrytable.AddRange(ByteConverter.GetBytes(gbix)); } // Add padding if the data isn't aligned by 16 if ((12 + entrytable.Count) % 16 != 0) { do { entrytable.Add(0); }while ((12 + entrytable.Count) % 16 != 0); } // Write other header stuff result.AddRange(BitConverter.GetBytes((uint)(firstoffset + entrytable.Count - 8))); // Offset of the first texture, Little Endian result.AddRange(ByteConverter.GetBytes((ushort)0xF)); // PVM/GVM flags result.AddRange(ByteConverter.GetBytes((ushort)Entries.Count)); result.AddRange(entrytable); // Write texture data for (int i = 0; i < Entries.Count; i++) { // Align by 16 int length = Entries[i].Data.Length - 16; if (length % 16 != 0) { do { length++; }while (length % 16 != 0); } byte[] nogbix = new byte[length]; Array.Copy(Entries[i].Data, 16, nogbix, 0, Entries[i].Data.Length - 16); result.AddRange(nogbix); } ByteConverter.BigEndian = bigendianbk; return(result.ToArray()); }
public PuyoFile(byte[] pvmdata) { bool bigendianbk = ByteConverter.BigEndian; Entries = new List <GenericArchiveEntry>(); Type = Identify(pvmdata); switch (Type) { case PuyoArchiveType.PVMFile: ByteConverter.BigEndian = false; break; case PuyoArchiveType.GVMFile: ByteConverter.BigEndian = true; break; default: throw new Exception("Error: Unknown archive format"); } // Get PVM/GVM flags and calculate item size in the entry table ushort numtextures = ByteConverter.ToUInt16(pvmdata, 0x0A); int pvmentrysize = 2; int gbixoffset = 0; int nameoffset = 0; PuyoArchiveFlags flags = (PuyoArchiveFlags)ByteConverter.ToUInt16(pvmdata, 0x08); if (flags.HasFlag(PuyoArchiveFlags.Filenames)) { nameoffset = pvmentrysize; } pvmentrysize += 28; if (flags.HasFlag(PuyoArchiveFlags.PixelDataFormat)) { pvmentrysize += 2; } if (flags.HasFlag(PuyoArchiveFlags.TextureDimensions)) { pvmentrysize += 2; } if (flags.HasFlag(PuyoArchiveFlags.GlobalIndex)) { gbixoffset = pvmentrysize; } pvmentrysize += 4; int offsetfirst = BitConverter.ToInt32(pvmdata, 0x4) + 8; // Always Little Endian int textureaddr = GetPVRTOffset(pvmdata, offsetfirst); // Where texture data begins for (int t = 0; t < numtextures; t++) { int size_gbix = flags.HasFlag(PuyoArchiveFlags.GlobalIndex) ? 16 : 0; int size = BitConverter.ToInt32(pvmdata, textureaddr + 4); // Always Little Endian byte[] pvrchunk = new byte[size + 8 + size_gbix]; // Handle cases when data size in the PVR/GVR header goes beyond the range of the archive (Billy Hatcher) if ((textureaddr + size + 8) > pvmdata.Length) { do { size--; }while ((textureaddr + size + 8) > pvmdata.Length); } Array.Copy(pvmdata, textureaddr, pvrchunk, 0 + size_gbix, size + 8); // Add GBIX header if the PVM/GVM has GBIX enabled if (flags.HasFlag(PuyoArchiveFlags.GlobalIndex)) { Array.Copy(BitConverter.GetBytes(Magic_GBIX), 0, pvrchunk, 0, 4); // Little Endian pvrchunk[4] = 0x08; // Always 8 according to PuyoTools uint gbix = BitConverter.ToUInt32(pvmdata, 0xC + pvmentrysize * t + gbixoffset); byte[] gbixb = BitConverter.GetBytes(gbix); Array.Copy(gbixb, 0, pvrchunk, 8, 4); } // Set filename if the PVM/GVM has filenames string entryfn = t.ToString("D3"); if (flags.HasFlag(PuyoArchiveFlags.Filenames)) { byte[] namestring = new byte[28]; Array.Copy(pvmdata, 0xC + pvmentrysize * t + nameoffset, namestring, 0, 28); entryfn = Encoding.ASCII.GetString(namestring).TrimEnd((char)0); } if (t < numtextures - 1) // Get the address of the next PVRT chunk, unless it's the last one { textureaddr = GetPVRTOffset(pvmdata, textureaddr + size + 8); } // Add PVR/GVR texture to the entry list if (Type == PuyoArchiveType.PVMFile) { PvrTexture pvrt = new PvrTexture(pvrchunk); if (pvrt.NeedsExternalPalette) { PaletteRequired = true; } Entries.Add(new PVMEntry(pvrchunk, entryfn + ".pvr")); } else { GvrTexture gvrt = new GvrTexture(pvrchunk); if (gvrt.NeedsExternalPalette) { PaletteRequired = true; } Entries.Add(new GVMEntry(pvrchunk, entryfn + ".gvr")); } } ByteConverter.BigEndian = bigendianbk; }
private void ReceivePlayerNumber(byte[] buffer) { playerNumber = ByteConverter.ToInt(buffer, 9); CheckChainingPacket(buffer, ByteConverter.ToInt(buffer, SocketInfo.PacketSizeStartIndex)); }
public byte[] GetBytes() { ArrayList res = new ArrayList(); res.Add((byte)BacNetEnums.BACNET_PDU_TYPE.PDU_TYPE_CONFIRMED_SERVICE_REQUEST); res.Add((byte)84); res.Add(BacNetDevice.Instance.InvokeId); res.Add((byte)BacNetEnums.BACNET_CONFIRMED_SERVICE.SERVICE_CONFIRMED_CREATE_OBJECT); BacNetTag openingTag = new BacNetTag { Class = true, Length = 6, Number = 0 }; res.AddRange(openingTag.GetBytes()); BacNetTag objectTag = new BacNetTag { Class = true, Length = 4, Number = 1 }; res.AddRange(objectTag.GetBytes()); res.AddRange(NewObject.GetObjectBytes()); BacNetTag closingTag = new BacNetTag { Class = true, Length = 7, Number = 0 }; res.AddRange(closingTag.GetBytes()); objectTag.Class = false; objectTag.Number = 0; openingTag.Number = 1; res.AddRange(openingTag.GetBytes()); openingTag.Number = 2; closingTag.Number = 2; foreach (BacNetProperty property in NewObject.Properties) { BacNetTag propertyIdTag = new BacNetTag { Class = true, Length = (byte)property.PropertyId.GetLength(), Number = 0 }; res.AddRange(propertyIdTag.GetBytes()); res.AddRange(property.PropertyId.GetBytes()); res.AddRange(openingTag.GetBytes()); BacNetTag metaTag = new BacNetTag(); foreach (var value in property.Values) { int type; byte[] valueBytes = ByteConverter.GetPropertyValueBytes(value, out type); metaTag = new BacNetTag { Class = false, Length = (byte)valueBytes.Length, Number = (byte)type, LongTag = true }; res.AddRange(metaTag.GetBytes()); res.AddRange(valueBytes); } res.AddRange(closingTag.GetBytes()); } closingTag.Number = 1; res.AddRange(closingTag.GetBytes()); return((byte[])res.ToArray(typeof(byte))); }
private void ReceiveSkill(byte[] buffer) { //AddExecutionDataToManager(executionData); CheckChainingPacket(buffer, ByteConverter.ToInt(buffer, SocketInfo.PacketSizeStartIndex)); }
public override byte[] ConvertToByteArray() { return(ByteConverter.ToBytes(m_msg)); }
public void SetUp() { converter = new ByteConverter(); }
/// <summary> /// 从流中读取2个字节,并将流内的位置向前推进2个字节, /// 返回其Int16表示类型 /// </summary> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <returns></returns> public short ReadInt16(Endians endian) { var range = this.ReadArraySegment(sizeof(short)); return(ByteConverter.ToInt16(range.Array, range.Offset, endian)); }
protected DicomStringElement(DicomTag tag, Encoding encoding, string value) : base(tag, EmptyBuffer.Value) { Encoding = encoding; Buffer = ByteConverter.ToByteBuffer(value ?? String.Empty, encoding, ValueRepresentation.PaddingValue); }
/// <summary> /// 从流中读取4个字节,并将流内的位置向前推进4个字节, /// 返回其UInt32表示类型 /// </summary> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <returns></returns> public uint ReadUInt32(Endians endian) { var range = this.ReadArraySegment(sizeof(uint)); return(ByteConverter.ToUInt32(range.Array, range.Offset, endian)); }
public void Test_ToArray() { byte[] value = ByteConverter.ToArray(IntPtr.Zero, 4); Assert.Null(value); }
/// <summary> /// 从流中读取8个字节,并将流内的位置向前推进8个字节, /// 返回其UInt64表示类型 /// </summary> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <returns></returns> public ulong ReadUInt64(Endians endian) { var range = this.ReadArraySegment(sizeof(ulong)); return(ByteConverter.ToUInt64(range.Array, range.Offset, endian)); }
public void ReadWriteString() { String[] values = new String[] { String.Empty, "Hallo, Kitty!", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "0123456789?!;:'[]{}-_*&^%$#@", "🐔🐓🥚🐣🐤🐥🐻🦆" }; StringCoding[] encodings = new StringCoding[] { StringCoding.ByteCharCount, StringCoding.Int16CharCount, StringCoding.Int32CharCount, StringCoding.VariableByteCount, StringCoding.ZeroTerminated }; ByteConverter[] endianness = new ByteConverter[] { ByteConverter.Big, ByteConverter.Little, ByteConverter.System }; using (MemoryStream stream = new MemoryStream()) { // Prepare test data. foreach (String value in values) { stream.WriteString(value); } foreach (StringCoding encoding in encodings) { foreach (String value in values) { stream.WriteString(value, encoding); } } foreach (ByteConverter endian in endianness) { foreach (String value in values) { stream.WriteString(value, converter: endian); } } foreach (ByteConverter endian in endianness) { foreach (StringCoding encoding in encodings) { foreach (String value in values) { stream.WriteString(value, encoding, converter: endian); } } } // Read test data. stream.Position = 0; foreach (String value in values) { Assert.AreEqual(value, stream.ReadString()); } foreach (StringCoding encoding in encodings) { foreach (String value in values) { Assert.AreEqual(value, stream.ReadString(encoding)); } } foreach (ByteConverter endian in endianness) { foreach (String value in values) { Assert.AreEqual(value, stream.ReadString(converter: endian)); } } foreach (ByteConverter endian in endianness) { foreach (StringCoding encoding in encodings) { foreach (String value in values) { Assert.AreEqual(value, stream.ReadString(encoding, converter: endian)); } } } // Read test data all at once. stream.Position = 0; CollectionAssert.AreEqual(values, stream.ReadStrings(values.Length)); foreach (StringCoding encoding in encodings) { CollectionAssert.AreEqual(values, stream.ReadStrings(values.Length, encoding)); } foreach (ByteConverter endian in endianness) { CollectionAssert.AreEqual(values, stream.ReadStrings(values.Length, converter: endian)); } foreach (ByteConverter endian in endianness) { foreach (StringCoding encoding in encodings) { CollectionAssert.AreEqual(values, stream.ReadStrings(values.Length, encoding, converter: endian)); } } } }
public static void Split(string filename) { nodenames.Clear(); modelfiles.Clear(); motionfiles.Clear(); Console.WriteLine("Splitting file {0}...", filename); byte[] fc; if (Path.GetExtension(filename).Equals(".prs", StringComparison.OrdinalIgnoreCase)) { fc = Prs.Decompress(filename); } else { fc = File.ReadAllBytes(filename); } MiniEventIniData ini = new MiniEventIniData() { Name = Path.GetFileNameWithoutExtension(filename) }; string path = Directory.CreateDirectory(Path.Combine(Path.GetDirectoryName(Path.GetFullPath(filename)), Path.GetFileNameWithoutExtension(filename))).FullName; uint key; List <NJS_MOTION> motions = null; if (fc[4] == 0x81) { Console.WriteLine("File is in GC/PC format."); ByteConverter.BigEndian = true; key = 0x816DFE60; ini.Game = Game.SA2B; } else { Console.WriteLine("File is in DC format."); ByteConverter.BigEndian = false; key = 0xCB00000; ini.Game = Game.SA2; } int ptr = fc.GetPointer(8, key); if (ptr != 0) { Console.WriteLine("Sonic is in this Mini-Event"); Directory.CreateDirectory(Path.Combine(path, "Sonic")); MiniEventChars data = new MiniEventChars(); data.BodyAnims = GetMotion(fc, ptr, key, $"Sonic\\Body.saanim", motions, 62); int ptr2 = fc.GetPointer(ptr + 4, key); if (ptr2 != 0) { data.HeadPart = GetModel(fc, ptr + 4, key, $"Sonic\\Head.sa2mdl"); } if (data.HeadPart != null) { data.HeadAnims = GetMotion(fc, ptr + 8, key, $"Sonic\\Head.saanim", motions, modelfiles[data.HeadPart].Model.CountAnimated()); if (data.HeadAnims != null) { modelfiles[data.HeadPart].Motions.Add($"Head.saanim"); } data.HeadShapeMotions = GetMotion(fc, ptr + 0xC, key, $"Sonic\\HeadShape.saanim", motions, modelfiles[data.HeadPart].Model.CountMorph()); if (data.HeadShapeMotions != null) { modelfiles[data.HeadPart].Motions.Add($"HeadShape.saanim"); } } ptr2 = fc.GetPointer(ptr + 0x10, key); if (ptr2 != 0) { data.MouthPart = GetModel(fc, ptr + 0x10, key, $"Sonic\\Mouth.sa2mdl"); } if (data.MouthPart != null) { data.MouthAnims = GetMotion(fc, ptr + 0x14, key, $"Sonic\\Mouth.saanim", motions, modelfiles[data.MouthPart].Model.CountAnimated()); if (data.MouthAnims != null) { modelfiles[data.MouthPart].Motions.Add($"Mouth.saanim"); } data.MouthShapeMotions = GetMotion(fc, ptr + 0x18, key, $"Sonic\\MouthShape.saanim", motions, modelfiles[data.MouthPart].Model.CountMorph()); if (data.MouthShapeMotions != null) { modelfiles[data.MouthPart].Motions.Add($"MouthShape.saanim"); } } ptr2 = fc.GetPointer(ptr + 0x1C, key); if (ptr2 != 0) { data.LHandPart = GetModel(fc, ptr + 0x1C, key, $"Sonic\\LeftHand.sa2mdl"); } if (data.LHandPart != null) { data.LHandAnims = GetMotion(fc, ptr + 0x20, key, $"Sonic\\LeftHand.saanim", motions, modelfiles[data.LHandPart].Model.CountAnimated()); if (data.LHandAnims != null) { modelfiles[data.LHandPart].Motions.Add($"LeftHand.saanim"); } data.LHandShapeMotions = GetMotion(fc, ptr + 0x24, key, $"Sonic\\LeftHandShape.saanim", motions, modelfiles[data.LHandPart].Model.CountMorph()); if (data.LHandShapeMotions != null) { modelfiles[data.LHandPart].Motions.Add($"LeftHandShape.saanim"); } } ptr2 = fc.GetPointer(ptr + 0x28, key); if (ptr2 != 0) { data.RHandPart = GetModel(fc, ptr + 0x28, key, $"Sonic\\RightHand.sa2mdl"); } if (data.RHandPart != null) { data.RHandAnims = GetMotion(fc, ptr + 0x2C, key, $"Sonic\\RightHand.saanim", motions, modelfiles[data.RHandPart].Model.CountAnimated()); if (data.RHandAnims != null) { modelfiles[data.RHandPart].Motions.Add($"RightHand.saanim"); } data.RHandShapeMotions = GetMotion(fc, ptr + 0x30, key, $"Sonic\\RightHandShape.saanim", motions, modelfiles[data.RHandPart].Model.CountMorph()); if (data.RHandShapeMotions != null) { modelfiles[data.RHandPart].Motions.Add($"RightHandShape.saanim"); } } ini.Sonic.Add(data); } ptr = fc.GetPointer(0xC, key); if (ptr != 0) { Console.WriteLine("Shadow is in this Mini-Event"); Directory.CreateDirectory(Path.Combine(path, "Shadow")); MiniEventChars data = new MiniEventChars(); data.BodyAnims = GetMotion(fc, ptr, key, $"Shadow\\Body.saanim", motions, 62); int ptr2 = fc.GetPointer(ptr + 4, key); if (ptr2 != 0) { data.HeadPart = GetModel(fc, ptr + 4, key, $"Shadow\\Head.sa2mdl"); } if (data.HeadPart != null) { data.HeadAnims = GetMotion(fc, ptr + 8, key, $"Shadow\\Head.saanim", motions, modelfiles[data.HeadPart].Model.CountAnimated()); if (data.HeadAnims != null) { modelfiles[data.HeadPart].Motions.Add($"Head.saanim"); } data.HeadShapeMotions = GetMotion(fc, ptr + 0xC, key, $"Shadow\\HeadShape.saanim", motions, modelfiles[data.HeadPart].Model.CountMorph()); if (data.HeadShapeMotions != null) { modelfiles[data.HeadPart].Motions.Add($"HeadShape.saanim"); } } ptr2 = fc.GetPointer(ptr + 0x10, key); if (ptr2 != 0) { data.MouthPart = GetModel(fc, ptr + 0x10, key, $"Shadow\\Mouth.sa2mdl"); } if (data.MouthPart != null) { data.MouthAnims = GetMotion(fc, ptr + 0x14, key, $"Shadow\\Mouth.saanim", motions, modelfiles[data.MouthPart].Model.CountAnimated()); if (data.MouthAnims != null) { modelfiles[data.MouthPart].Motions.Add($"Mouth.saanim"); } data.MouthShapeMotions = GetMotion(fc, ptr + 0x18, key, $"Shadow\\MouthShape.saanim", motions, modelfiles[data.MouthPart].Model.CountMorph()); if (data.MouthShapeMotions != null) { modelfiles[data.MouthPart].Motions.Add($"MouthShape.saanim"); } } ptr2 = fc.GetPointer(ptr + 0x1C, key); if (ptr2 != 0) { data.LHandPart = GetModel(fc, ptr + 0x1C, key, $"Shadow\\LeftHand.sa2mdl"); } if (data.LHandPart != null) { data.LHandAnims = GetMotion(fc, ptr + 0x20, key, $"Shadow\\LeftHand.saanim", motions, modelfiles[data.LHandPart].Model.CountAnimated()); if (data.LHandAnims != null) { modelfiles[data.LHandPart].Motions.Add($"LeftHand.saanim"); } data.LHandShapeMotions = GetMotion(fc, ptr + 0x24, key, $"Shadow\\LeftHandShape.saanim", motions, modelfiles[data.LHandPart].Model.CountMorph()); if (data.LHandShapeMotions != null) { modelfiles[data.LHandPart].Motions.Add($"LeftHandShape.saanim"); } } ptr2 = fc.GetPointer(ptr + 0x28, key); if (ptr2 != 0) { data.RHandPart = GetModel(fc, ptr + 0x28, key, $"Shadow\\RightHand.sa2mdl"); } if (data.RHandPart != null) { data.RHandAnims = GetMotion(fc, ptr + 0x2C, key, $"Shadow\\RightHand.saanim", motions, modelfiles[data.RHandPart].Model.CountAnimated()); if (data.RHandAnims != null) { modelfiles[data.RHandPart].Motions.Add($"RightHand.saanim"); } data.RHandShapeMotions = GetMotion(fc, ptr + 0x30, key, $"Shadow\\RightHandShape.saanim", motions, modelfiles[data.RHandPart].Model.CountMorph()); if (data.RHandShapeMotions != null) { modelfiles[data.RHandPart].Motions.Add($"RightHandShape.saanim"); } } ini.Shadow.Add(data); } ptr = fc.GetPointer(0x18, key); if (ptr != 0) { Console.WriteLine("Knuckles is in this Mini-Event"); Directory.CreateDirectory(Path.Combine(path, "Knuckles")); MiniEventChars data = new MiniEventChars(); data.BodyAnims = GetMotion(fc, ptr, key, $"Knuckles\\Body.saanim", motions, 62); int ptr2 = fc.GetPointer(ptr + 4, key); if (ptr2 != 0) { data.HeadPart = GetModel(fc, ptr + 4, key, $"Knuckles\\Head.sa2mdl"); } if (data.HeadPart != null) { data.HeadAnims = GetMotion(fc, ptr + 8, key, $"Knuckles\\Head.saanim", motions, modelfiles[data.HeadPart].Model.CountAnimated()); if (data.HeadAnims != null) { modelfiles[data.HeadPart].Motions.Add($"Head.saanim"); } data.HeadShapeMotions = GetMotion(fc, ptr + 0xC, key, $"Knuckles\\HeadShape.saanim", motions, modelfiles[data.HeadPart].Model.CountMorph()); if (data.HeadShapeMotions != null) { modelfiles[data.HeadPart].Motions.Add($"HeadShape.saanim"); } } ptr2 = fc.GetPointer(ptr + 0x10, key); if (ptr2 != 0) { data.MouthPart = GetModel(fc, ptr + 0x10, key, $"Knuckles\\Mouth.sa2mdl"); } if (data.MouthPart != null) { data.MouthAnims = GetMotion(fc, ptr + 0x14, key, $"Knuckles\\Mouth.saanim", motions, modelfiles[data.MouthPart].Model.CountAnimated()); if (data.MouthAnims != null) { modelfiles[data.MouthPart].Motions.Add($"Mouth.saanim"); } data.MouthShapeMotions = GetMotion(fc, ptr + 0x18, key, $"Knuckles\\MouthShape.saanim", motions, modelfiles[data.MouthPart].Model.CountMorph()); if (data.MouthShapeMotions != null) { modelfiles[data.MouthPart].Motions.Add($"MouthShape.saanim"); } } ptr2 = fc.GetPointer(ptr + 0x1C, key); if (ptr2 != 0) { data.LHandPart = GetModel(fc, ptr + 0x1C, key, $"Knuckles\\LeftHand.sa2mdl"); } if (data.LHandPart != null) { data.LHandAnims = GetMotion(fc, ptr + 0x20, key, $"Knuckles\\LeftHand.saanim", motions, modelfiles[data.LHandPart].Model.CountAnimated()); if (data.LHandAnims != null) { modelfiles[data.LHandPart].Motions.Add($"LeftHand.saanim"); } data.LHandShapeMotions = GetMotion(fc, ptr + 0x24, key, $"Knuckles\\LeftHandShape.saanim", motions, modelfiles[data.LHandPart].Model.CountMorph()); if (data.LHandShapeMotions != null) { modelfiles[data.LHandPart].Motions.Add($"LeftHandShape.saanim"); } } ptr2 = fc.GetPointer(ptr + 0x28, key); if (ptr2 != 0) { data.RHandPart = GetModel(fc, ptr + 0x28, key, $"Knuckles\\RightHand.sa2mdl"); } if (data.RHandPart != null) { data.RHandAnims = GetMotion(fc, ptr + 0x2C, key, $"Knuckles\\RightHand.saanim", motions, modelfiles[data.RHandPart].Model.CountAnimated()); if (data.RHandAnims != null) { modelfiles[data.RHandPart].Motions.Add($"RightHand.saanim"); } data.RHandShapeMotions = GetMotion(fc, ptr + 0x30, key, $"Knuckles\\RightHandShape.saanim", motions, modelfiles[data.RHandPart].Model.CountMorph()); if (data.RHandShapeMotions != null) { modelfiles[data.RHandPart].Motions.Add($"RightHandShape.saanim"); } } ini.Knuckles.Add(data); } ptr = fc.GetPointer(0x1C, key); if (ptr != 0) { Console.WriteLine("Rouge is in this Mini-Event"); Directory.CreateDirectory(Path.Combine(path, "Rouge")); MiniEventChars data = new MiniEventChars(); data.BodyAnims = GetMotion(fc, ptr, key, $"Rouge\\Body.saanim", motions, 62); int ptr2 = fc.GetPointer(ptr + 4, key); if (ptr2 != 0) { data.HeadPart = GetModel(fc, ptr + 4, key, $"Rouge\\Head.sa2mdl"); } if (data.HeadPart != null) { data.HeadAnims = GetMotion(fc, ptr + 8, key, $"Rouge\\Head.saanim", motions, modelfiles[data.HeadPart].Model.CountAnimated()); if (data.HeadAnims != null) { modelfiles[data.HeadPart].Motions.Add($"Head.saanim"); } data.HeadShapeMotions = GetMotion(fc, ptr + 0xC, key, $"Rouge\\HeadShape.saanim", motions, modelfiles[data.HeadPart].Model.CountMorph()); if (data.HeadShapeMotions != null) { modelfiles[data.HeadPart].Motions.Add($"HeadShape.saanim"); } } ptr2 = fc.GetPointer(ptr + 0x10, key); if (ptr2 != 0) { data.MouthPart = GetModel(fc, ptr + 0x10, key, $"Rouge\\Mouth.sa2mdl"); } if (data.MouthPart != null) { data.MouthAnims = GetMotion(fc, ptr + 0x14, key, $"Rouge\\Mouth.saanim", motions, modelfiles[data.MouthPart].Model.CountAnimated()); if (data.MouthAnims != null) { modelfiles[data.MouthPart].Motions.Add($"Mouth.saanim"); } data.MouthShapeMotions = GetMotion(fc, ptr + 0x18, key, $"Rouge\\MouthShape.saanim", motions, modelfiles[data.MouthPart].Model.CountMorph()); if (data.MouthShapeMotions != null) { modelfiles[data.MouthPart].Motions.Add($"MouthShape.saanim"); } } ptr2 = fc.GetPointer(ptr + 0x1C, key); if (ptr2 != 0) { data.LHandPart = GetModel(fc, ptr + 0x1C, key, $"Rouge\\LeftHand.sa2mdl"); } if (data.LHandPart != null) { data.LHandAnims = GetMotion(fc, ptr + 0x20, key, $"Rouge\\LeftHand.saanim", motions, modelfiles[data.LHandPart].Model.CountAnimated()); if (data.LHandAnims != null) { modelfiles[data.LHandPart].Motions.Add($"LeftHand.saanim"); } data.LHandShapeMotions = GetMotion(fc, ptr + 0x24, key, $"Rouge\\LeftHandShape.saanim", motions, modelfiles[data.LHandPart].Model.CountMorph()); if (data.LHandShapeMotions != null) { modelfiles[data.LHandPart].Motions.Add($"LeftHandShape.saanim"); } } ptr2 = fc.GetPointer(ptr + 0x28, key); if (ptr2 != 0) { data.RHandPart = GetModel(fc, ptr + 0x28, key, $"Rouge\\RightHand.sa2mdl"); } if (data.RHandPart != null) { data.RHandAnims = GetMotion(fc, ptr + 0x2C, key, $"Rouge\\RightHand.saanim", motions, modelfiles[data.RHandPart].Model.CountAnimated()); if (data.RHandAnims != null) { modelfiles[data.RHandPart].Motions.Add($"RightHand.saanim"); } data.RHandShapeMotions = GetMotion(fc, ptr + 0x30, key, $"Rouge\\RightHandShape.saanim", motions, modelfiles[data.RHandPart].Model.CountMorph()); if (data.RHandShapeMotions != null) { modelfiles[data.RHandPart].Motions.Add($"RightHandShape.saanim"); } } ini.Rouge.Add(data); } ptr = fc.GetPointer(0x24, key); if (ptr != 0) { Console.WriteLine("Mech Eggman is in this Mini-Event"); Directory.CreateDirectory(Path.Combine(path, "Mech Eggman")); ini.MechEggmanBodyAnims = GetMotion(fc, ptr, key, $"Mech Eggman\\Body.saanim", motions, 33); } ptr = fc.GetPointer(4, key); if (ptr != 0) { ini.Camera = GetMotion(fc, ptr + 0x10, key, $"Camera.saanim", motions, 1); ini.CamFrames = ByteConverter.ToInt32(fc, ptr + 4); } else { Console.WriteLine("Mini-Event does not contain a camera."); } foreach (var item in motionfiles.Values) { string fn = item.Filename; string fp = Path.Combine(path, fn); item.Motion.Save(fp); ini.Files.Add(fn, HelperFunctions.FileHash(fp)); } foreach (var item in modelfiles.Values) { string fp = Path.Combine(path, item.Filename); ModelFile.CreateFile(fp, item.Model, item.Motions.ToArray(), null, null, null, item.Format); ini.Files.Add(item.Filename, HelperFunctions.FileHash(fp)); } JsonSerializer js = new JsonSerializer { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore }; using (var tw = File.CreateText(Path.Combine(path, Path.ChangeExtension(Path.GetFileName(filename), ".json")))) js.Serialize(tw, ini); }
protected void DoSerialize(MemoryStream stream, Type type, object obj) { if (type != typeof(object)) { byte[] buffer5; if (type == typeof(Font)) { if (obj != null) { obj = new SimpleFont((Font)obj); } type = typeof(SimpleFont); } if (ByteConverter.SupportType(type)) { buffer5 = ByteConverter.ToBytes(type, obj); stream.Write(buffer5, 0, buffer5.Length); } else if (type == typeof(Color)) { Color color = (Color)obj; byte[] bytes = BitConverter.GetBytes((short)color.R); byte[] buffer3 = BitConverter.GetBytes((short)color.G); byte[] buffer4 = BitConverter.GetBytes((short)color.B); stream.Write(bytes, 0, 1); stream.Write(buffer3, 0, 1); stream.Write(buffer4, 0, 1); } else if (type == typeof(string)) { if (obj == null) { buffer5 = ByteConverter.ToBytes <int>(-1); stream.Write(buffer5, 0, buffer5.Length); } else { byte[] buffer8 = Encoding.UTF8.GetBytes(obj.ToString()); byte[] buffer9 = ByteConverter.ToBytes <int>(buffer8.Length); stream.Write(buffer9, 0, buffer9.Length); stream.Write(buffer8, 0, buffer8.Length); } } else { byte[] buffer; byte[] buffer7; if (type == typeof(byte[])) { if (obj == null) { buffer5 = ByteConverter.ToBytes <int>(-1); stream.Write(buffer5, 0, buffer5.Length); } else { buffer = (byte[])obj; buffer7 = ByteConverter.ToBytes <int>(buffer.Length); stream.Write(buffer7, 0, buffer7.Length); stream.Write(buffer, 0, buffer.Length); } } else if ((type == typeof(Image)) || type.IsSubclassOf(typeof(Image))) { if (obj == null) { buffer5 = ByteConverter.ToBytes <int>(-1); stream.Write(buffer5, 0, buffer5.Length); } else { buffer = null; bool flag = false; Image image = (Image)obj; FrameDimension dimension = new FrameDimension(image.FrameDimensionsList[0]); if (image.GetFrameCount(dimension) > 1) { flag = true; buffer = SerializeHelper.SerializeObject(image); } else { buffer = ImageHelper.Convert(image); } buffer7 = ByteConverter.ToBytes <int>(buffer.Length); stream.Write(buffer7, 0, buffer7.Length); stream.Write(BitConverter.GetBytes(flag), 0, 1); stream.Write(buffer, 0, buffer.Length); } } else { byte[] buffer6; if (type.IsGenericType && ((type.GetGenericTypeDefinition() == typeof(IList <>)) || (type.GetGenericTypeDefinition() == typeof(List <>)))) { if (obj == null) { buffer5 = ByteConverter.ToBytes <int>(-1); stream.Write(buffer5, 0, 4); } else { Type type4 = type.GetGenericArguments()[0]; IList list = (IList)obj; buffer6 = ByteConverter.ToBytes <int>(list.Count); stream.Write(buffer6, 0, 4); for (int i = 0; i < list.Count; i++) { object obj1 = list[i]; this.DoSerialize(stream, type4, list[i]); } } } else if (type.IsGenericType && ((type.GetGenericTypeDefinition() == typeof(IDictionary <,>)) || (type.GetGenericTypeDefinition() == typeof(Dictionary <,>)))) { if (obj == null) { buffer5 = ByteConverter.ToBytes <int>(-1); stream.Write(buffer5, 0, 4); } else { Type type2 = type.GetGenericArguments()[0]; Type type3 = type.GetGenericArguments()[1]; ICollection is2 = (ICollection)obj; buffer6 = ByteConverter.ToBytes <int>(is2.Count); stream.Write(buffer6, 0, 4); foreach (object obj2 in is2) { object property = ReflectionHelper.GetProperty(obj2, "Key"); object obj4 = ReflectionHelper.GetProperty(obj2, "Value"); this.DoSerialize(stream, type2, property); this.DoSerialize(stream, type3, obj4); } } } else { if (type.IsArray) { throw new Exception(string.Format("CompactSerializer don't support Type {0} ! ", type)); } this.DoSerializeComplicatedType(type, obj, stream); } } } } }
public static void Build(string filename) { nodenames.Clear(); modelfiles.Clear(); motionfiles.Clear(); byte[] fc; if (Path.GetExtension(filename).Equals(".prs", StringComparison.OrdinalIgnoreCase)) { fc = Prs.Decompress(filename); } else { fc = File.ReadAllBytes(filename); } string path = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(filename)), Path.GetFileNameWithoutExtension(filename)); JsonSerializer js = new JsonSerializer(); MiniEventIniData ini; using (TextReader tr = File.OpenText(Path.Combine(path, Path.ChangeExtension(Path.GetFileName(filename), ".json")))) using (JsonTextReader jtr = new JsonTextReader(tr)) ini = js.Deserialize <MiniEventIniData>(jtr); uint key; if (fc[4] == 0x81) { ByteConverter.BigEndian = true; key = 0x816DFE60; } else { ByteConverter.BigEndian = false; key = 0xCB00000; } List <byte> modelbytes = new List <byte>(fc); Dictionary <string, uint> labels = new Dictionary <string, uint>(); foreach (string file in ini.Files.Where(a => a.Key.EndsWith(".sa2mdl", StringComparison.OrdinalIgnoreCase) && HelperFunctions.FileHash(Path.Combine(path, a.Key)) != a.Value).Select(a => a.Key)) { modelbytes.AddRange(new ModelFile(Path.Combine(path, file)).Model.GetBytes((uint)(key + modelbytes.Count), false, labels, new List <uint>(), out uint _)); } foreach (string file in ini.Files.Where(a => a.Key.EndsWith(".saanim", StringComparison.OrdinalIgnoreCase) && HelperFunctions.FileHash(Path.Combine(path, a.Key)) != a.Value).Select(a => a.Key)) { modelbytes.AddRange(NJS_MOTION.Load(Path.Combine(path, file)).GetBytes((uint)(key + modelbytes.Count), labels, out uint _)); } fc = modelbytes.ToArray(); int ptr = fc.GetPointer(8, key); if (ptr != 0) { MiniEventChars info = ini.Sonic[0]; if (labels.ContainsKeySafer(info.BodyAnims)) { ByteConverter.GetBytes(labels[info.BodyAnims]).CopyTo(fc, ptr); } if (info.HeadPart != null) { if (labels.ContainsKeySafer(info.HeadPart)) { ByteConverter.GetBytes(labels[info.HeadPart]).CopyTo(fc, ptr + 4); } if (labels.ContainsKeySafer(info.HeadAnims)) { ByteConverter.GetBytes(labels[info.HeadAnims]).CopyTo(fc, ptr + 8); } if (labels.ContainsKeySafer(info.HeadShapeMotions)) { ByteConverter.GetBytes(labels[info.HeadShapeMotions]).CopyTo(fc, ptr + 0xC); } if (labels.ContainsKeySafer(info.MouthPart)) { ByteConverter.GetBytes(labels[info.MouthPart]).CopyTo(fc, ptr + 0x10); } if (labels.ContainsKeySafer(info.MouthAnims)) { ByteConverter.GetBytes(labels[info.MouthAnims]).CopyTo(fc, ptr + 0x14); } if (labels.ContainsKeySafer(info.MouthShapeMotions)) { ByteConverter.GetBytes(labels[info.MouthShapeMotions]).CopyTo(fc, ptr + 0x18); } if (labels.ContainsKeySafer(info.LHandPart)) { ByteConverter.GetBytes(labels[info.LHandPart]).CopyTo(fc, ptr + 0x1C); } if (labels.ContainsKeySafer(info.LHandAnims)) { ByteConverter.GetBytes(labels[info.LHandAnims]).CopyTo(fc, ptr + 0x20); } if (labels.ContainsKeySafer(info.LHandShapeMotions)) { ByteConverter.GetBytes(labels[info.LHandShapeMotions]).CopyTo(fc, ptr + 0x24); } if (labels.ContainsKeySafer(info.RHandPart)) { ByteConverter.GetBytes(labels[info.RHandPart]).CopyTo(fc, ptr + 0x28); } if (labels.ContainsKeySafer(info.RHandAnims)) { ByteConverter.GetBytes(labels[info.RHandAnims]).CopyTo(fc, ptr + 0x2C); } if (labels.ContainsKeySafer(info.RHandShapeMotions)) { ByteConverter.GetBytes(labels[info.RHandShapeMotions]).CopyTo(fc, ptr + 0x30); } } } ptr = fc.GetPointer(0xC, key); if (ptr != 0) { MiniEventChars info = ini.Shadow[0]; if (labels.ContainsKeySafer(info.BodyAnims)) { ByteConverter.GetBytes(labels[info.BodyAnims]).CopyTo(fc, ptr); } if (info.HeadPart != null) { if (labels.ContainsKeySafer(info.HeadPart)) { ByteConverter.GetBytes(labels[info.HeadPart]).CopyTo(fc, ptr + 4); } if (labels.ContainsKeySafer(info.HeadAnims)) { ByteConverter.GetBytes(labels[info.HeadAnims]).CopyTo(fc, ptr + 8); } if (labels.ContainsKeySafer(info.HeadShapeMotions)) { ByteConverter.GetBytes(labels[info.HeadShapeMotions]).CopyTo(fc, ptr + 0xC); } if (labels.ContainsKeySafer(info.MouthPart)) { ByteConverter.GetBytes(labels[info.MouthPart]).CopyTo(fc, ptr + 0x10); } if (labels.ContainsKeySafer(info.MouthAnims)) { ByteConverter.GetBytes(labels[info.MouthAnims]).CopyTo(fc, ptr + 0x14); } if (labels.ContainsKeySafer(info.MouthShapeMotions)) { ByteConverter.GetBytes(labels[info.MouthShapeMotions]).CopyTo(fc, ptr + 0x18); } if (labels.ContainsKeySafer(info.LHandPart)) { ByteConverter.GetBytes(labels[info.LHandPart]).CopyTo(fc, ptr + 0x1C); } if (labels.ContainsKeySafer(info.LHandAnims)) { ByteConverter.GetBytes(labels[info.LHandAnims]).CopyTo(fc, ptr + 0x20); } if (labels.ContainsKeySafer(info.LHandShapeMotions)) { ByteConverter.GetBytes(labels[info.LHandShapeMotions]).CopyTo(fc, ptr + 0x24); } if (labels.ContainsKeySafer(info.RHandPart)) { ByteConverter.GetBytes(labels[info.RHandPart]).CopyTo(fc, ptr + 0x28); } if (labels.ContainsKeySafer(info.RHandAnims)) { ByteConverter.GetBytes(labels[info.RHandAnims]).CopyTo(fc, ptr + 0x2C); } if (labels.ContainsKeySafer(info.RHandShapeMotions)) { ByteConverter.GetBytes(labels[info.RHandShapeMotions]).CopyTo(fc, ptr + 0x30); } } } ptr = fc.GetPointer(0x18, key); if (ptr != 0) { MiniEventChars info = ini.Knuckles[0]; if (labels.ContainsKeySafer(info.BodyAnims)) { ByteConverter.GetBytes(labels[info.BodyAnims]).CopyTo(fc, ptr); } if (info.HeadPart != null) { if (labels.ContainsKeySafer(info.HeadPart)) { ByteConverter.GetBytes(labels[info.HeadPart]).CopyTo(fc, ptr + 4); } if (labels.ContainsKeySafer(info.HeadAnims)) { ByteConverter.GetBytes(labels[info.HeadAnims]).CopyTo(fc, ptr + 8); } if (labels.ContainsKeySafer(info.HeadShapeMotions)) { ByteConverter.GetBytes(labels[info.HeadShapeMotions]).CopyTo(fc, ptr + 0xC); } if (labels.ContainsKeySafer(info.MouthPart)) { ByteConverter.GetBytes(labels[info.MouthPart]).CopyTo(fc, ptr + 0x10); } if (labels.ContainsKeySafer(info.MouthAnims)) { ByteConverter.GetBytes(labels[info.MouthAnims]).CopyTo(fc, ptr + 0x14); } if (labels.ContainsKeySafer(info.MouthShapeMotions)) { ByteConverter.GetBytes(labels[info.MouthShapeMotions]).CopyTo(fc, ptr + 0x18); } if (labels.ContainsKeySafer(info.LHandPart)) { ByteConverter.GetBytes(labels[info.LHandPart]).CopyTo(fc, ptr + 0x1C); } if (labels.ContainsKeySafer(info.LHandAnims)) { ByteConverter.GetBytes(labels[info.LHandAnims]).CopyTo(fc, ptr + 0x20); } if (labels.ContainsKeySafer(info.LHandShapeMotions)) { ByteConverter.GetBytes(labels[info.LHandShapeMotions]).CopyTo(fc, ptr + 0x24); } if (labels.ContainsKeySafer(info.RHandPart)) { ByteConverter.GetBytes(labels[info.RHandPart]).CopyTo(fc, ptr + 0x28); } if (labels.ContainsKeySafer(info.RHandAnims)) { ByteConverter.GetBytes(labels[info.RHandAnims]).CopyTo(fc, ptr + 0x2C); } if (labels.ContainsKeySafer(info.RHandShapeMotions)) { ByteConverter.GetBytes(labels[info.RHandShapeMotions]).CopyTo(fc, ptr + 0x30); } } } ptr = fc.GetPointer(0x1C, key); if (ptr != 0) { MiniEventChars info = ini.Rouge[0]; if (labels.ContainsKeySafer(info.BodyAnims)) { ByteConverter.GetBytes(labels[info.BodyAnims]).CopyTo(fc, ptr); } if (info.HeadPart != null) { if (labels.ContainsKeySafer(info.HeadPart)) { ByteConverter.GetBytes(labels[info.HeadPart]).CopyTo(fc, ptr + 4); } if (labels.ContainsKeySafer(info.HeadAnims)) { ByteConverter.GetBytes(labels[info.HeadAnims]).CopyTo(fc, ptr + 8); } if (labels.ContainsKeySafer(info.HeadShapeMotions)) { ByteConverter.GetBytes(labels[info.HeadShapeMotions]).CopyTo(fc, ptr + 0xC); } if (labels.ContainsKeySafer(info.MouthPart)) { ByteConverter.GetBytes(labels[info.MouthPart]).CopyTo(fc, ptr + 0x10); } if (labels.ContainsKeySafer(info.MouthAnims)) { ByteConverter.GetBytes(labels[info.MouthAnims]).CopyTo(fc, ptr + 0x14); } if (labels.ContainsKeySafer(info.MouthShapeMotions)) { ByteConverter.GetBytes(labels[info.MouthShapeMotions]).CopyTo(fc, ptr + 0x18); } if (labels.ContainsKeySafer(info.LHandPart)) { ByteConverter.GetBytes(labels[info.LHandPart]).CopyTo(fc, ptr + 0x1C); } if (labels.ContainsKeySafer(info.LHandAnims)) { ByteConverter.GetBytes(labels[info.LHandAnims]).CopyTo(fc, ptr + 0x20); } if (labels.ContainsKeySafer(info.LHandShapeMotions)) { ByteConverter.GetBytes(labels[info.LHandShapeMotions]).CopyTo(fc, ptr + 0x24); } if (labels.ContainsKeySafer(info.RHandPart)) { ByteConverter.GetBytes(labels[info.RHandPart]).CopyTo(fc, ptr + 0x28); } if (labels.ContainsKeySafer(info.RHandAnims)) { ByteConverter.GetBytes(labels[info.RHandAnims]).CopyTo(fc, ptr + 0x2C); } if (labels.ContainsKeySafer(info.RHandShapeMotions)) { ByteConverter.GetBytes(labels[info.RHandShapeMotions]).CopyTo(fc, ptr + 0x30); } } } ptr = fc.GetPointer(0x24, key); if (ptr != 0 && labels.ContainsKeySafer(ini.MechEggmanBodyAnims)) { ByteConverter.GetBytes(labels[ini.MechEggmanBodyAnims]).CopyTo(fc, ptr); } ptr = fc.GetPointer(4, key); if (ptr != 0 && labels.ContainsKeySafer(ini.Camera)) { ByteConverter.GetBytes(labels[ini.Camera]).CopyTo(fc, 4); //ByteConverter.GetBytes(ini.CamFrames).CopyTo(fc, ptr + 4); ByteConverter.GetBytes(labels[ini.Camera]).CopyTo(fc, ptr + 0x10); } if (Path.GetExtension(filename).Equals(".prs", StringComparison.OrdinalIgnoreCase)) { Prs.Compress(fc, filename); } else { File.WriteAllBytes(filename, fc); } }
static void Main(string[] args) { string dir = Environment.CurrentDirectory; try { Queue <string> argq = new Queue <string>(args); bool? be = null; if (argq.Count > 0) { if (argq.Peek().Equals("/be", StringComparison.OrdinalIgnoreCase)) { be = true; argq.Dequeue(); } else if (argq.Peek().Equals("/le", StringComparison.OrdinalIgnoreCase)) { be = false; argq.Dequeue(); } } string mdlfilename; if (argq.Count > 0) { mdlfilename = argq.Dequeue(); Console.WriteLine("File: {0}", mdlfilename); } else { Console.Write("File: "); mdlfilename = Console.ReadLine().Trim('"'); } mdlfilename = Path.GetFullPath(mdlfilename); if (Directory.Exists(mdlfilename)) { mdlfilename += ".prs"; } Environment.CurrentDirectory = Path.GetDirectoryName(mdlfilename); SortedDictionary <int, NJS_OBJECT> models = new SortedDictionary <int, NJS_OBJECT>(); foreach (string file in Directory.GetFiles(Path.GetFileNameWithoutExtension(mdlfilename), "*.sa2mdl")) { if (int.TryParse(Path.GetFileNameWithoutExtension(file), NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out int i)) { models.Add(i, new ModelFile(file).Model); } } MDLInfo mdlinfo = IniSerializer.Deserialize <MDLInfo>( Path.Combine(Path.GetFileNameWithoutExtension(mdlfilename), Path.GetFileNameWithoutExtension(mdlfilename) + ".ini")); if (!be.HasValue) { ByteConverter.BigEndian = mdlinfo.BigEndian; } else { ByteConverter.BigEndian = be.Value; } List <byte> mdlfile = new List <byte>(); List <byte> modelbytes = new List <byte>(); Dictionary <string, uint> labels = new Dictionary <string, uint>(); uint imageBase = (uint)(mdlinfo.Indexes.Count * 8) + 8; foreach (KeyValuePair <int, NJS_OBJECT> item in models) { byte[] tmp = item.Value.GetBytes(imageBase, false, labels, out uint address); modelbytes.AddRange(tmp); imageBase += (uint)tmp.Length; } foreach (KeyValuePair <int, string> item in mdlinfo.Indexes) { mdlfile.AddRange(ByteConverter.GetBytes(item.Key)); mdlfile.AddRange(ByteConverter.GetBytes(labels[item.Value])); } mdlfile.AddRange(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0 }); mdlfile.AddRange(modelbytes); if (Path.GetExtension(mdlfilename).Equals(".prs", StringComparison.OrdinalIgnoreCase)) { FraGag.Compression.Prs.Compress(mdlfile.ToArray(), mdlfilename); } else { File.WriteAllBytes(mdlfilename, mdlfile.ToArray()); } } finally { Environment.CurrentDirectory = dir; } }
public ItemActionInfo ReadItemAction(byte[] data) { var i = new ItemActionInfo(); i.action = (ItemActionType)data[1]; var category = (ItemCategory)data[3]; i.uid = BitConverter.ToUInt32(data, 4); var pOffset = data[0] == 0x9D ? 13 : 8; i.flags = (ItemFlag)BitConverter.ToUInt32(data, pOffset); var version = data[pOffset += 4]; ++pOffset; //Log("Uid {0} action {1}", i.uid, i.action); if (i.action != ItemActionType.AddToGround && i.action != ItemActionType.DropToGround && i.action != ItemActionType.OnGround) { return(null); } i.x = BitConverter.ToUInt16(data, pOffset); i.y = BitConverter.ToUInt16(data, pOffset += 2); i.x = (i.x + 131072) / 32; i.y = (i.y + 131072) / 32; pOffset += 2; //TODO: Unknown bit //pOffset = pOffset * 8 + 1; pOffset = pOffset * 8 - 32 + 5; i.x = ByteConverter.GetBits(data, ref pOffset, 16); i.y = ByteConverter.GetBits(data, ref pOffset, 16); //var tmp = ByteConverter.GetBits(data, ref pOffset, 4); var container = ItemContainer.Ground; if (i.flags.HasFlag(ItemFlag.Ear)) { return(null); /*var charClass = ByteConverter.GetBits(data, ref pOffset, 3); * var level = (ushort)ByteConverter.GetBits(data, ref pOffset, 7); * var builder = new System.Text.StringBuilder(); * int mChar; * while ((mChar = ByteConverter.GetBits(data, ref pOffset, 7)) != 0) * builder.Append((char)mChar); * var name = builder.ToString(); * return i;*/ } i.code = String.Concat( (char)ByteConverter.GetBits(data, ref pOffset, 8), (char)ByteConverter.GetBits(data, ref pOffset, 8), (char)ByteConverter.GetBits(data, ref pOffset, 8)); pOffset += 4; if (i.code == "gld") { pOffset += 4; if (ByteConverter.GetBits(data, ref pOffset, 1) == 1) { i.goldCount = ByteConverter.GetBits(data, ref pOffset, 20); } else { i.goldCount = ByteConverter.GetBits(data, ref pOffset, 18); } return(i); } var location = EquipmentLocation.NotApplicable; // Buffer to container mapping (sanitize NPC tabs IDs and coords, changed belt location to X, Y, etc.) if (i.flags.HasFlag(ItemFlag.InStore) || // Flag is not always set for shop items !?! i.action == ItemActionType.AddToShop || i.action == ItemActionType.RemoveFromShop) { int buff = (int)container | 0x80; if (i.y < 2 && (buff == 0x83 || buff == 0x85 || buff == 0x89)) { buff -= 1; i.y += 8; } container = (ItemContainer)buff; } else if (container == ItemContainer.Equipment) { if (location == EquipmentLocation.NotApplicable) { if ((i.flags & ItemFlag.InSocket) != 0) { container = ItemContainer.Item; } else { container = ItemContainer.Belt; i.y = i.x / 4; i.x = i.x % 4; } } else { // Hides them in dump... not needed anyway i.y = -1; i.x = -1; } } // TODO: I don't know what this is (always 2 ??) var unknown1 = (byte)ByteConverter.GetBits(data, ref pOffset, 4); // Used Sockets : 3 byte usedSockets = 0; if (i.flags.HasFlag(ItemFlag.Socketed)) { usedSockets = (byte)ByteConverter.GetBits(data, pOffset, 3); } pOffset += 3; // Ends here if Simple or Gamble Item if ((i.flags & ItemFlag.SimpleItem) != 0 || (i.flags & ItemFlag.Gamble) != 0) { return(i); } // ILevel : 7 i.iLvl = (byte)ByteConverter.GetBits(data, ref pOffset, 7); // Quality : 4 i.quality = (ItemQuality)ByteConverter.GetBits(data, ref pOffset, 4); // Graphic : 1 : 3 if (ByteConverter.GetBits(data, ref pOffset, 1) == 1) { ByteConverter.GetBits(data, ref pOffset, 3); } //TODO: ClassInfo : 1 : 11 if (ByteConverter.GetBits(data, ref pOffset, 1) == 1) { ByteConverter.GetBits(data, ref pOffset, 11); } // Quality information if (i.flags.HasFlag(ItemFlag.Identified)) { switch (i.quality) { case ItemQuality.Inferior: /*this.prefix = new ItemAffix(ItemAffixType.InferiorPrefix, * ByteConverter.GetBits(data, ref pOffset, 3));*/ ByteConverter.GetBits(data, ref pOffset, 3); break; case ItemQuality.Superior: //this.prefix = new ItemAffix(ItemAffixType.SuperiorPrefix, 0); //TODO: quality type // 00 = AR // 01 = Max Dmg // 02 = AC // 03 = AR + Max Dmg // 04 = Durability // 05 = Durability + AR // 06 = Durability + Max Dmg // 07 = Durability + AC pOffset += 3; break; case ItemQuality.Magic: /*this.prefix = new ItemAffix(ItemAffixType.MagicPrefix, * ByteConverter.GetBits(data, ref pOffset, 11)); * this.suffix = new ItemAffix(ItemAffixType.MagicSuffix, * ByteConverter.GetBits(data, ref pOffset, 11));*/ ByteConverter.GetBits(data, ref pOffset, 11); ByteConverter.GetBits(data, ref pOffset, 11); break; case ItemQuality.Rare: case ItemQuality.Craft: /*this.prefix = new ItemAffix(ItemAffixType.RarePrefix, * ByteConverter.GetBits(data, ref pOffset, 8)); * this.suffix = new ItemAffix(ItemAffixType.RareSuffix, * ByteConverter.GetBits(data, ref pOffset, 8));*/ ByteConverter.GetBits(data, ref pOffset, 8); ByteConverter.GetBits(data, ref pOffset, 8); for (int j = 0; j < 3; ++j) { if (ByteConverter.GetBits(data, ref pOffset, 1) == 1) { ByteConverter.GetBits(data, ref pOffset, 11); } //this.magicPrefixes[i] = new ItemAffix(ItemAffixType.MagicPrefix, //ByteConverter.GetBits(data, ref pOffset, 11)); if (ByteConverter.GetBits(data, ref pOffset, 1) == 1) { ByteConverter.GetBits(data, ref pOffset, 11); } //this.magicSuffixes[i] = new ItemAffix(ItemAffixType.MagicSuffix, //ByteConverter.GetBits(data, ref pOffset, 11)); } break; case ItemQuality.Set: //this.setItem = BaseSetItem.Get(ByteConverter.GetBits(data, ref pOffset, 12)); ByteConverter.GetBits(data, ref pOffset, 12); break; case ItemQuality.Unique: if (i.code != "std") // TODO: add UniqueItem entry to parse mod (req lvl 90) { ByteConverter.GetBits(data, ref pOffset, 12); } //this.uniqueItem = BaseUniqueItem.Get(ByteConverter.GetBits(data, ref pOffset, 12)); break; } } // Personalized Name : 7 * (NULLSTRING Length) if (i.flags.HasFlag(ItemFlag.Personalized)) { System.Text.StringBuilder builder = new System.Text.StringBuilder(); int mChar; while ((mChar = ByteConverter.GetBits(data, ref pOffset, 7)) != 0) { builder.Append((char)mChar); } var personalizedName = builder.ToString(); } // Runeword Info : 16 if (i.flags.HasFlag(ItemFlag.Runeword)) { //HACK: this is probably wrong, but works for all the runewords I tested so far... //TODO: Need to test cases where runewordUnknown != 5 and where ID is around 100 //TODO: remove these fields once testing is done var runewordID = ByteConverter.GetBits(data, ref pOffset, 12); var runewordUnknown = ByteConverter.GetBits(data, ref pOffset, 4); } var itemInfo = ItemStorage.GetInfo(i.code); if (itemInfo == null) { return(null); } if (itemInfo.BodyLocation == ItemBodyLocation.Armor && itemInfo.ArmorType != ItemArmorType.Amulet && itemInfo.ArmorType != ItemArmorType.Ring) { var defense = ByteConverter.GetBits(data, ref pOffset, 11) - 10; } var maxDurability = 0; var currentDurability = 0; if (itemInfo.BodyLocation == ItemBodyLocation.Armor && itemInfo.ArmorType != ItemArmorType.Amulet && itemInfo.ArmorType != ItemArmorType.Ring || itemInfo.BodyLocation == ItemBodyLocation.Weapon) { maxDurability = ByteConverter.GetBits(data, ref pOffset, 8); // 0 durability means indestructible, but only found on old items (having the "zod bug"...) if (maxDurability > 0) { currentDurability = ByteConverter.GetBits(data, ref pOffset, 8); //TODO: unknown. Indestructible bit ?? ByteConverter.GetBits(data, ref pOffset, 1); } } // Total Sockets : 4 if (i.flags.HasFlag(ItemFlag.Socketed)) { i.sockets = ByteConverter.GetBits(data, ref pOffset, 4); } return(i); }