public void StartSave( string path ) { path += Name()+"/"; if( !Directory.Exists( path ) ) Directory.CreateDirectory( path ); try { GenericWriter idx = new BinaryFileWriter( path+Name()+".idx", false ); GenericWriter tdb = new BinaryFileWriter( path+Name()+".tdb", false ); GenericWriter bin = new BinaryFileWriter( path+Name()+".bin", true ); Console.Write( " - Saving {0}...", Name() ); Save( idx, tdb, bin ); idx.Close(); tdb.Close(); bin.Close(); Console.WriteLine( "Done." ); } catch( Exception err ) { Console.WriteLine( "Failed. Exception: "+err ); } }
public void Serialize(BinaryFileWriter writer) { writer.Write((uint)PtrFile); writer.Write((uint)FileSize); writer.Write((uint)FileSizeCompressed); writer.Write((uint)Flags); }
public void Serialize(BinaryFileWriter writer) { writer.Write((uint)InterXLib.Library.FourCharsToUInt("LPK2")); writer.Write((uint)Hashcount); writer.Write((uint)BlockCount); writer.Write((uint)PtrHashTable); writer.Write((uint)PtrBlocks); writer.Write((uint)PtrFiles); writer.Write((uint)HashTableSizeCompressed); writer.Write((uint)BlockTableSizeCompressed); }
protected RecordGroup ReadTES3(Header header, bool loadAll, StreamSink.DataInfo info) { using (var ms = new MemoryStream()) using (var w = new BinaryFileWriter(ms)) { header.Write(w, Format); ms.Position = 0; var headerBytes = ms.ToArray(); info?.AddGroup(header.Label, headerBytes); } //var group = new RecordGroup(_streamSink, _r, FilePath, Format, RecordLevel, Depth + 1); AddHeader(header, info); if (loadAll || info != null) { Load(loadAll, info); } ReadTES3Transform(this, info); return(this); }
private static void Serialize(BinaryFileWriter writer) { writer.Write((int)0); //Version if (m_CombatProfiles != null) { writer.Write((int)m_CombatProfiles.Count); } else { writer.Write((int)0); } foreach (CombatantProfile p in m_CombatProfiles) { p.Serialize(writer); } }
static void Main(string[] args) { BinaryFileWriter.WritePrimitiveValues(); BinaryImageManipulator.ReadFileIn(); //string appdatapath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); //Console.WriteLine(appdatapath); //Dictionary<string, string> hometowns = new Dictionary<string, string>() //{ // {"Josh", "Brunswick" }, // {"Craig", "Bainbridge" }, // {"JohnK", "Euclid" } //}; //SaveDictionaryToFile(hometowns); }
public static void OnSave(WorldSaveEventArgs e) { if (!Directory.Exists(SAVE_PATH)) { Directory.CreateDirectory(SAVE_PATH); } GenericWriter writer = new BinaryFileWriter(Path.Combine(SAVE_PATH, FILENAME), true); writer.Write(0); writer.Write(GameData.Count); foreach (BoardGameData data in GameData) { data.Serialize(writer); } writer.Close(); }
public static void SaveMsgs() { if (!Directory.Exists(General.SavePath)) { Directory.CreateDirectory(General.SavePath); } GenericWriter writer = new BinaryFileWriter(Path.Combine(General.SavePath, "Pms.bin"), true); writer.Write(0); // version writer.Write(s_Datas.Count); foreach (Data data in s_Datas.Values) { writer.Write(data.Mobile); data.SaveMsgs(writer); } writer.Close(); }
public static bool SubWrite(GenericWriter writer, Action <GenericWriter> serializer) { if (writer == null) { return(false); } using (MemoryStream s = new MemoryStream()) { BinaryFileWriter w = new BinaryFileWriter(s, true); try { serializer(w); } catch (Exception e) { Console.WriteLine("Quest Save Failure: {0}", Utility.FormatDelegate(serializer)); Server.Diagnostics.ExceptionLogging.LogException(e); writer.Write(0L); return(false); } finally { w.Flush(); } writer.Write(s.Length); s.Position = 0; while (s.Position < s.Length) { writer.Write((byte)s.ReadByte()); } } return(true); }
private static void Event_WorldSave(WorldSaveEventArgs args) { try { if (!Directory.Exists(SavePath)) { Directory.CreateDirectory(SavePath); } BinaryFileWriter writer = new BinaryFileWriter(SaveFile, true); Serialize(writer); writer.Close(); } catch (ArgumentException e) { eqUtility.HandleGenericException(e); } }
protected void SaveItems() { var items = World.m_Items; GenericWriter idx = new BinaryFileWriter(World.ItemIndexPath, false); GenericWriter tdb = new BinaryFileWriter(World.ItemTypesPath, false); GenericWriter bin = new BinaryFileWriter(World.ItemDataPath, true); idx.Write(items.Count); foreach (var item in items.Values) { if (item.Decays && item.Parent == null && item.Map != Map.Internal && (item.LastMoved + item.DecayTime) <= DateTime.UtcNow) { m_DecayQueue.Enqueue(item); } var start = bin.Position; idx.Write(item.m_TypeRef); idx.Write(item.Serial); idx.Write(start); item.Serialize(bin); idx.Write((int)(bin.Position - start)); item.FreeCache(); } tdb.Write(World.m_ItemTypes.Count); for (var i = 0; i < World.m_ItemTypes.Count; ++i) { tdb.Write(World.m_ItemTypes[i].FullName); } idx.Close(); tdb.Close(); bin.Close(); }
private static void ExportSectorNodeNetwork(CommandEventArgs e) { try { Console.Write("Saving SectorNodes..."); DateTime dt = DateTime.Now; if (!Directory.Exists("Data")) { Directory.CreateDirectory("Data"); } using (FileStream fs = new FileStream("Data/SectorPathData.dat", FileMode.Create)) { BinaryFileWriter writer = new BinaryFileWriter(fs, false); writer.Write(Map.Felucca.Width >> Map.SectorShift); writer.Write(Map.Felucca.Height >> Map.SectorShift); for (int y = 0; y < (Map.Felucca.Height >> Map.SectorShift); y++) { for (int x = 0; x < (Map.Felucca.Width >> Map.SectorShift); x++) { m_Nodes[x, y].Serialize(writer); } } writer.Close(); } Console.WriteLine("done in {0}ms.", (DateTime.Now - dt).TotalMilliseconds); } catch (Exception ex) { LogHelper.LogException(ex); Console.WriteLine("error:"); Console.WriteLine(ex); } }
private static void EventSink_WorldSave(WorldSaveEventArgs e) { if (!Directory.Exists(Path.Combine(Core.BaseDirectory, "Saves\\BugTracker"))) { Directory.CreateDirectory(Path.Combine(Core.BaseDirectory, "Saves\\BugTracker")); } GenericWriter writer = new BinaryFileWriter(new FileStream(Path.Combine(Core.BaseDirectory, "Saves\\BugTracker\\bugs.bin"), FileMode.OpenOrCreate), true); List <int> toDelete = new List <int>(); for (int i = 0; i < _GlobalList.Count; i++) { if (_GlobalList[i].Status == BugStatus.Closed) { toDelete.Add(i); } } for (int i = 0; i < toDelete.Count; i++) { _GlobalList.RemoveAt(toDelete[i]); } writer.Write((int)0); int count = _GlobalList.Count; writer.Write((int)count); for (int i = 0; i < count; i++) { _GlobalList[i].Serilize(writer); } writer.Close(); }
public void Serialize(BinaryFileWriter writer) { m_Tilegfx.Consolidate(m_Metatiles); writer.Write(c_SerializeIdentifier); writer.Write((int)0); // version writer.Write(m_PaletteZero); for (int i = 0; i < 4; i++) { writer.Write(m_Palettes[i]); } for (int i = 0; i < 3; i++) { writer.Write((byte)0); } writer.Write((int)m_Tilegfx.CurrentIndex); writer.Write((int)m_Tilegfx.Count); for (int i = 0; i < m_Tilegfx.Count; i++) { TilePage value = m_Tilegfx[i]; writer.Write((int)i); writer.Write((byte)value.Tile); writer.Write((byte)value.Page); } for (int i = 0; i < TilesPerSet; i++) { for (int j = 0; j < 4; j++) { writer.Write((int)m_Metatiles[i][j]); } writer.Write((byte)m_Bitfields[i]); writer.Write((byte)m_Attributes[i]); } }
public void ReadStringUntilTest() { File file = new File(System.IO.Path.Combine(TestDirectory, "Test1")); try { BinaryFileWriter target = new BinaryFileWriter(file); string actual = "abcdefghijk;"; char ch = ';'; byte terminator = (byte)ch; int maximumLength = actual.Length; //target.writer.Write(actual); target.WriteString(actual); target.Close(); BinaryFileReader r = new BinaryFileReader(file); string expected = r.ReadStringUntil(terminator, maximumLength, true); r.Close(); Assert.AreEqual(expected, actual, "Should be equal"); } catch (Exception e) { Assert.Fail(e.ToString()); } }
public void BinaryFileWriterConstructorTest() { File file = new File(System.IO.Path.Combine(TestDirectory, "Test1.Txt")); try { BinaryFileWriter target = new BinaryFileWriter(file, Encoding.UTF32); byte b = 10; target.WriteByte(b); target.Close(); BinaryFileReader r = new BinaryFileReader(file); byte c = r.ReadByte(); Assert.AreEqual(b, c, "Should be equal"); } catch (Exception e) { Assert.Fail(e.ToString()); } }
public static void Save() { if (!Directory.Exists("Saves/CTFScore/")) { Directory.CreateDirectory("Saves/CTFScore/"); } string idxPath = Path.Combine("Saves/CTFScore", "CTFScore.idx"); string binPath = Path.Combine("Saves/CTFScore", "CTFScore.bin"); GenericWriter idx = new BinaryFileWriter(idxPath, false); GenericWriter bin = new BinaryFileWriter(binPath, true); idx.Write((int)Players.Values.Count); foreach (CTFPlayer player in Players.Values) { long startPos = bin.Position; player.Serialize(bin); idx.Write((long)startPos); idx.Write((int)(bin.Position - startPos)); } idx.Close(); bin.Close(); }
private static void OnSave(WorldSaveEventArgs args) { if (!Directory.Exists(SavePath)) { Directory.CreateDirectory(SavePath); } GenericWriter writer = new BinaryFileWriter(Path.Combine(SavePath, SaveFile), true); writer.Write(m_LastResetTime); writer.Write(MobileRateInfo.Entries.Count); foreach (KeyValuePair <Mobile, MobileRateInfo> kvp in MobileRateInfo.Entries) { writer.Write((Mobile)kvp.Key); MobileRateInfo info = (MobileRateInfo)kvp.Value; info.Serialize(writer); } writer.Close(); }
public static void SaveFights() { GenericWriter idx = new BinaryFileWriter(fightIdxPath, false); GenericWriter bin = new BinaryFileWriter(fightBinPath, true); idx.Write((int)fights.Count); foreach (Fight f in fights) { long startPos = bin.Position; f.Serialize(bin); idx.Write((long)startPos); idx.Write((int)(bin.Position - startPos)); } idx.Close(); bin.Close(); }
public void SavePlugin(BinaryFileWriter writer) { writer.Write(SkillReportsHelper.EnableProfileReport); writer.Write(SkillReportsHelper.EnableSelectionReport); }
public static void SaveArenas() { GenericWriter bin = new BinaryFileWriter(arenaBinPath, true); bin.WriteItemList(arenas, true); bin.Close(); }
public static void Save() { Console.Write("DonatorAccountSettings: Saving..."); if (!Directory.Exists("Saves/Donation/")) Directory.CreateDirectory("Saves/Donation/"); string idxPath = Path.Combine( "Saves/Donation", "DonatorAccountSettings.idx" ); string binPath = Path.Combine( "Saves/Donation", "DonatorAccountSettings.bin" ); GenericWriter idx = new BinaryFileWriter(idxPath, false); GenericWriter bin = new BinaryFileWriter(binPath, true); idx.Write( (int)DonatorAccountSettingsTable.Values.Count ); foreach ( DonatorAccountSettings das in DonatorAccountSettingsTable.Values ) { long startPos = bin.Position; das.Serialize( bin ); idx.Write( (long)startPos ); idx.Write( (int)(bin.Position - startPos) ); } idx.Close(); bin.Close(); Console.WriteLine("done"); }
/// <summary> /// Writes the model to a DMT file. /// </summary> /// <param name="model">The DMTModel to write.</param> /// <param name="file">The file to write to.</param> public void WriteFile(DMTModel model, File file) { BinaryFileWriter binaryWriter = null; try { // If there are no blocks then return if (model.TriangleBlocks.Count == 0) { throw new DMTFileException(DMTFileError.NoTriangleBlocks); } // If there are no vertices then return if (model.TotalNoOfVertices == 0) { throw new DMTFileException(DMTFileError.NoVertices); } // If there are no triangles then return if (model.TotalNoOfTriangles == 0) { throw new DMTFileException(DMTFileError.NoTriangles); } // Delete the file file.Delete(); // Create the writer binaryWriter = new BinaryFileWriter(file); // Write the header string header = null; header = "DMT Triangles saved by Automation Interface v" + Assembly.GetExecutingAssembly().GetName().Version + " in MM " + DateTime.Now.ToShortDateString(); if (header.Length > 255) { header = header.Substring(0, 255); } header += Strings.Chr(0); binaryWriter.WriteString(header); // Write version ushort version = 1000; binaryWriter.WriteUShort(version); // Write file flags (Bit 1 = 0 (doubles), Bit 2 = 1 (MMs)) uint fileFlags = 2; binaryWriter.WriteUInteger(fileFlags); // Write total block count uint totalNoOfBlocks = 0; totalNoOfBlocks = (uint)model.TriangleBlocks.Count; binaryWriter.WriteUInteger(totalNoOfBlocks); // Write total vertex count uint totalNoOfTriangleVertices = 0; totalNoOfTriangleVertices = model.TotalNoOfVertices; binaryWriter.WriteUInteger(totalNoOfTriangleVertices); // Write total triangle count uint totalNoOfTriangles = 0; var triangleIndex = 0; Vector normal = null; totalNoOfTriangles = model.TotalNoOfTriangles; binaryWriter.WriteUInteger(totalNoOfTriangles); foreach (var block in model.TriangleBlocks) { binaryWriter.WriteUInteger(block.Flags); binaryWriter.WriteUInteger((uint)block.NoOfVertices); binaryWriter.WriteUInteger((uint)block.NoOfTriangles); for (var vertexNo = 0; vertexNo <= block.TriangleVertices.Count - 1; vertexNo++) { binaryWriter.WriteDouble(block.TriangleVertices.ElementAt(vertexNo).X); binaryWriter.WriteDouble(block.TriangleVertices.ElementAt(vertexNo).Y); binaryWriter.WriteDouble(block.TriangleVertices.ElementAt(vertexNo).Z); if (block.DoVerticesHaveNormals) { binaryWriter.WriteDouble(block.VertexNormals.ElementAt(vertexNo).I.Value); binaryWriter.WriteDouble(block.VertexNormals.ElementAt(vertexNo).J.Value); binaryWriter.WriteDouble(block.VertexNormals.ElementAt(vertexNo).K.Value); } } var use32bitPointers = false; use32bitPointers = block.TriangleVertices.Count > ushort.MaxValue; for (var triangleNo = 0; triangleNo <= block.NoOfTriangles - 1; triangleNo++) { if (use32bitPointers) { binaryWriter.WriteInteger(block.TriangleFirstVertexIndices.ElementAt(triangleNo)); binaryWriter.WriteInteger(block.TriangleSecondVertexIndices.ElementAt(triangleNo)); binaryWriter.WriteInteger(block.TriangleThirdVertexIndices.ElementAt(triangleNo)); } else { binaryWriter.WriteUShort((ushort)block.TriangleFirstVertexIndices.ElementAt(triangleNo)); binaryWriter.WriteUShort((ushort)block.TriangleSecondVertexIndices.ElementAt(triangleNo)); binaryWriter.WriteUShort((ushort)block.TriangleThirdVertexIndices.ElementAt(triangleNo)); } } binaryWriter.WriteUShort(version); } // All done, close the writer binaryWriter.Close(); } finally { if (binaryWriter != null) { binaryWriter.Close(); } } }
public static void OnSave(WorldSaveEventArgs e) { if (!Directory.Exists(UltimaLiveSettings.LumberHarvestFallenTreeSaveLocation)) { Directory.CreateDirectory(UltimaLiveSettings.LumberHarvestFallenTreeSaveLocation); } bool updateRegrowthTime = false; //foreach map in the lookup table foreach (Map m in Map.AllMaps) { if (RegrowthMasterLookupTable.ContainsKey(m.MapID)) { #region Regrowth if (DateTime.Now > LastGrowth + TimeBetweenRegrowth) { updateRegrowthTime = true; Dictionary <Point3D, int> mapLookupTable = RegrowthMasterLookupTable[m.MapID]; MapOperationSeries mapOperations = null; List <Point3D> locationsToRemove = new List <Point3D>(); //for each tree location in the lookup table foreach (KeyValuePair <Point3D, int> treeLocationKvp in mapLookupTable) { if (BaseHarvestablePhase.MasterHarvestablePhaseLookupByItemIdList.ContainsKey(treeLocationKvp.Value)) { //look up the current phase bool existingTileFound = false; foreach (StaticTile tile in m.Tiles.GetStaticTiles(treeLocationKvp.Key.X, treeLocationKvp.Key.Y)) { if (tile.Z == treeLocationKvp.Key.Z) // if the z altitude matches { if (BaseHarvestablePhase.MasterHarvestablePhaseLookupByItemIdList.ContainsKey(tile.ID)) //if the item id is linked to a phase { BaseHarvestablePhase currentPhase = BaseHarvestablePhase.MasterHarvestablePhaseLookupByItemIdList[tile.ID]; foreach (GraphicAsset[] assetSet in currentPhase.BaseAssetSets) { if (assetSet.Length > 0 && assetSet[0].ItemID == tile.ID) { existingTileFound = true; } } if (existingTileFound && !currentPhase.grow(treeLocationKvp.Key, m, ref mapOperations)) { locationsToRemove.Add(treeLocationKvp.Key); } break; } } } //nothing to grow at this location, so construct the starting phase if (!existingTileFound) { //lookup original phase that was saved BaseHarvestablePhase grownPhase = BaseHarvestablePhase.MasterHarvestablePhaseLookupByItemIdList[treeLocationKvp.Value]; //cleanup final harvest graphics if (grownPhase.FinalHarvestPhase != null && BaseHarvestablePhase.MasterHarvestablePhaseLookupByTypeList.ContainsKey(grownPhase.FinalHarvestPhase)) { BaseHarvestablePhase.MasterHarvestablePhaseLookupByTypeList[grownPhase.FinalHarvestPhase].Teardown(treeLocationKvp.Key, m, ref mapOperations); } if (grownPhase.StartingGrowthPhase != null && BaseHarvestablePhase.MasterHarvestablePhaseLookupByTypeList.ContainsKey(grownPhase.StartingGrowthPhase)) { //remove stump BaseTreeHarvestPhase maturePhase = grownPhase as BaseTreeHarvestPhase; if (maturePhase != null) { if (mapOperations != null) { mapOperations.Add(new DeleteStatic(m.MapID, new StaticTarget(treeLocationKvp.Key, maturePhase.StumpGraphic))); } else { mapOperations = new MapOperationSeries(new DeleteStatic(m.MapID, new StaticTarget(treeLocationKvp.Key, maturePhase.StumpGraphic)), m.MapID); } } BaseHarvestablePhase.MasterHarvestablePhaseLookupByTypeList[grownPhase.StartingGrowthPhase].Construct(treeLocationKvp.Key, m, ref mapOperations); } } } } if (mapOperations != null) { mapOperations.DoOperation(); } foreach (Point3D p in locationsToRemove) { RegrowthMasterLookupTable[m.MapID].Remove(p); } } #endregion GenericWriter writer = new BinaryFileWriter(Path.Combine(UltimaLiveSettings.LumberHarvestFallenTreeSaveLocation, "TreeLocations." + m.MapID), true); foreach (KeyValuePair <Point3D, int> kvp in RegrowthMasterLookupTable[m.MapID]) { writer.Write(kvp.Key); writer.Write(kvp.Value); } writer.Close(); } } if (updateRegrowthTime) { LastGrowth = DateTime.Now; } }
private static void OnSave(WorldSaveEventArgs e) { try{ if (!Directory.Exists("Saves/Chat/")) { Directory.CreateDirectory("Saves/Chat/"); } GenericWriter writer = new BinaryFileWriter(Path.Combine("Saves/Chat/", "Chat.bin"), true); writer.Write(12); // version // Version 12 writer.Write(s_PublicPlusIRC); // Version 11 writer.Write((int)s_FilterPenalty); // Version 10 writer.Write(s_AllianceChat); // Version 9 writer.Write(s_AllowFaction); // Version 8 writer.Write(s_GuildMenuAccess); // Version 7 writer.Write(s_MaxPmHistory); // version 6 writer.Write(s_IrcAutoConnect); // Version 5 writer.Write(s_IrcMaxAttempts); // Version 4 writer.Write(s_IrcAutoConnect); // Version 3 writer.Write((int)s_IrcStaffColor); // Version 2 writer.Write(s_IrcNick); // Version 1 writer.Write(s_IrcEnabled); writer.Write(s_IrcServer); writer.Write(s_IrcRoom); writer.Write(s_IrcPort); // Version 0 writer.Write(s_Filters.Count); foreach (string str in s_Filters) { writer.Write(str); } writer.Write(s_SpamLimiter); writer.Write(s_FilterBanLength); writer.Write(s_ShowLocation); writer.Write(s_ShowStaff); writer.Write((int)s_PublicStyle); ArrayList list = new ArrayList(); foreach (ChatInfo info in s_ChatInfos.Values) { if (info.Mobile != null && info.Mobile.Player && !info.Mobile.Deleted && info.Mobile.Account != null && ((Account)info.Mobile.Account).LastLogin > DateTime.Now - TimeSpan.FromDays(30)) { list.Add(info); } } writer.Write(list.Count); foreach (ChatInfo info in new ArrayList(list)) { writer.Write(info.Mobile); if (!info.Save(writer)) { return; } } writer.Close(); }catch { Errors.Report("ChatInfo-> OnSave"); } }
public static void OnSave(WorldSaveEventArgs e) { if (!Directory.Exists(UltimaLiveSettings.UltimaLiveMapChangesSavePath)) { Directory.CreateDirectory(UltimaLiveSettings.UltimaLiveMapChangesSavePath); } DateTime now = DateTime.Now; string Stamp = string.Format("{0}-{1}-{2}-{3}-{4}-{5}", now.Year, now.Month.ToString("00"), now.Day.ToString("00"), now.Hour.ToString("00"), now.Minute.ToString("00"), now.Second.ToString("00")); foreach (KeyValuePair <int, MapRegistry.MapDefinition> kvp in MapRegistry.Definitions) //for (int mapIndex = 0; mapIndex < Live.NumberOfMapFiles; mapIndex++) { try { Map CurrentMap = Server.Map.Maps[kvp.Key]; TileMatrix CurrentMatrix = CurrentMap.Tiles; ICollection keyColl = m_LandChanges[kvp.Key].Keys; if (keyColl.Count > 0) { string filename = string.Format("map{0}-{1}.live", kvp.Key, Stamp); Console.WriteLine(Path.Combine(UltimaLiveSettings.UltimaLiveMapChangesSavePath, filename)); GenericWriter writer = new BinaryFileWriter(Path.Combine(UltimaLiveSettings.UltimaLiveMapChangesSavePath, filename), true); writer.Write((UInt16)kvp.Key); foreach (Point2D p in keyColl) { writer.Write((UInt16)p.X); writer.Write((UInt16)p.Y); LandTile[] blocktiles = CurrentMatrix.GetLandBlock(p.X, p.Y); for (int j = 0; j < 64; j++) { writer.Write((UInt16)blocktiles[j].ID); writer.Write((sbyte)blocktiles[j].Z); } } writer.Close(); } m_LandChanges[kvp.Key].Clear(); keyColl = m_StaticsChanges[kvp.Key].Keys; if (keyColl.Count > 0) { string filename = string.Format("statics{0}-{1}.live", kvp.Key, Stamp); GenericWriter writer = new BinaryFileWriter(Path.Combine(UltimaLiveSettings.UltimaLiveMapChangesSavePath, filename), true); writer.Write((UInt16)kvp.Key); foreach (Point2D p in keyColl) { StaticTile[][][] staticTiles = CurrentMatrix.GetStaticBlock(p.X, p.Y); int staticCount = 0; for (int i = 0; i < staticTiles.Length; i++) { for (int j = 0; j < staticTiles[i].Length; j++) { staticCount += staticTiles[i][j].Length; } } writer.Write((UInt16)p.X); writer.Write((UInt16)p.Y); writer.Write((int)staticCount); for (int i = 0; i < staticTiles.Length; i++) { for (int j = 0; j < staticTiles[i].Length; j++) { for (int k = 0; k < staticTiles[i][j].Length; k++) { writer.Write((ushort)staticTiles[i][j][k].ID); writer.Write((byte)i); writer.Write((byte)j); writer.Write((sbyte)staticTiles[i][j][k].Z); writer.Write((short)staticTiles[i][j][k].Hue); } } } } writer.Close(); } m_StaticsChanges[kvp.Key].Clear(); } catch { Console.WriteLine("Key: " + kvp.Key); } } }
private void InternalSerializeHeaders(BinaryFileWriter writer, bool compress) { byte[] hash_entry_data = InternalGetHashEntryBytes(); byte[] block_entry_data = InternalGetBlockEntryBytes(); if (compress) { byte[] hash_entries_compressed, block_entries_compressed; Compression.LZF.Compress(hash_entry_data, out hash_entries_compressed); Compression.LZF.Compress(block_entry_data, out block_entries_compressed); m_Header.SetCompressedDataSizes((uint)hash_entries_compressed.Length, (uint)block_entries_compressed.Length); m_Header.Serialize(writer); writer.Write(hash_entries_compressed); writer.Write(block_entries_compressed); } else { m_Header.HashTableSizeCompressed = 0; m_Header.BlockTableSizeCompressed = 0; m_Header.Serialize(writer); writer.Write(hash_entry_data); writer.Write(block_entry_data); } }
private byte[] InternalGetHashEntryBytes() { byte[] hash_entry_data; BinaryFileWriter mem_writer = new BinaryFileWriter(new MemoryStream(), false); for (int i = 0; i < m_Header.Hashcount; i++) { if (m_HashEntries[i] != null) m_HashEntries[i].Serialize(mem_writer); else LPKHashEntry.SerializeAsEmpty(mem_writer); } hash_entry_data = ((MemoryStream)mem_writer.UnderlyingStream).ToArray(); mem_writer.Close(); mem_writer = null; return hash_entry_data; }
private byte[] InternalGetBlockEntryBytes() { byte[] data; BinaryFileWriter mem_writer = new BinaryFileWriter(new MemoryStream(), false); for (int i = 0; i < m_Header.BlockCount; i++) m_BlockEntries[i].Serialize(mem_writer); data = ((MemoryStream)mem_writer.UnderlyingStream).ToArray(); mem_writer.Close(); mem_writer = null; return data; }
public static void SaveDuellers() { GenericWriter bin = new BinaryFileWriter(duellersBinPath, true); bin.WriteMobileList(duellers, true); bin.Close(); }
/* ID's: * 101 = Button Manage System * 102 = Button Import Page * 103 = Button Apply Location * 104 = Button Apply Category * 105 = Text Name * 106 = Text X * 107 = Text Y * 108 = Text Z * 109 = Text Hue * 110 = Text Cost * 111 = Radio Trammel * 112 = Radio Malas * 113 = Radio Felucca * 114 = Radio Ilshenar * 115 = Radio Tokuno * 116 = Check Generate * 117 = Check StaffOnly * 118 = Check Reds * 119 = Check Charge * 120 = Check Young * 121 = Button Add Category * 122 = Button Add Location * 123 = Button Export * 124 = Button Import Systems * 125 = Button Import Categories * 126 = Button Import Locations * 300+ = Imports */ public override void OnResponse(NetState state, RelayInfo info, ACCGumpParams subParams) { if (info.ButtonID == 0 || state.Mobile.AccessLevel < ACC.GlobalMinimumAccessLevel) { return; } if (subParams is PGGumpParams) { Params = subParams as PGGumpParams; } PGGumpParams newParams = new PGGumpParams(); if (info.ButtonID == 101) { newParams.Page = Pages.Manage; } else if (info.ButtonID == 102) { newParams.Page = Pages.Import; } #region Add/Remove else if (info.ButtonID == 103 || info.ButtonID == 104 || info.ButtonID == 121 || info.ButtonID == 122) { SetFlag(EntryFlag.Generate, info.IsSwitched(116)); SetFlag(EntryFlag.StaffOnly, info.IsSwitched(117)); SetFlag(EntryFlag.Reds, info.IsSwitched(118)); SetFlag(EntryFlag.Charge, info.IsSwitched(119)); Map Map = info.IsSwitched(111) ? Map.Trammel : info.IsSwitched(112) ? Map.Malas : info.IsSwitched(113) ? Map.Felucca : info.IsSwitched(114) ? Map.Ilshenar : info.IsSwitched(115) ? Map.Tokuno : Map.Trammel; string Name = GetString(info, 105); string X = GetString(info, 106); string Y = GetString(info, 107); string Z = GetString(info, 108); string H = GetString(info, 109); string C = GetString(info, 110); if (Name == null || Name.Length == 0) { try { state.Mobile.SendMessage("Removed the entry"); if (info.ButtonID == 103) { Params.SelectedCategory.Key.Locations.Remove(Params.SelectedLocation.Key); } else { m_CategoryList.Remove(Params.SelectedCategory.Key); } } catch { Console.WriteLine("Exception caught removing entry"); } } else { if (info.ButtonID == 103 || info.ButtonID == 122) { int x, y, z, h, c = 0; Point3D Loc; int Hue; int Cost; PGLocation PGL; if (X == null || X.Length == 0 || Y == null || Y.Length == 0 || Z == null || Z.Length == 0 || H == null || H.Length == 0 || C == null || C.Length == 0) { if (info.ButtonID == 122) { Hue = 0; Loc = new Point3D(0, 0, 0); Cost = 0; PGL = new PGLocation(Name, Flags, Loc, Map, Hue, Cost); if (PGL == null) { state.Mobile.SendMessage("Error adding Location."); return; } m_CategoryList[Params.SelectedCategory.Value].Locations.Add(PGL); } state.Mobile.SendMessage("Please fill in each field."); state.Mobile.SendGump(new ACCGump(state.Mobile, this.ToString(), Params)); return; } try { x = Int32.Parse(X); y = Int32.Parse(Y); z = Int32.Parse(Z); h = Int32.Parse(H); c = Int32.Parse(C); Loc = new Point3D(x, y, z); Hue = h; Cost = c; } catch { state.Mobile.SendMessage("Please enter an integer in each of the info fields. (X, Y, Z, H, Cost)"); state.Mobile.SendGump(new ACCGump(state.Mobile, this.ToString(), Params)); return; } PGL = new PGLocation(Name, Flags, Loc, Map, Hue, Cost); if (PGL == null) { state.Mobile.SendMessage("Bad Location information, can't add!"); } else { try { if (info.ButtonID == 122) { m_CategoryList[Params.SelectedCategory.Value].Locations.Add(PGL); state.Mobile.SendMessage("Added the Location."); } else { state.Mobile.SendMessage("Changed the Location."); m_CategoryList[Params.SelectedCategory.Value].Locations[Params.SelectedLocation.Value] = PGL; } } catch { Console.WriteLine("Problem adding/changing Location!"); } } } else { if (C == null || C.Length == 0) { state.Mobile.SendMessage("Please fill in each field."); state.Mobile.SendGump(new ACCGump(state.Mobile, this.ToString(), Params)); return; } int c = 0; int Cost; try { c = Int32.Parse(C); Cost = c; } catch { state.Mobile.SendMessage("Please enter an integer for the Cost"); state.Mobile.SendGump(new ACCGump(state.Mobile, this.ToString(), Params)); return; } try { if (info.ButtonID == 121) { m_CategoryList.Add(new PGCategory(Name, Flags, Cost)); state.Mobile.SendMessage("Added the Category."); } else { m_CategoryList[Params.SelectedCategory.Value].Name = Name; m_CategoryList[Params.SelectedCategory.Value].Flags = Flags; m_CategoryList[Params.SelectedCategory.Value].Cost = Cost; state.Mobile.SendMessage("Changed the Category."); } } catch { Console.WriteLine("Problems adding/changing Category!"); } } } } #endregion //Add/Remove #region Imports/Exports #region Exports else if (info.ButtonID == 123) { if (!Directory.Exists("ACC Exports")) { Directory.CreateDirectory("ACC Exports"); } string fileName; string Path = "ACC Exports/"; if (Params.SelectedLocation.Key != null) { fileName = String.Format("Location - {0}.pgl", Params.SelectedLocation.Key.Name); } else if (Params.SelectedCategory.Key != null) { fileName = String.Format("Category - {0}.pgc", Params.SelectedCategory.Key.Name); } else { fileName = String.Format("System - {0:yyMMdd-HHmmss}.pgs", DateTime.Now); } try { using (FileStream m_FileStream = new FileStream(Path + fileName, FileMode.Create, FileAccess.Write)) { GenericWriter writer = new BinaryFileWriter(m_FileStream, true); if (Params.SelectedLocation.Key != null) { Params.SelectedLocation.Key.Serialize(writer); state.Mobile.SendMessage("Exported the Location to {0}{1}", Path, fileName); } else if (Params.SelectedCategory.Key != null) { Params.SelectedCategory.Key.Serialize(writer); state.Mobile.SendMessage("Exported the Category (and all Locations contained within) to {0}{1}", Path, fileName); } else { writer.Write((int)0); //version writer.Write(m_CategoryList.Count); for (int i = 0; i < m_CategoryList.Count; i++) { m_CategoryList[i].Serialize(writer); } state.Mobile.SendMessage("Exported the entire Public Gates System to {0}{1}", Path, fileName); } writer.Close(); m_FileStream.Close(); } } catch (Exception e) { state.Mobile.SendMessage("Problem exporting the selection. Please contact the admin."); Console.WriteLine("Error exporting PGSystem : {0}", e); } } #endregion //Exports #region Imports //Switch between import types else if (info.ButtonID == 124 || info.ButtonID == 125 || info.ButtonID == 126) { newParams.Page = Pages.Import; switch (info.ButtonID) { case 124: newParams.ImportSelection = ImportSelections.Systems; break; case 125: newParams.ImportSelection = ImportSelections.Categories; break; case 126: newParams.ImportSelection = ImportSelections.Locations; break; } } //Perform the import else if (info.ButtonID >= 300 && Dirs != null && Dirs.Length > 0) { if (!Directory.Exists("ACC Exports")) { Directory.CreateDirectory("ACC Exports"); } string Path = null; try { Path = Dirs[info.ButtonID - 300]; if (File.Exists(Path)) { using (FileStream m_FileStream = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryFileReader reader = new BinaryFileReader(new BinaryReader(m_FileStream)); switch ((int)Params.ImportSelection) { case (int)ImportSelections.Systems: { //Systems int version = reader.ReadInt(); int count = reader.ReadInt(); List <PGCategory> list = new List <PGCategory>(); for (int i = 0; i < count; i++) { list.Add(new PGCategory(reader)); } state.Mobile.CloseGump(typeof(SysChoiceGump)); state.Mobile.SendGump(new SysChoiceGump(this.ToString(), Params, list)); reader.Close(); return; } case (int)ImportSelections.Categories: { //Categories if (m_CategoryList == null) { m_CategoryList = new List <PGCategory>(); } m_CategoryList.Add(new PGCategory(reader)); state.Mobile.SendMessage("Added the Category."); break; } case (int)ImportSelections.Locations: { //Locations state.Mobile.CloseGump(typeof(CatSelGump)); state.Mobile.SendMessage("Please choose a Category to put this Location in."); state.Mobile.SendGump(new CatSelGump(this.ToString(), Params, new PGLocation(reader))); reader.Close(); return; } } reader.Close(); } } } catch { } } #endregion //Imports #endregion //Imports/Exports else if (info.ButtonID >= 150 && info.ButtonID < m_CategoryList.Count + 150) { newParams.SelectedCategory = new KeyValuePair <PGCategory, int>(m_CategoryList[info.ButtonID - 150], info.ButtonID - 150); } else if (info.ButtonID >= 200 && info.ButtonID < 200 + Params.SelectedCategory.Key.Locations.Count) { newParams.SelectedCategory = Params.SelectedCategory; newParams.SelectedLocation = new KeyValuePair <PGLocation, int>(Params.SelectedCategory.Key.Locations[info.ButtonID - 200], info.ButtonID - 200); } state.Mobile.SendGump(new ACCGump(state.Mobile, this.ToString(), newParams)); }
public static void onSave( WorldSaveEventArgs e ) { Console.WriteLine( "Saving Jailings" ); if( !Directory.Exists( jailDirectory ) ) Directory.CreateDirectory( jailDirectory ); GenericWriter idxWriter; GenericWriter binWriter; long tPos; if( StandardSaveStrategy.SaveType == 0 ) { idxWriter = new BinaryFileWriter( idxPath, false ); binWriter = new BinaryFileWriter( binPath, true ); } else { idxWriter = new AsyncWriter( idxPath, false ); binWriter = new AsyncWriter( binPath, true ); } idxWriter.WriteEncodedInt( m_jailings.Count ); try { foreach( JailSystem tJail in m_jailings.Values ) { tPos = binWriter.Position; idxWriter.Write( 0 ); idxWriter.Write( tJail.ID ); idxWriter.Write( tPos ); try { tJail.Serialize( binWriter ); } catch( Exception err ) { Console.WriteLine( "{0}, {1} serialize", err.Message, err.TargetSite ); } idxWriter.Write( (int)( binWriter.Position - tPos ) ); } saveingameeditsettings( binWriter ); } catch( Exception er ) { Console.WriteLine( "{0}, {1}", er.Message, er.TargetSite ); } idxWriter.Close(); binWriter.Close(); Console.WriteLine( "Jailings Saved" ); }
/// <summary> /// Saves persistent data /// </summary> private static void OnWorldSave( WorldSaveEventArgs args ) { if( !Directory.Exists(DataPath) ) Directory.CreateDirectory(DataPath); BinaryFileWriter writer = new BinaryFileWriter(DataFile, true); writer.Write((int)EoCTable.Count); foreach( KeyValuePair<Player, EoCContext> kvp in EoCTable ) { if( kvp.Key == null || kvp.Key.Deleted ) { writer.Write(false); } else { writer.Write(true); writer.WriteMobile<Player>(kvp.Key); kvp.Value.Serialize(writer); } } writer.Write((int)HitsTable.Count); foreach( KeyValuePair<Player, HitsTimer> kvp in HitsTable ) { if( kvp.Key != null && !kvp.Key.Deleted && kvp.Value.Running ) { writer.Write(true); writer.WriteMobile<Player>(kvp.Key); writer.Write(kvp.Value.Next); } else { writer.Write(false); } } writer.Close(); }
public static void Save(WorldSaveEventArgs e) { if (EntityAttachments == null) { return; } CleanUp(); if (!Directory.Exists("Saves/Attachments")) { Directory.CreateDirectory("Saves/Attachments"); } string filePath = Path.Combine("Saves/Attachments", "Attachments.bin"); // the attachment serializations string imaPath = Path.Combine("Saves/Attachments", "Attachments.ima"); // the item/mob attachment tables string fpiPath = Path.Combine("Saves/Attachments", "Attachments.fpi"); // the file position indices BinaryFileWriter writer = null; BinaryFileWriter imawriter = null; BinaryFileWriter fpiwriter = null; try { writer = new BinaryFileWriter(filePath, true); imawriter = new BinaryFileWriter(imaPath, true); fpiwriter = new BinaryFileWriter(fpiPath, true); } catch (Exception err) { ErrorReporter.GenerateErrorReport(err.ToString()); return; } if (writer != null && imawriter != null && fpiwriter != null) { // save the current global attachment serial state ASerial.GlobalSerialize(writer); // remove all deleted attachments FullDefrag(); // save the attachments themselves if (AllAttachments != null) { writer.Write(AllAttachments.Count); var valuearray = new XmlAttachment[AllAttachments.Count]; AllAttachments.Values.CopyTo(valuearray, 0); var keyarray = new int[AllAttachments.Count]; AllAttachments.Keys.CopyTo(keyarray, 0); for (int i = 0; i < keyarray.Length; i++) { // write the key writer.Write(keyarray[i]); XmlAttachment a = valuearray[i]; // write the value type writer.Write(a.GetType().ToString()); // serialize the attachment itself a.Serialize(writer); // save the fileposition index fpiwriter.Write(writer.Position); } } else { writer.Write(0); } writer.Close(); /* // Collapsed into a single IEntity Hash // save the hash table info for items and mobiles // mobile attachments if (XmlAttach.MobileAttachments != null) { imawriter.Write(XmlAttach.MobileAttachments.Count); object[] valuearray = new object[XmlAttach.MobileAttachments.Count]; XmlAttach.MobileAttachments.Values.CopyTo(valuearray, 0); object[] keyarray = new object[XmlAttach.MobileAttachments.Count]; XmlAttach.MobileAttachments.Keys.CopyTo(keyarray, 0); for (int i = 0; i < keyarray.Length; i++) { // write the key imawriter.Write((Mobile)keyarray[i]); // write out the attachments ArrayList alist = (ArrayList)valuearray[i]; imawriter.Write((int)alist.Count); foreach (XmlAttachment a in alist) { // write the attachment serial imawriter.Write((int)a.Serial.Value); // write the value type imawriter.Write((string)a.GetType().ToString()); // save the fileposition index fpiwriter.Write((long)imawriter.Position); } } } else { // no mobile attachments imawriter.Write((int)0); } // item attachments if (XmlAttach.ItemAttachments != null) { imawriter.Write(XmlAttach.ItemAttachments.Count); object[] valuearray = new object[XmlAttach.ItemAttachments.Count]; XmlAttach.ItemAttachments.Values.CopyTo(valuearray, 0); object[] keyarray = new object[XmlAttach.ItemAttachments.Count]; XmlAttach.ItemAttachments.Keys.CopyTo(keyarray, 0); for (int i = 0; i < keyarray.Length; i++) { // write the key imawriter.Write((Item)keyarray[i]); // write out the attachments ArrayList alist = (ArrayList)valuearray[i]; imawriter.Write((int)alist.Count); foreach (XmlAttachment a in alist) { // write the attachment serial imawriter.Write((int)a.Serial.Value); // write the value type imawriter.Write((string)a.GetType().ToString()); // save the fileposition index fpiwriter.Write((long)imawriter.Position); } } } else { // no item attachments imawriter.Write((int)0); }*/ // Alan MOD // save the hash table info for items and mobiles // mobile attachments if (EntityAttachments != null) { imawriter.Write(EntityAttachments.Count); var valuearray = new ArrayList[EntityAttachments.Count]; EntityAttachments.Values.CopyTo(valuearray, 0); var keyarray = new int[EntityAttachments.Count]; EntityAttachments.Keys.CopyTo(keyarray, 0); for (int i = 0; i < keyarray.Length; i++) { // write the key imawriter.Write(keyarray[i]); // write out the attachments ArrayList alist = valuearray[i]; imawriter.Write(alist.Count); foreach (XmlAttachment a in alist) { // write the attachment serial imawriter.Write(a.Serial.Value); // write the value type imawriter.Write(a.GetType().ToString()); // save the fileposition index fpiwriter.Write(imawriter.Position); } } } else { // no mobile attachments imawriter.Write(0); } imawriter.Write(0); // pretend no item attachments and leave the deserialization as-is -- this way deserialization will still work with older saves -Alan // END ALAN MOD imawriter.Close(); fpiwriter.Close(); } }
private static short FactorySave() { if (RareFactory.InUse) { Console.WriteLine("FactorySave() : Rare Factory busy, cannot save"); return 1; } // Save DOD information Console.WriteLine("FactorySave() : Saving DOD instance definitions"); if ( !Directory.Exists( "Saves/AngelIsland" ) ) Directory.CreateDirectory( "Saves/AngelIsland" ); string filePath = Path.Combine( "Saves/AngelIsland", "RareFactory.dat" ); BinaryFileWriter bfw = new BinaryFileWriter(filePath, true); // Version ((GenericWriter)bfw).Write((short)0); // First write out how many we're going to have to save (and hence load in again) ((GenericWriter)bfw).Write((short)m_DODInst.Count); // Loop through DOD instances and have them write their definitions out to this // stream for( int i=0; i < m_DODInst.Count; i++ ) { ((DODInstance) m_DODInst[i]).Save(bfw); } Console.WriteLine("FactorySave() : Saved {0} instance definitions", m_DODInst.Count); // Write out our group definitions Console.WriteLine("FactorySave() : Saving DOD group definitions"); // Number of groups ((GenericWriter)bfw).Write((short)m_DODGroup.Count); for (int i = 0; i < m_DODGroup.Count; i++) { if (m_DODGroup[i] is DODGroup) { ((DODGroup)m_DODGroup[i]).Save(bfw); } } Console.WriteLine("FactorySave() : Saved {0} group definitions", m_DODGroup.Count); ((GenericWriter)bfw).Close(); return 1; }
public static void Save(WorldSaveEventArgs args) { Console.WriteLine("Resource Pool Saving..."); if (!Directory.Exists("Saves/ResourcePool")) { Directory.CreateDirectory("Saves/ResourcePool"); } XmlTextWriter writer = new XmlTextWriter("Saves/ResourcePool/config.xml", System.Text.Encoding.Default); writer.Formatting = Formatting.Indented; BinaryFileWriter rcwriter = new BinaryFileWriter(new FileStream("Saves/ResourcePool/Consignments.dat", FileMode.Create, FileAccess.Write), true); BinaryFileWriter dwriter = new BinaryFileWriter(new FileStream("Saves/ResourcePool/Debts.dat", FileMode.Create, FileAccess.Write), true); writer.WriteStartDocument(true); writer.WriteStartElement("ResourcePool"); writer.WriteAttributeString("version", "1"); try { // VERSION 1 writer.WriteElementString("PaymentFactor", m_PaymentFactor.ToString("R")); writer.WriteElementString("FailsafePriceHike", m_FailsafePriceHike.ToString("R")); //Hashtable RDTable = new Hashtable(); rcwriter.Write((int)0); // version //rcwriter.Write((long)0); // placeholder tableposition foreach (Type t in m_Resources.Keys) { if (m_Resources[t] is RDRedirect || !(m_Resources[t] is ResourceData)) { continue; } //RDTable[t.FullName] = rcwriter.Position; //Console.WriteLine("{0} {1}", t.FullName, rcwriter.Position); ((ResourceData)m_Resources[t]).Save(writer, rcwriter); } foreach (Type t in m_Resources.Keys) { if (!(m_Resources[t] is RDRedirect)) { continue; } //RDTable[t.FullName] = rcwriter.Position; //Console.WriteLine("{0} {1}", t.FullName, rcwriter.Position); ((RDRedirect)m_Resources[t]).Save(writer, rcwriter); } /*long pos = rcwriter.Position; * foreach (string key in RDTable.Keys) * { * rcwriter.Write((string)key); * rcwriter.Write((long)RDTable[key]); * Console.WriteLine("Writing {0} {1}", key, (long)RDTable[key]); * } * rcwriter.UnderlyingStream.Seek(0, SeekOrigin.Begin); * rcwriter.Write((int)0); // REAL version * rcwriter.Write((long)pos); // REAL tableposition * Console.WriteLine("Writing tableposition {0}", pos);*/ // version 1 change // we used to read until EOF, but there is a bug with that. // so now we write the number of hashtable elements written // http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=127647&SiteID=1 // count valid elements int count = 0; foreach (Mobile m in m_Debts.Keys) { // mobile serials can get reassigned to non PlayerMobiles if (m == null || m.Deleted || m is PlayerMobile == false) { continue; } count++; } // write count dwriter.Write(count); // write elements foreach (Mobile m in m_Debts.Keys) { if (m == null || m.Deleted || m is PlayerMobile == false) { continue; } dwriter.Write((Mobile)m); dwriter.Write((double)m_Debts[m]); } } finally { writer.WriteEndDocument(); } BinaryFileWriter rpw = new BinaryFileWriter(new FileStream("Saves/ResourcePool/ResourcePool.dat", FileMode.Create, FileAccess.Write), true); rpw.Write((int)0); // version rpw.Write((DateTime)m_LastModified); rpw.Close(); writer.Close(); rcwriter.Close(); dwriter.Close(); }
public static void Save() { if (!Directory.Exists("Saves/FriendLists/")) Directory.CreateDirectory("Saves/FriendLists/"); string idxPath = Path.Combine( "Saves/FriendLists", "FriendLists.idx" ); string binPath = Path.Combine( "Saves/FriendLists", "FriendLists.bin" ); GenericWriter idx = new BinaryFileWriter(idxPath, false); GenericWriter bin = new BinaryFileWriter(binPath, true); idx.Write( (int)FriendLists.Values.Count ); foreach ( FriendList fl in FriendLists.Values ) { long startPos = bin.Position; fl.Serialize( bin ); idx.Write( (long)startPos ); idx.Write( (int)(bin.Position - startPos) ); } idx.Close(); bin.Close(); }
protected void SaveMobiles() { Dictionary<Serial, Mobile> mobiles = World.Instance.m_Mobiles; GenericWriter idx = new BinaryFileWriter( World.MobileIndexPath, false ); GenericWriter tdb = new BinaryFileWriter( World.MobileTypesPath, false ); GenericWriter bin = new BinaryFileWriter( World.MobileDataPath, true ); idx.Write( (int) mobiles.Count ); foreach ( Mobile m in mobiles.Values ) { long start = bin.Position; idx.Write( (int) m.m_TypeRef ); idx.Write( (int) m.Serial ); idx.Write( (long) start ); m.Serialize( bin ); idx.Write( (int) ( bin.Position - start ) ); if ( m is IVendor ) { IVendor vendor = m as IVendor; if ( ( vendor.LastRestock + vendor.RestockDelay ) < DateTime.Now ) m_RestockQueue.Enqueue( vendor ); } m.FreeCache(); } tdb.Write( (int) World.m_MobileTypes.Count ); for ( int i = 0; i < World.m_MobileTypes.Count; ++i ) tdb.Write( World.m_MobileTypes[i].FullName ); idx.Close(); tdb.Close(); bin.Close(); }
public static void Save(WorldSaveEventArgs e) { if (MobileAttachments == null && ItemAttachments == null) { return; } CleanUp(); if (!Directory.Exists("Saves/Attachments")) { Directory.CreateDirectory("Saves/Attachments"); } string filePath = Path.Combine("Saves/Attachments", "Attachments.bin"); // the attachment serializations string imaPath = Path.Combine("Saves/Attachments", "Attachments.ima"); // the item/mob attachment tables string fpiPath = Path.Combine("Saves/Attachments", "Attachments.fpi"); // the file position indices BinaryFileWriter writer = null; BinaryFileWriter imawriter = null; BinaryFileWriter fpiwriter = null; try { writer = new BinaryFileWriter(filePath, true); imawriter = new BinaryFileWriter(imaPath, true); fpiwriter = new BinaryFileWriter(fpiPath, true); } catch (Exception err) { ErrorReporter.GenerateErrorReport(err.ToString()); return; } if (writer != null && imawriter != null && fpiwriter != null) { // save the current global attachment serial state ASerial.GlobalSerialize(writer); // remove all deleted attachments FullDefrag(); // save the attachments themselves if (AllAttachments != null) { writer.Write(AllAttachments.Count); var valuearray = new object[AllAttachments.Count]; AllAttachments.Values.CopyTo(valuearray, 0); var keyarray = new object[AllAttachments.Count]; AllAttachments.Keys.CopyTo(keyarray, 0); for (int i = 0; i < keyarray.Length; i++) { // write the key writer.Write((int)keyarray[i]); XmlAttachment a = valuearray[i] as XmlAttachment; // write the value type writer.Write(a.GetType().ToString()); // serialize the attachment itself a.Serialize(writer); // save the fileposition index fpiwriter.Write(writer.Position); } } else { writer.Write(0); } writer.Close(); // save the hash table info for items and mobiles // mobile attachments if (MobileAttachments != null) { imawriter.Write(MobileAttachments.Count); var valuearray = new object[MobileAttachments.Count]; MobileAttachments.Values.CopyTo(valuearray, 0); var keyarray = new object[MobileAttachments.Count]; MobileAttachments.Keys.CopyTo(keyarray, 0); for (int i = 0; i < keyarray.Length; i++) { // write the key imawriter.Write((Mobile)keyarray[i]); // write out the attachments ArrayList alist = (ArrayList)valuearray[i]; imawriter.Write(alist.Count); foreach (XmlAttachment a in alist) { // write the attachment serial imawriter.Write(a.Serial.Value); // write the value type imawriter.Write(a.GetType().ToString()); // save the fileposition index fpiwriter.Write(imawriter.Position); } } } else { // no mobile attachments imawriter.Write(0); } // item attachments if (ItemAttachments != null) { imawriter.Write(ItemAttachments.Count); var valuearray = new object[ItemAttachments.Count]; ItemAttachments.Values.CopyTo(valuearray, 0); var keyarray = new object[ItemAttachments.Count]; ItemAttachments.Keys.CopyTo(keyarray, 0); for (int i = 0; i < keyarray.Length; i++) { // write the key imawriter.Write((Item)keyarray[i]); // write out the attachments ArrayList alist = (ArrayList)valuearray[i]; imawriter.Write(alist.Count); foreach (XmlAttachment a in alist) { // write the attachment serial imawriter.Write(a.Serial.Value); // write the value type imawriter.Write(a.GetType().ToString()); // save the fileposition index fpiwriter.Write(imawriter.Position); } } } else { // no item attachments imawriter.Write(0); } imawriter.Close(); fpiwriter.Close(); } }
public static bool Add(ResourceTransaction rt, Mobile player) { if (!(m_History[player] is ArrayList)) { LoadHistory(player); } int count = 0; foreach (ResourceTransaction r in (ArrayList)m_History[player]) { if (r.TransactionID == rt.TransactionID && r.TransType == rt.TransType) { break; } count++; } // fear not, this is just a sh!tload of casts and indexes if (count < ((ArrayList)m_History[player]).Count) { ((ResourceTransaction)((ArrayList)m_History[player])[count]).Amount += rt.Amount; } else { ((ArrayList)m_History[player]).Insert(0, rt); } if (((ArrayList)m_History[player]).Count > 50) { ((ArrayList)m_History[player]).RemoveRange(49, ((ArrayList)m_History[player]).Count - 50); } m_TransactionStack--; if (m_TransactionStack == 0) { m_TransID++; } // log if (m_LogLevel > 0) { try { if (!Directory.Exists("Saves/ResourcePool")) { Directory.CreateDirectory("Saves/ResourcePool"); } if (!Directory.Exists("Saves/ResourcePool/TransactionHistories")) { Directory.CreateDirectory("Saves/ResourcePool/TransactionHistories"); } BinaryFileWriter writer = new BinaryFileWriter(new FileStream("Saves/ResourcePool/MasterHistory.dat", FileMode.Append, FileAccess.Write, FileShare.Read), true); rt.Serialize(writer); writer.Close(); } catch (Exception e) { LogHelper.LogException(e); Console.WriteLine("ResourceLogger error: Failed to open MasterHistory.dat for writing."); Console.WriteLine(e.ToString()); } } return(true); }
protected void SaveItems() { Dictionary<Serial, Item> items = World.Instance.m_Items; GenericWriter idx = new BinaryFileWriter( World.ItemIndexPath, false ); GenericWriter tdb = new BinaryFileWriter( World.ItemTypesPath, false ); GenericWriter bin = new BinaryFileWriter( World.ItemDataPath, true ); idx.Write( (int) items.Count ); foreach ( Item item in items.Values ) { if ( item.Decays && item.Parent == null && item.Map != Map.Internal && ( item.LastMoved + item.DecayTime ) <= DateTime.Now ) m_DecayQueue.Enqueue( item ); long start = bin.Position; idx.Write( (int) item.m_TypeRef ); idx.Write( (int) item.Serial ); idx.Write( (long) start ); item.Serialize( bin ); idx.Write( (int) ( bin.Position - start ) ); item.FreeCache(); } tdb.Write( (int) World.m_ItemTypes.Count ); for ( int i = 0; i < World.m_ItemTypes.Count; ++i ) tdb.Write( World.m_ItemTypes[i].FullName ); idx.Close(); tdb.Close(); bin.Close(); }
public static void SaveDuels() { GenericWriter idx = new BinaryFileWriter(duelIdxPath, false); GenericWriter bin = new BinaryFileWriter(duelBinPath, true); idx.Write((int)duels.Count); foreach (DuelObject d in duels) { if (!d.Player1.Deleted && !d.Player2.Deleted) { long startPos = bin.Position; d.Serialize(bin); idx.Write((long)startPos); idx.Write((int)(bin.Position - startPos)); } } idx.Close(); bin.Close(); }
protected void SaveGuilds() { GenericWriter idx = new BinaryFileWriter( World.GuildIndexPath, false ); GenericWriter tdb = new BinaryFileWriter( World.GuildTypesPath, false ); GenericWriter bin = new BinaryFileWriter( World.GuildDataPath, true ); idx.Write( (int) BaseGuild.List.Count ); foreach ( BaseGuild guild in BaseGuild.List.Values ) { long start = bin.Position; idx.Write( (int) guild.m_TypeRef ); idx.Write( (int) guild.Serial ); idx.Write( (long) start ); guild.Serialize( bin ); idx.Write( (int) ( bin.Position - start ) ); } tdb.Write( (int) World.m_GuildTypes.Count ); for ( int i = 0; i < World.m_GuildTypes.Count; ++i ) tdb.Write( World.m_GuildTypes[i].FullName ); idx.Close(); tdb.Close(); bin.Close(); }
private static void Serialize(WorldSaveEventArgs e) { if (!Directory.Exists(m_Directory)) Directory.CreateDirectory(m_Directory); GenericWriter writer = new BinaryFileWriter(m_FilePath, true); writer.Write(Version);//version writer.Close(); }
public static void OnSave(WorldSaveEventArgs e) { try { Console.WriteLine("TownshipSettings Saving..."); if (!Directory.Exists("Saves/AngelIsland")) { Directory.CreateDirectory("Saves/AngelIsland"); } string filePath = Path.Combine("Saves/AngelIsland", "Township.bin"); GenericWriter bin; bin = new BinaryFileWriter(filePath, true); bin.Write(9); //version //v9 addition bin.Write(WallHitsDecay); //v8 addition bin.Write(AuctioneerPayoutPercentage); //v7 addition bin.Write(AuctioneerCharge); //v6 addition bin.Write(FightBrokerCharge); //v5 addition bin.Write(WallTeleporterDistance); //v4 addition bin.Write(InitialFunds); //v3 additions bin.Write(TSDeedCost); bin.Write(GuildHousePercentage); bin.Write(LLModifierNone); bin.Write(LLModifierLow); bin.Write(LLModifierMed); bin.Write(LLModifierHigh); bin.Write(LLModifierBoom); bin.Write(NPCModifierNone); bin.Write(NPCModifierLow); bin.Write(NPCModifierMed); bin.Write(NPCModifierHigh); bin.Write(NPCModifierBoom); bin.Write(BaseModifierNone); bin.Write(BaseModifierLow); bin.Write(BaseModifierMed); bin.Write(BaseModifierHigh); bin.Write(BaseModifierBoom); //begin v2 additions bin.Write(BaseFee); bin.Write(ExtendedFee); bin.Write(NoGateOutFee); bin.Write(NoGateInFee); bin.Write(NoRecallOutFee); bin.Write(NoRecallInFee); bin.Write(LawlessFee); bin.Write(LawAuthFee); bin.Write(NPCType1Fee); bin.Write(NPCType2Fee); bin.Write(NPCType3Fee); bin.Write(LawNormCharge); bin.Write(LawlessCharge); bin.Write(LawAuthCharge); bin.Write(ChangeTravelCharge); bin.Write(UpdateEnemyCharge); bin.Write(EmissaryCharge); bin.Write(EvocatorCharge); bin.Write(AlchemistCharge); bin.Write(AnimalTrainerCharge); bin.Write(BankerCharge); bin.Write(InnkeeperCharge); bin.Write(MageCharge); bin.Write(ProvisionerCharge); bin.Write(ArmsTrainerCharge); bin.Write(MageTrainerCharge); bin.Write(RogueTrainerCharge); bin.Write(LookoutCharge); bin.Write(TownCrierCharge); //v1 below bin.Write(Hue); bin.Write(NoneToLow); bin.Write(LowToMedium); bin.Write(MediumToHigh); bin.Write(HighToBooming); bin.Close(); } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } }
public void Serialize(BinaryFileWriter writer) { writer.Write((uint)SecondHash); writer.Write((uint)BlockIndex); writer.Write((uint)NextHashInSequence); }
public static void SerializeAsEmpty(BinaryFileWriter writer) { writer.Write((uint)0); writer.Write((uint)0); writer.Write((uint)LPK.NoHash); }
private static void EventSink_WorldSave(WorldSaveEventArgs e) { DateTime start = DateTime.Now; Console.WriteLine("processing additional components."); Console.WriteLine("Forums: Saving..."); if (AutoCleanup) { Console.Write("Auto Cleanup is checking posts..."); } else { Console.Write("Checking deletion queue..."); } int queue = 0; int deleted = RemovedDeletedQueue(out queue); if (queue == 0) { Console.Write("Empty Queue..."); } else { Console.Write("{1} Queued...{0} Deleted...", deleted, queue); } string SavePath = Path.Combine(m_SavePath, "forumdata.sig"); if (!Directory.Exists(m_SavePath)) { Directory.CreateDirectory(m_SavePath); } GenericWriter bin = new BinaryFileWriter(SavePath, true); try { bin.Write(( int )0); //Versioning WritePlayerStatistics(bin); bin.Write(( int )(m_Threads.Count)); foreach (ThreadEntry te in m_Threads) { te.Serialize(bin); } bin.WriteMobileList(m_Moderators); bin.Write(( int )m_ThreadDeleteAccessLevel); bin.Write(( int )m_ThreadLockAccesLevel); bin.Write(( bool )m_AutoCleanup); bin.Write(( int )m_AutoCleanupDays); bin.Write(( int )m_MinPostCharactersCount); bin.Write(( int )m_MaxPostCharactersCount); bin.Close(); DateTime end = DateTime.Now; Console.WriteLine("done in {0:F1} seconds.", (end - start).TotalSeconds); Console.Write("World: "); } catch (Exception err) { bin.Close(); Console.Write("An error occurred while trying to save the forums. {0}", err.ToString()); } }
public static void SaveSpawners_OnCommand(CommandEventArgs e) { if (e.Arguments.Length == 5) { int count = 0; int x1, y1, x2, y2; string FileName = e.Arguments[0].ToString(); try { x1 = Int32.Parse(e.Arguments[1]); y1 = Int32.Parse(e.Arguments[2]); x2 = Int32.Parse(e.Arguments[3]); y2 = Int32.Parse(e.Arguments[4]); } catch { Usage(e.Mobile); return; } //adjust rect if (x1 > x2) { int x3 = x1; x1 = x2; x2 = x3; } if (y1 > y2) { int y3 = y1; y1 = y2; y2 = y3; } string itemIdxPath = Path.Combine("Saves/Spawners/", FileName + ".idx"); string itemBinPath = Path.Combine("Saves/Spawners/", FileName + ".bin"); try { ArrayList list = new ArrayList(); foreach (Item item in Server.World.Items.Values) { if (item is Spawner) { if (item.X >= x1 && item.Y >= y1 && item.X < x2 && item.Y < y2 && item.Map == e.Mobile.Map) { list.Add(item); } } } if (list.Count > 0) { try { string folder = Path.GetDirectoryName(itemIdxPath); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } } catch { e.Mobile.SendMessage("An error occured while trying to create Spawner folder."); } count = list.Count; GenericWriter idx; GenericWriter bin; idx = new BinaryFileWriter(itemIdxPath, false); bin = new BinaryFileWriter(itemBinPath, true); idx.Write((int)list.Count); for (int i = 0; i < list.Count; ++i) { long start = bin.Position; Spawner temp = new Spawner(); CopyProperties(temp, (Spawner)list[i]); idx.Write((long)start); //dont save template data as we cant load it back properly temp.TemplateItem = null; temp.TemplateMobile = null; temp.CreaturesName = ((Spawner)list[i]).CreaturesName; temp.Serialize(bin); idx.Write((int)(bin.Position - start)); temp.Delete(); } idx.Close(); bin.Close(); } } catch (Exception ex) { LogHelper.LogException(ex); System.Console.WriteLine("Exception Caught in SaveSpawner code: " + ex.Message); System.Console.WriteLine(ex.StackTrace); } e.Mobile.SendMessage("{0} Spawners Saved.", count); } else { Usage(e.Mobile); } }
public static void OnSave(WorldSaveEventArgs e) { try { Console.WriteLine("KinSystemSettings Saving..."); if (!Directory.Exists("Saves/AngelIsland")) { Directory.CreateDirectory("Saves/AngelIsland"); } string filePath = Path.Combine("Saves/AngelIsland", "KinSystemSettings.bin"); GenericWriter bin; bin = new BinaryFileWriter(filePath, true); bin.Write(11); //version //v11 bin.Write(A_MaxShoppers); //v10 below bin.Write(A_F_Visitor); bin.Write(A_Visitor); bin.Write(A_F_Sale); bin.Write(A_Sale); bin.Write(A_GPMaint); bin.Write(A_GPHire); bin.Write(A_GDeath); bin.Write(A_F_Death); bin.Write(A_Death); bin.Write(A_GCChampLevel); bin.Write(A_GCDeath); bin.Write(A_MaxVisitors); //v9 below bin.Write(GuardChangeTimeHours); //v8 below bin.Write(CityGuardSlots); bin.Write(GuardMaintMinutes); bin.Write(GuardTypeLowSilverCost); bin.Write(GuardTypeMediumSilverCost); bin.Write(GuardTypeHighSilverCost); bin.Write(GuardTypeLowSilverMaintCost); bin.Write(GuardTypeMediumSilverMaintCost); bin.Write(GuardTypeHighSilverMaintCost); //v7 below bin.Write(KinAwards); //v6 below bin.Write(OutputCaptureData); //v5 below bin.Write(CityCaptureEnabled); bin.Write(VortexCaptureProportion); bin.Write(VortexMinDamagePercentage); bin.Write(BeneficiaryQualifyPercentage); bin.Write(BeneficiaryCap); bin.Write(CaptureDefenseRange); bin.Write(VortexExpireMinutes); bin.Write(BaseCaptureMinutes); //v4 below bin.Write(KinNameHueEnabled); //v3 below bin.Write(ShowStatloss); bin.Write(ShowKinSingleClick); //v2 below: bin.Write(KinAggressionMinutes); bin.Write(KinBeneficialMinutes); bin.Write(KinHealerModifier); //v1 below bin.Write(PointsEnabled); bin.Write(StatLossEnabled); bin.Write(StatLossPercentageSkills); bin.Write(StatLossPercentageStats); bin.Write(StatLossDurationMinutes); bin.Close(); } catch (Exception ex) { EventSink.InvokeLogException(new LogExceptionEventArgs(ex)); } }
private static void EventSink_WorldSave( WorldSaveEventArgs e ) { int queue = 0; int deleted = RemovedDeletedQueue(out queue); if ( queue != 0 ) Console.Write( "{0} Forum Posts Deleted...", deleted ); string SavePath = Path.Combine( m_SavePath, "forumdata.sig" ); if( !Directory.Exists( m_SavePath ) ) Directory.CreateDirectory( m_SavePath ); GenericWriter bin = new BinaryFileWriter( SavePath, true ); try { bin.Write( ( int )0 );//Versioning WritePlayerStatistics( bin ); bin.Write( ( int )( m_Threads.Count ) ); foreach( ThreadEntry te in m_Threads ) { te.Serialize( bin ); } bin.WriteMobileList( m_Moderators ); bin.Write( ( int )m_ThreadDeleteAccessLevel ); bin.Write( ( int )m_ThreadLockAccesLevel ); bin.Write( ( bool )m_AutoCleanup ); bin.Write( ( int )m_AutoCleanupDays ); bin.Write( ( int )m_MinPostCharactersCount ); bin.Write( ( int )m_MaxPostCharactersCount ); bin.Close(); } catch( Exception err ) { bin.Close(); Console.Write( "An error occurred while trying to save the forums. {0}", err.ToString()); } }
public static void OnSave(WorldSaveEventArgs e) { if (!ExportOnNextSave) { return; } ExportOnNextSave = false; if (!Directory.Exists(UltimaLiveSettings.UltimaLiveClientExportPath)) { Directory.CreateDirectory(UltimaLiveSettings.UltimaLiveClientExportPath); } Console.Write("Exporting Client Files..."); /* maps */ // public static Dictionary<int, MapDefinition> Definitions foreach (KeyValuePair <int, MapRegistry.MapDefinition> kvp in MapRegistry.Definitions) { if (!MapRegistry.MapAssociations.ContainsKey(kvp.Key)) { continue; } string filename = string.Format("map{0}.mul", kvp.Key); GenericWriter writer = new BinaryFileWriter(Path.Combine(UltimaLiveSettings.UltimaLiveClientExportPath, filename), true); m_WorkMap = Server.Map.Maps[kvp.Key]; TileMatrix CurrentMatrix = m_WorkMap.Tiles; int blocks = CurrentMatrix.BlockWidth * CurrentMatrix.BlockHeight; for (int xblock = 0; xblock < CurrentMatrix.BlockWidth; xblock++) { for (int yblock = 0; yblock < CurrentMatrix.BlockHeight; yblock++) { writer.Write((uint)0); LandTile[] blocktiles = CurrentMatrix.GetLandBlock(xblock, yblock); if (blocktiles.Length == 196) { Console.WriteLine("Invalid landblock! Save failed!"); return; } else { for (int j = 0; j < 64; j++) { writer.Write((short)blocktiles[j].ID); writer.Write((sbyte)blocktiles[j].Z); } } } } writer.Close(); } /* Statics */ foreach (KeyValuePair <int, MapRegistry.MapDefinition> kvp in MapRegistry.Definitions) { if (!MapRegistry.MapAssociations.ContainsKey(kvp.Key)) { continue; } string filename = string.Format("statics{0}.mul", kvp.Key); GenericWriter staticWriter = new BinaryFileWriter(Path.Combine(UltimaLiveSettings.UltimaLiveClientExportPath, filename), true); filename = string.Format("staidx{0}.mul", kvp.Key); GenericWriter staticIndexWriter = new BinaryFileWriter(Path.Combine(UltimaLiveSettings.UltimaLiveClientExportPath, filename), true); m_WorkMap = Server.Map.Maps[kvp.Key]; TileMatrix CurrentMatrix = m_WorkMap.Tiles; int blocks = CurrentMatrix.BlockWidth * CurrentMatrix.BlockHeight; int startBlock = 0; int finishBlock = 0; for (int xblock = 0; xblock < CurrentMatrix.BlockWidth; xblock++) { for (int yblock = 0; yblock < CurrentMatrix.BlockHeight; yblock++) { StaticTile[][][] staticTiles = CurrentMatrix.GetStaticBlock(xblock, yblock); //Static File for (int i = 0; i < staticTiles.Length; i++) { for (int j = 0; j < staticTiles[i].Length; j++) { StaticTile[] sortedTiles = staticTiles[i][j]; Array.Sort(sortedTiles, BlockUtility.CompareStaticTiles); for (int k = 0; k < sortedTiles.Length; k++) { staticWriter.Write((ushort)sortedTiles[k].ID); staticWriter.Write((byte)i); staticWriter.Write((byte)j); staticWriter.Write((sbyte)sortedTiles[k].Z); staticWriter.Write((short)sortedTiles[k].Hue); finishBlock += 7; } } } //Index File if (finishBlock != startBlock) { staticIndexWriter.Write((int)startBlock); //lookup staticIndexWriter.Write((int)(finishBlock - startBlock)); //length staticIndexWriter.Write((int)0); //extra startBlock = finishBlock; } else { staticIndexWriter.Write((uint)uint.MaxValue); //lookup staticIndexWriter.Write((uint)uint.MaxValue); //length staticIndexWriter.Write((uint)uint.MaxValue); //extra } } } staticWriter.Close(); staticIndexWriter.Close(); } }
public static void Save() { if (!Directory.Exists( "Saves/FS Systems/FSBounty" ) ) Directory.CreateDirectory( "Saves/FS Systems/FSBounty" ); string idxPath = Path.Combine( "Saves/FS Systems/FSBounty", "BountyTable.idx" ); string binPath = Path.Combine( "Saves/FS Systems/FSBounty", "BountyTable.bin" ); GenericWriter idx = new BinaryFileWriter( idxPath, false ); GenericWriter bin = new BinaryFileWriter( binPath, true ); idx.Write( (int)BountyTable.Values.Count ); foreach ( Bounty b in BountyTable.Values ) { long startPos = bin.Position; b.Serialize( bin ); idx.Write( (long)startPos ); idx.Write( (int)( bin.Position - startPos ) ); } idx.Close(); bin.Close(); }
/// <summary> /// Writes the model to a binary STL file. /// </summary> /// <param name="model">The DMTModel to write.</param> /// <param name="file">The file to write to.</param> public void WriteFile(DMTModel model, File file) { //Check that we are not going to inadvertantly overwrite a file file.Delete(); BinaryFileWriter binaryWriter = null; try { binaryWriter = new BinaryFileWriter(file); //If there are no triangles then return if (model.TotalNoOfTriangles == 0) { throw new DMTFileException(DMTFileError.NoTriangles); } // Write header for (var i = 0; i < 80; i++) { byte b = 0; binaryWriter.WriteByte(b); } // write number of triangles binaryWriter.WriteUInteger(model.TotalNoOfTriangles); Point vertex1 = null; Point vertex2 = null; Point vertex3 = null; Vector normal = null; foreach (var block in model.TriangleBlocks) { for (var intCounter = 0; intCounter <= block.NoOfTriangles - 1; intCounter++) { // STL wants a triangle Normal vertex1 = block.GetVertex1(intCounter); vertex2 = block.GetVertex2(intCounter); vertex3 = block.GetVertex3(intCounter); normal = DMTTriangle.GetNormal(vertex1, vertex2, vertex3); binaryWriter.WriteSingle((float)normal.I.Value); binaryWriter.WriteSingle((float)normal.J.Value); binaryWriter.WriteSingle((float)normal.K.Value); // Write vertices var x = (float)vertex1.X; var y = (float)vertex1.Y; var z = (float)vertex1.Z; binaryWriter.WriteSingle(x); binaryWriter.WriteSingle(y); binaryWriter.WriteSingle(z); x = (float)vertex2.X; y = (float)vertex2.Y; z = (float)vertex2.Z; binaryWriter.WriteSingle(x); binaryWriter.WriteSingle(y); binaryWriter.WriteSingle(z); x = (float)vertex3.X; y = (float)vertex3.Y; z = (float)vertex3.Z; binaryWriter.WriteSingle(x); binaryWriter.WriteSingle(y); binaryWriter.WriteSingle(z); // padding to 50 bytes ushort code = 0; binaryWriter.WriteUInt16(code); } } } finally { if (binaryWriter != null) { binaryWriter.Close(); } } }
public void Serialize() { //Console.WriteLine("[Vote System]: Saving Config..."); FileInfo info = new FileInfo("Data\\VoteSystem.cfg"); if (!info.Exists) info.Create().Close(); using(FileStream fs = info.Open(FileMode.Truncate, FileAccess.Write)) { BinaryFileWriter bin = new BinaryFileWriter(fs, true); bin.Write(1); //version //version 1 bin.Write(_DefaultGold); //version 0 bin.Write(_DefaultName); bin.Write(_DefaultURL); bin.Write(_DefaultCoolDown); bin.Close(); } //Console.WriteLine("[Vote System]: Done."); }
private static void Serialize() { if (!Directory.Exists(m_Directory)) Directory.CreateDirectory(m_Directory); GenericWriter writer = new BinaryFileWriter(m_FilePath, true); writer.Write(0);//version writer.Write(m_Messages.Count - 1); for (int i = 1; i < m_Messages.Count; i++) { MotDStruct mds = (MotDStruct)m_Messages[i]; writer.Write(mds.Subject); writer.Write(mds.Body); writer.Write(mds.Links.Count); for (int j = 0; j < mds.Links.Count; j++) writer.Write((string)mds.Links[j]); } writer.Close(); }
private static void EventSink_WorldSave(WorldSaveEventArgs e) { try { if (!Directory.Exists(SaveDirectory)) Directory.CreateDirectory(SaveDirectory); GenericWriter writer = new BinaryFileWriter(new FileStream(PointsFile, FileMode.OpenOrCreate), true); InternalSave(writer); writer.Close(); Console.WriteLine("Onsite Dueling System: DuelPoints saved!"); } catch (Exception ex) { Console.WriteLine("Onsite Dueling System: Save failed!"); Console.WriteLine("Caught an exception: {0}", ex.ToString()); } }
public static void Save() { try { if (!Directory.Exists(General.SavePath)) { Directory.CreateDirectory(General.SavePath); } GenericWriter writer = new BinaryFileWriter(Path.Combine(General.SavePath, "Gumps.bin"), true); writer.Write(0); // version writer.Write(s_ForceMenu); writer.Write(s_ForceInfos.Count); foreach (GumpInfo ginfo in s_ForceInfos.Values) { ginfo.Save(writer); } ArrayList list = new ArrayList(); GumpInfo info; foreach (object o in new ArrayList(s_Infos.Values)) { if (!(o is Hashtable)) { continue; } foreach (object ob in new ArrayList(((Hashtable)o).Values)) { if (!(ob is GumpInfo)) { continue; } info = (GumpInfo)ob; if (info.Mobile != null && info.Mobile.Player && !info.Mobile.Deleted && info.Mobile.Account != null && ((Account)info.Mobile.Account).LastLogin > DateTime.Now - TimeSpan.FromDays(30)) { list.Add(ob); } } } writer.Write(list.Count); foreach (GumpInfo ginfo in list) { ginfo.Save(writer); } writer.Close(); } catch (Exception e) { Errors.Report(General.Local(199)); Console.WriteLine(e.Message); Console.WriteLine(e.Source); Console.WriteLine(e.StackTrace); } }
protected static void SaveMobiles(List<Mobile> moblist) { GenericWriter idx = new BinaryFileWriter(MobileIndexPath, false); GenericWriter tdb = new BinaryFileWriter(MobileTypesPath, false); GenericWriter bin = new BinaryFileWriter(MobileDataPath, true); idx.Write(moblist.Count); foreach (Mobile m in moblist) { long start = bin.Position; idx.Write(m.TypeRef); idx.Write(m.Serial); idx.Write(start); m.Serialize(bin); idx.Write((int) (bin.Position - start)); m.FreeCache(); } tdb.Write(World.MobileTypes.Count); foreach (Type t in World.MobileTypes) { tdb.Write(t.FullName); } idx.Close(); tdb.Close(); bin.Close(); }