Fixes code according to modern code style. Fixes a few expression bugs.
This commit is contained in:
parent
89eea25e5f
commit
970fd563b2
3324 changed files with 441118 additions and 433755 deletions
|
|
@ -20,62 +20,63 @@
|
|||
|
||||
using System.IO;
|
||||
|
||||
namespace Server {
|
||||
public sealed class BinaryMemoryWriter : BinaryFileWriter {
|
||||
private MemoryStream stream;
|
||||
namespace Server
|
||||
{
|
||||
public sealed class BinaryMemoryWriter : BinaryFileWriter
|
||||
{
|
||||
private static byte[] indexBuffer;
|
||||
private MemoryStream stream;
|
||||
|
||||
protected override int BufferSize => 512;
|
||||
public BinaryMemoryWriter()
|
||||
: base(new MemoryStream(512), true)
|
||||
{
|
||||
stream = UnderlyingStream as MemoryStream;
|
||||
}
|
||||
|
||||
public BinaryMemoryWriter()
|
||||
: base( new MemoryStream( 512 ), true ) {
|
||||
stream = UnderlyingStream as MemoryStream;
|
||||
}
|
||||
protected override int BufferSize => 512;
|
||||
|
||||
private static byte[] indexBuffer;
|
||||
public int CommitTo(SequentialFileWriter dataFile, SequentialFileWriter indexFile, int typeCode, int serial)
|
||||
{
|
||||
Flush();
|
||||
|
||||
public int CommitTo( SequentialFileWriter dataFile, SequentialFileWriter indexFile, int typeCode, int serial ) {
|
||||
Flush();
|
||||
byte[] buffer = stream.GetBuffer();
|
||||
int length = (int)stream.Length;
|
||||
|
||||
byte[] buffer = stream.GetBuffer();
|
||||
int length = ( int ) stream.Length;
|
||||
long position = dataFile.Position;
|
||||
|
||||
long position = dataFile.Position;
|
||||
dataFile.Write(buffer, 0, length);
|
||||
|
||||
dataFile.Write( buffer, 0, length );
|
||||
if (indexBuffer == null) indexBuffer = new byte[20];
|
||||
|
||||
if ( indexBuffer == null ) {
|
||||
indexBuffer = new byte[20];
|
||||
}
|
||||
indexBuffer[0] = (byte)typeCode;
|
||||
indexBuffer[1] = (byte)(typeCode >> 8);
|
||||
indexBuffer[2] = (byte)(typeCode >> 16);
|
||||
indexBuffer[3] = (byte)(typeCode >> 24);
|
||||
|
||||
indexBuffer[0] = ( byte ) ( typeCode );
|
||||
indexBuffer[1] = ( byte ) ( typeCode >> 8 );
|
||||
indexBuffer[2] = ( byte ) ( typeCode >> 16 );
|
||||
indexBuffer[3] = ( byte ) ( typeCode >> 24 );
|
||||
indexBuffer[4] = (byte)serial;
|
||||
indexBuffer[5] = (byte)(serial >> 8);
|
||||
indexBuffer[6] = (byte)(serial >> 16);
|
||||
indexBuffer[7] = (byte)(serial >> 24);
|
||||
|
||||
indexBuffer[4] = ( byte ) ( serial );
|
||||
indexBuffer[5] = ( byte ) ( serial >> 8 );
|
||||
indexBuffer[6] = ( byte ) ( serial >> 16 );
|
||||
indexBuffer[7] = ( byte ) ( serial >> 24 );
|
||||
indexBuffer[8] = (byte)position;
|
||||
indexBuffer[9] = (byte)(position >> 8);
|
||||
indexBuffer[10] = (byte)(position >> 16);
|
||||
indexBuffer[11] = (byte)(position >> 24);
|
||||
indexBuffer[12] = (byte)(position >> 32);
|
||||
indexBuffer[13] = (byte)(position >> 40);
|
||||
indexBuffer[14] = (byte)(position >> 48);
|
||||
indexBuffer[15] = (byte)(position >> 56);
|
||||
|
||||
indexBuffer[8] = ( byte ) ( position );
|
||||
indexBuffer[9] = ( byte ) ( position >> 8 );
|
||||
indexBuffer[10] = ( byte ) ( position >> 16 );
|
||||
indexBuffer[11] = ( byte ) ( position >> 24 );
|
||||
indexBuffer[12] = ( byte ) ( position >> 32 );
|
||||
indexBuffer[13] = ( byte ) ( position >> 40 );
|
||||
indexBuffer[14] = ( byte ) ( position >> 48 );
|
||||
indexBuffer[15] = ( byte ) ( position >> 56 );
|
||||
indexBuffer[16] = (byte)length;
|
||||
indexBuffer[17] = (byte)(length >> 8);
|
||||
indexBuffer[18] = (byte)(length >> 16);
|
||||
indexBuffer[19] = (byte)(length >> 24);
|
||||
|
||||
indexBuffer[16] = ( byte ) ( length );
|
||||
indexBuffer[17] = ( byte ) ( length >> 8 );
|
||||
indexBuffer[18] = ( byte ) ( length >> 16 );
|
||||
indexBuffer[19] = ( byte ) ( length >> 24 );
|
||||
indexFile.Write(indexBuffer, 0, indexBuffer.Length);
|
||||
|
||||
indexFile.Write( indexBuffer, 0, indexBuffer.Length );
|
||||
stream.SetLength(0);
|
||||
|
||||
stream.SetLength( 0 );
|
||||
|
||||
return length;
|
||||
}
|
||||
}
|
||||
return length;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -20,31 +20,29 @@
|
|||
|
||||
using System.Threading;
|
||||
|
||||
namespace Server {
|
||||
public sealed class DualSaveStrategy : StandardSaveStrategy {
|
||||
public override string Name => "Dual";
|
||||
namespace Server
|
||||
{
|
||||
public sealed class DualSaveStrategy : StandardSaveStrategy
|
||||
{
|
||||
public override string Name => "Dual";
|
||||
|
||||
public DualSaveStrategy() {
|
||||
}
|
||||
public override void Save(SaveMetrics metrics, bool permitBackgroundWrite)
|
||||
{
|
||||
PermitBackgroundWrite = permitBackgroundWrite;
|
||||
|
||||
public override void Save( SaveMetrics metrics, bool permitBackgroundWrite )
|
||||
{
|
||||
PermitBackgroundWrite = permitBackgroundWrite;
|
||||
Thread saveThread = new Thread(delegate() { SaveItems(metrics); });
|
||||
|
||||
Thread saveThread = new Thread( delegate() {
|
||||
SaveItems(metrics);
|
||||
} );
|
||||
saveThread.Name = "Item Save Subset";
|
||||
saveThread.Start();
|
||||
|
||||
saveThread.Name = "Item Save Subset";
|
||||
saveThread.Start();
|
||||
SaveMobiles(metrics);
|
||||
SaveGuilds(metrics);
|
||||
|
||||
SaveMobiles(metrics);
|
||||
SaveGuilds(metrics);
|
||||
saveThread.Join();
|
||||
|
||||
saveThread.Join();
|
||||
|
||||
if (permitBackgroundWrite && UseSequentialWriters) //If we're permitted to write in the background, but we don't anyways, then notify.
|
||||
World.NotifyDiskWriteComplete();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (permitBackgroundWrite && UseSequentialWriters
|
||||
) //If we're permitted to write in the background, but we don't anyways, then notify.
|
||||
World.NotifyDiskWriteComplete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -20,278 +20,270 @@
|
|||
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using System.Collections.Concurrent;
|
||||
using Server.Guilds;
|
||||
|
||||
namespace Server
|
||||
{
|
||||
public sealed class DynamicSaveStrategy : SaveStrategy
|
||||
{
|
||||
public override string Name => "Dynamic";
|
||||
|
||||
private SaveMetrics _metrics;
|
||||
|
||||
private SequentialFileWriter _itemData, _itemIndex;
|
||||
private SequentialFileWriter _mobileData, _mobileIndex;
|
||||
private SequentialFileWriter _guildData, _guildIndex;
|
||||
|
||||
private ConcurrentBag<Item> _decayBag;
|
||||
|
||||
private BlockingCollection<QueuedMemoryWriter> _itemThreadWriters;
|
||||
private BlockingCollection<QueuedMemoryWriter> _mobileThreadWriters;
|
||||
private BlockingCollection<QueuedMemoryWriter> _guildThreadWriters;
|
||||
|
||||
public DynamicSaveStrategy()
|
||||
{
|
||||
_decayBag = new ConcurrentBag<Item>();
|
||||
_itemThreadWriters = new BlockingCollection<QueuedMemoryWriter>();
|
||||
_mobileThreadWriters = new BlockingCollection<QueuedMemoryWriter>();
|
||||
_guildThreadWriters = new BlockingCollection<QueuedMemoryWriter>();
|
||||
}
|
||||
|
||||
public override void Save(SaveMetrics metrics, bool permitBackgroundWrite)
|
||||
{
|
||||
_metrics = metrics;
|
||||
|
||||
OpenFiles();
|
||||
|
||||
Task[] saveTasks = new Task[3];
|
||||
|
||||
saveTasks[0] = SaveItems();
|
||||
saveTasks[1] = SaveMobiles();
|
||||
saveTasks[2] = SaveGuilds();
|
||||
|
||||
SaveTypeDatabases();
|
||||
public sealed class DynamicSaveStrategy : SaveStrategy
|
||||
{
|
||||
private ConcurrentBag<Item> _decayBag;
|
||||
private SequentialFileWriter _guildData, _guildIndex;
|
||||
private BlockingCollection<QueuedMemoryWriter> _guildThreadWriters;
|
||||
|
||||
private SequentialFileWriter _itemData, _itemIndex;
|
||||
|
||||
private BlockingCollection<QueuedMemoryWriter> _itemThreadWriters;
|
||||
|
||||
private SaveMetrics _metrics;
|
||||
private SequentialFileWriter _mobileData, _mobileIndex;
|
||||
private BlockingCollection<QueuedMemoryWriter> _mobileThreadWriters;
|
||||
|
||||
public DynamicSaveStrategy()
|
||||
{
|
||||
_decayBag = new ConcurrentBag<Item>();
|
||||
_itemThreadWriters = new BlockingCollection<QueuedMemoryWriter>();
|
||||
_mobileThreadWriters = new BlockingCollection<QueuedMemoryWriter>();
|
||||
_guildThreadWriters = new BlockingCollection<QueuedMemoryWriter>();
|
||||
}
|
||||
|
||||
public override string Name => "Dynamic";
|
||||
|
||||
public override void Save(SaveMetrics metrics, bool permitBackgroundWrite)
|
||||
{
|
||||
_metrics = metrics;
|
||||
|
||||
OpenFiles();
|
||||
|
||||
Task[] saveTasks = new Task[3];
|
||||
|
||||
saveTasks[0] = SaveItems();
|
||||
saveTasks[1] = SaveMobiles();
|
||||
saveTasks[2] = SaveGuilds();
|
||||
|
||||
if (permitBackgroundWrite)
|
||||
{
|
||||
//This option makes it finish the writing to disk in the background, continuing even after Save() returns.
|
||||
Task.Factory.ContinueWhenAll(saveTasks, _ =>
|
||||
{
|
||||
CloseFiles();
|
||||
SaveTypeDatabases();
|
||||
|
||||
World.NotifyDiskWriteComplete();
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
Task.WaitAll(saveTasks); //Waits for the completion of all of the tasks(committing to disk)
|
||||
CloseFiles();
|
||||
}
|
||||
}
|
||||
if (permitBackgroundWrite)
|
||||
{
|
||||
//This option makes it finish the writing to disk in the background, continuing even after Save() returns.
|
||||
Task.Factory.ContinueWhenAll(saveTasks, _ =>
|
||||
{
|
||||
CloseFiles();
|
||||
|
||||
private Task StartCommitTask(BlockingCollection<QueuedMemoryWriter> threadWriter, SequentialFileWriter data, SequentialFileWriter index)
|
||||
{
|
||||
Task commitTask = Task.Factory.StartNew(() =>
|
||||
{
|
||||
while (!(threadWriter.IsCompleted))
|
||||
{
|
||||
QueuedMemoryWriter writer;
|
||||
World.NotifyDiskWriteComplete();
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
Task.WaitAll(saveTasks); //Waits for the completion of all of the tasks(committing to disk)
|
||||
CloseFiles();
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
writer = threadWriter.Take();
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
//Per MSDN, it's fine if we're here, successful completion of adding can rarely put us into this state.
|
||||
break;
|
||||
}
|
||||
private Task StartCommitTask(BlockingCollection<QueuedMemoryWriter> threadWriter, SequentialFileWriter data,
|
||||
SequentialFileWriter index)
|
||||
{
|
||||
Task commitTask = Task.Factory.StartNew(() =>
|
||||
{
|
||||
while (!threadWriter.IsCompleted)
|
||||
{
|
||||
QueuedMemoryWriter writer;
|
||||
|
||||
writer.CommitTo(data, index);
|
||||
}
|
||||
});
|
||||
try
|
||||
{
|
||||
writer = threadWriter.Take();
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
//Per MSDN, it's fine if we're here, successful completion of adding can rarely put us into this state.
|
||||
break;
|
||||
}
|
||||
|
||||
return commitTask;
|
||||
}
|
||||
writer.CommitTo(data, index);
|
||||
}
|
||||
});
|
||||
|
||||
private Task SaveItems()
|
||||
{
|
||||
//Start the blocking consumer; this runs in background.
|
||||
Task commitTask = StartCommitTask(_itemThreadWriters, _itemData, _itemIndex);
|
||||
return commitTask;
|
||||
}
|
||||
|
||||
IEnumerable<Item> items = World.Items.Values;
|
||||
private Task SaveItems()
|
||||
{
|
||||
//Start the blocking consumer; this runs in background.
|
||||
Task commitTask = StartCommitTask(_itemThreadWriters, _itemData, _itemIndex);
|
||||
|
||||
//Start the producer.
|
||||
Parallel.ForEach(items, () => new QueuedMemoryWriter(),
|
||||
(Item item, ParallelLoopState state, QueuedMemoryWriter writer) =>
|
||||
{
|
||||
long startPosition = writer.Position;
|
||||
IEnumerable<Item> items = World.Items.Values;
|
||||
|
||||
item.Serialize(writer);
|
||||
//Start the producer.
|
||||
Parallel.ForEach(items, () => new QueuedMemoryWriter(),
|
||||
(item, state, writer) =>
|
||||
{
|
||||
long startPosition = writer.Position;
|
||||
|
||||
int size = (int)(writer.Position - startPosition);
|
||||
item.Serialize(writer);
|
||||
|
||||
writer.QueueForIndex(item, size);
|
||||
int size = (int)(writer.Position - startPosition);
|
||||
|
||||
if (item.Decays && item.Parent == null && item.Map != Map.Internal && DateTime.UtcNow > (item.LastMoved + item.DecayTime))
|
||||
{
|
||||
_decayBag.Add(item);
|
||||
}
|
||||
writer.QueueForIndex(item, size);
|
||||
|
||||
_metrics?.OnItemSaved(size);
|
||||
if (item.Decays && item.Parent == null && item.Map != Map.Internal &&
|
||||
DateTime.UtcNow > item.LastMoved + item.DecayTime) _decayBag.Add(item);
|
||||
|
||||
return writer;
|
||||
},
|
||||
(writer) =>
|
||||
{
|
||||
writer.Flush();
|
||||
_metrics?.OnItemSaved(size);
|
||||
|
||||
_itemThreadWriters.Add(writer);
|
||||
});
|
||||
return writer;
|
||||
},
|
||||
writer =>
|
||||
{
|
||||
writer.Flush();
|
||||
|
||||
_itemThreadWriters.CompleteAdding(); //We only get here after the Parallel.ForEach completes. Lets our task
|
||||
_itemThreadWriters.Add(writer);
|
||||
});
|
||||
|
||||
return commitTask;
|
||||
}
|
||||
_itemThreadWriters.CompleteAdding(); //We only get here after the Parallel.ForEach completes. Lets our task
|
||||
|
||||
private Task SaveMobiles()
|
||||
{
|
||||
//Start the blocking consumer; this runs in background.
|
||||
Task commitTask = StartCommitTask( _mobileThreadWriters, _mobileData, _mobileIndex );
|
||||
return commitTask;
|
||||
}
|
||||
|
||||
IEnumerable<Mobile> mobiles = World.Mobiles.Values;
|
||||
private Task SaveMobiles()
|
||||
{
|
||||
//Start the blocking consumer; this runs in background.
|
||||
Task commitTask = StartCommitTask(_mobileThreadWriters, _mobileData, _mobileIndex);
|
||||
|
||||
//Start the producer.
|
||||
Parallel.ForEach(mobiles, () => new QueuedMemoryWriter(),
|
||||
(Mobile mobile, ParallelLoopState state, QueuedMemoryWriter writer) =>
|
||||
{
|
||||
long startPosition = writer.Position;
|
||||
IEnumerable<Mobile> mobiles = World.Mobiles.Values;
|
||||
|
||||
mobile.Serialize(writer);
|
||||
//Start the producer.
|
||||
Parallel.ForEach(mobiles, () => new QueuedMemoryWriter(),
|
||||
(mobile, state, writer) =>
|
||||
{
|
||||
long startPosition = writer.Position;
|
||||
|
||||
int size = (int)(writer.Position - startPosition);
|
||||
mobile.Serialize(writer);
|
||||
|
||||
writer.QueueForIndex(mobile, size);
|
||||
int size = (int)(writer.Position - startPosition);
|
||||
|
||||
_metrics?.OnMobileSaved(size);
|
||||
writer.QueueForIndex(mobile, size);
|
||||
|
||||
return writer;
|
||||
},
|
||||
(writer) =>
|
||||
{
|
||||
writer.Flush();
|
||||
_metrics?.OnMobileSaved(size);
|
||||
|
||||
_mobileThreadWriters.Add(writer);
|
||||
});
|
||||
return writer;
|
||||
},
|
||||
writer =>
|
||||
{
|
||||
writer.Flush();
|
||||
|
||||
_mobileThreadWriters.CompleteAdding(); //We only get here after the Parallel.ForEach completes. Lets our task tell the consumer that we're done
|
||||
_mobileThreadWriters.Add(writer);
|
||||
});
|
||||
|
||||
return commitTask;
|
||||
}
|
||||
_mobileThreadWriters
|
||||
.CompleteAdding(); //We only get here after the Parallel.ForEach completes. Lets our task tell the consumer that we're done
|
||||
|
||||
private Task SaveGuilds()
|
||||
{
|
||||
//Start the blocking consumer; this runs in background.
|
||||
Task commitTask = StartCommitTask(_guildThreadWriters, _guildData, _guildIndex);
|
||||
return commitTask;
|
||||
}
|
||||
|
||||
IEnumerable<BaseGuild> guilds = BaseGuild.List.Values;
|
||||
private Task SaveGuilds()
|
||||
{
|
||||
//Start the blocking consumer; this runs in background.
|
||||
Task commitTask = StartCommitTask(_guildThreadWriters, _guildData, _guildIndex);
|
||||
|
||||
//Start the producer.
|
||||
Parallel.ForEach(guilds, () => new QueuedMemoryWriter(),
|
||||
(BaseGuild guild, ParallelLoopState state, QueuedMemoryWriter writer) =>
|
||||
{
|
||||
long startPosition = writer.Position;
|
||||
IEnumerable<BaseGuild> guilds = BaseGuild.List.Values;
|
||||
|
||||
guild.Serialize(writer);
|
||||
//Start the producer.
|
||||
Parallel.ForEach(guilds, () => new QueuedMemoryWriter(),
|
||||
(guild, state, writer) =>
|
||||
{
|
||||
long startPosition = writer.Position;
|
||||
|
||||
int size = (int)(writer.Position - startPosition );
|
||||
guild.Serialize(writer);
|
||||
|
||||
writer.QueueForIndex(guild, size);
|
||||
int size = (int)(writer.Position - startPosition);
|
||||
|
||||
_metrics?.OnGuildSaved(size);
|
||||
writer.QueueForIndex(guild, size);
|
||||
|
||||
return writer;
|
||||
},
|
||||
(writer) =>
|
||||
{
|
||||
writer.Flush();
|
||||
_metrics?.OnGuildSaved(size);
|
||||
|
||||
_guildThreadWriters.Add(writer);
|
||||
});
|
||||
return writer;
|
||||
},
|
||||
writer =>
|
||||
{
|
||||
writer.Flush();
|
||||
|
||||
_guildThreadWriters.CompleteAdding(); //We only get here after the Parallel.ForEach completes. Lets our task
|
||||
_guildThreadWriters.Add(writer);
|
||||
});
|
||||
|
||||
return commitTask;
|
||||
}
|
||||
_guildThreadWriters.CompleteAdding(); //We only get here after the Parallel.ForEach completes. Lets our task
|
||||
|
||||
public override void ProcessDecay()
|
||||
{
|
||||
Item item;
|
||||
return commitTask;
|
||||
}
|
||||
|
||||
while( _decayBag.TryTake( out item ) )
|
||||
{
|
||||
if ( item.OnDecay() )
|
||||
{
|
||||
item.Delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
public override void ProcessDecay()
|
||||
{
|
||||
Item item;
|
||||
|
||||
private void OpenFiles()
|
||||
{
|
||||
_itemData = new SequentialFileWriter(World.ItemDataPath, _metrics);
|
||||
_itemIndex = new SequentialFileWriter(World.ItemIndexPath, _metrics);
|
||||
while (_decayBag.TryTake(out item))
|
||||
if (item.OnDecay())
|
||||
item.Delete();
|
||||
}
|
||||
|
||||
_mobileData = new SequentialFileWriter(World.MobileDataPath, _metrics);
|
||||
_mobileIndex = new SequentialFileWriter(World.MobileIndexPath, _metrics);
|
||||
private void OpenFiles()
|
||||
{
|
||||
_itemData = new SequentialFileWriter(World.ItemDataPath, _metrics);
|
||||
_itemIndex = new SequentialFileWriter(World.ItemIndexPath, _metrics);
|
||||
|
||||
_guildData = new SequentialFileWriter(World.GuildDataPath, _metrics);
|
||||
_guildIndex = new SequentialFileWriter(World.GuildIndexPath, _metrics);
|
||||
_mobileData = new SequentialFileWriter(World.MobileDataPath, _metrics);
|
||||
_mobileIndex = new SequentialFileWriter(World.MobileIndexPath, _metrics);
|
||||
|
||||
WriteCount(_itemIndex, World.Items.Count);
|
||||
WriteCount(_mobileIndex, World.Mobiles.Count);
|
||||
WriteCount(_guildIndex, BaseGuild.List.Count);
|
||||
}
|
||||
_guildData = new SequentialFileWriter(World.GuildDataPath, _metrics);
|
||||
_guildIndex = new SequentialFileWriter(World.GuildIndexPath, _metrics);
|
||||
|
||||
private void CloseFiles()
|
||||
{
|
||||
_itemData.Close();
|
||||
_itemIndex.Close();
|
||||
WriteCount(_itemIndex, World.Items.Count);
|
||||
WriteCount(_mobileIndex, World.Mobiles.Count);
|
||||
WriteCount(_guildIndex, BaseGuild.List.Count);
|
||||
}
|
||||
|
||||
_mobileData.Close();
|
||||
_mobileIndex.Close();
|
||||
private void CloseFiles()
|
||||
{
|
||||
_itemData.Close();
|
||||
_itemIndex.Close();
|
||||
|
||||
_guildData.Close();
|
||||
_guildIndex.Close();
|
||||
}
|
||||
_mobileData.Close();
|
||||
_mobileIndex.Close();
|
||||
|
||||
private void WriteCount(SequentialFileWriter indexFile, int count)
|
||||
{
|
||||
//Equiv to GenericWriter.Write( (int)count );
|
||||
byte[] buffer = new byte[4];
|
||||
_guildData.Close();
|
||||
_guildIndex.Close();
|
||||
}
|
||||
|
||||
buffer[0] = (byte)(count);
|
||||
buffer[1] = (byte)(count >> 8);
|
||||
buffer[2] = (byte)(count >> 16);
|
||||
buffer[3] = (byte)(count >> 24);
|
||||
private void WriteCount(SequentialFileWriter indexFile, int count)
|
||||
{
|
||||
//Equiv to GenericWriter.Write( (int)count );
|
||||
byte[] buffer = new byte[4];
|
||||
|
||||
indexFile.Write(buffer, 0, buffer.Length);
|
||||
}
|
||||
buffer[0] = (byte)count;
|
||||
buffer[1] = (byte)(count >> 8);
|
||||
buffer[2] = (byte)(count >> 16);
|
||||
buffer[3] = (byte)(count >> 24);
|
||||
|
||||
private void SaveTypeDatabases()
|
||||
{
|
||||
SaveTypeDatabase(World.ItemTypesPath, World.m_ItemTypes);
|
||||
SaveTypeDatabase(World.MobileTypesPath, World.m_MobileTypes);
|
||||
}
|
||||
indexFile.Write(buffer, 0, buffer.Length);
|
||||
}
|
||||
|
||||
private void SaveTypeDatabase(string path, List<Type> types)
|
||||
{
|
||||
BinaryFileWriter bfw = new BinaryFileWriter(path, false);
|
||||
private void SaveTypeDatabases()
|
||||
{
|
||||
SaveTypeDatabase(World.ItemTypesPath, World.m_ItemTypes);
|
||||
SaveTypeDatabase(World.MobileTypesPath, World.m_MobileTypes);
|
||||
}
|
||||
|
||||
bfw.Write(types.Count);
|
||||
private void SaveTypeDatabase(string path, List<Type> types)
|
||||
{
|
||||
BinaryFileWriter bfw = new BinaryFileWriter(path, false);
|
||||
|
||||
foreach (Type type in types)
|
||||
{
|
||||
bfw.Write(type.FullName);
|
||||
}
|
||||
bfw.Write(types.Count);
|
||||
|
||||
bfw.Flush();
|
||||
foreach (Type type in types) bfw.Write(type.FullName);
|
||||
|
||||
bfw.Close();
|
||||
}
|
||||
}
|
||||
bfw.Flush();
|
||||
|
||||
}
|
||||
bfw.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -24,83 +24,89 @@ using System.IO;
|
|||
#if !MONO
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
#endif
|
||||
|
||||
namespace Server {
|
||||
public static class FileOperations {
|
||||
public const int KB = 1024;
|
||||
public const int MB = 1024 * KB;
|
||||
namespace Server
|
||||
{
|
||||
public static class FileOperations
|
||||
{
|
||||
public const int KB = 1024;
|
||||
public const int MB = 1024 * KB;
|
||||
|
||||
#if !MONO
|
||||
private const FileOptions NoBuffering = ( FileOptions ) 0x20000000;
|
||||
public static int BufferSize{ get; set; } = 1 * MB;
|
||||
|
||||
internal static class UnsafeNativeMethods {
|
||||
[DllImport("Kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
internal static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, IntPtr securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
|
||||
}
|
||||
#endif
|
||||
public static int Concurrency{ get; set; } = 1;
|
||||
|
||||
public static int BufferSize { get; set; } = 1 * MB;
|
||||
public static bool Unbuffered{ get; set; } = true;
|
||||
|
||||
public static int Concurrency { get; set; } = 1;
|
||||
public static bool AreSynchronous => Concurrency < 1;
|
||||
|
||||
public static bool Unbuffered { get; set; } = true;
|
||||
public static bool AreAsynchronous => Concurrency > 0;
|
||||
|
||||
public static bool AreSynchronous => ( Concurrency < 1 );
|
||||
public static FileStream OpenSequentialStream(string path, FileMode mode, FileAccess access, FileShare share)
|
||||
{
|
||||
FileOptions options = FileOptions.SequentialScan;
|
||||
|
||||
public static bool AreAsynchronous => ( Concurrency > 0 );
|
||||
|
||||
public static FileStream OpenSequentialStream( string path, FileMode mode, FileAccess access, FileShare share ) {
|
||||
FileOptions options = FileOptions.SequentialScan;
|
||||
|
||||
if ( Concurrency > 0 ) {
|
||||
options |= FileOptions.Asynchronous;
|
||||
}
|
||||
if (Concurrency > 0) options |= FileOptions.Asynchronous;
|
||||
|
||||
#if MONO
|
||||
return new FileStream( path, mode, access, share, bufferSize, options );
|
||||
#else
|
||||
if ( Unbuffered ) {
|
||||
options |= NoBuffering;
|
||||
} else {
|
||||
return new FileStream( path, mode, access, share, BufferSize, options );
|
||||
}
|
||||
if (Unbuffered)
|
||||
options |= NoBuffering;
|
||||
else
|
||||
return new FileStream(path, mode, access, share, BufferSize, options);
|
||||
|
||||
SafeFileHandle fileHandle = UnsafeNativeMethods.CreateFile(path, (int)access, share, IntPtr.Zero, mode, (int)options, IntPtr.Zero);
|
||||
SafeFileHandle fileHandle =
|
||||
UnsafeNativeMethods.CreateFile(path, (int)access, share, IntPtr.Zero, mode, (int)options, IntPtr.Zero);
|
||||
|
||||
if ( fileHandle.IsInvalid ) {
|
||||
throw new IOException();
|
||||
}
|
||||
if (fileHandle.IsInvalid) throw new IOException();
|
||||
|
||||
return new UnbufferedFileStream( fileHandle, access, BufferSize, ( Concurrency > 0 ) );
|
||||
return new UnbufferedFileStream(fileHandle, access, BufferSize, Concurrency > 0);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#if !MONO
|
||||
private class UnbufferedFileStream : FileStream {
|
||||
private SafeFileHandle fileHandle;
|
||||
private class UnbufferedFileStream : FileStream
|
||||
{
|
||||
private SafeFileHandle fileHandle;
|
||||
|
||||
public UnbufferedFileStream( SafeFileHandle fileHandle, FileAccess access, int bufferSize, bool isAsync )
|
||||
: base( fileHandle, access, bufferSize, isAsync ) {
|
||||
this.fileHandle = fileHandle;
|
||||
}
|
||||
public UnbufferedFileStream(SafeFileHandle fileHandle, FileAccess access, int bufferSize, bool isAsync)
|
||||
: base(fileHandle, access, bufferSize, isAsync)
|
||||
{
|
||||
this.fileHandle = fileHandle;
|
||||
}
|
||||
|
||||
public override void Write( byte[] array, int offset, int count ) {
|
||||
base.Write( array, offset, BufferSize );
|
||||
}
|
||||
public override void Write(byte[] array, int offset, int count)
|
||||
{
|
||||
base.Write(array, offset, BufferSize);
|
||||
}
|
||||
|
||||
public override IAsyncResult BeginWrite( byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject ) {
|
||||
return base.BeginWrite( array, offset, BufferSize, userCallback, stateObject );
|
||||
}
|
||||
public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback userCallback,
|
||||
object stateObject)
|
||||
{
|
||||
return base.BeginWrite(array, offset, BufferSize, userCallback, stateObject);
|
||||
}
|
||||
|
||||
protected override void Dispose( bool disposing ) {
|
||||
if ( !fileHandle.IsClosed ) {
|
||||
fileHandle.Close();
|
||||
}
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (!fileHandle.IsClosed) fileHandle.Close();
|
||||
|
||||
base.Dispose( disposing );
|
||||
}
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#if !MONO
|
||||
private const FileOptions NoBuffering = (FileOptions)0x20000000;
|
||||
|
||||
internal static class UnsafeNativeMethods
|
||||
{
|
||||
[DllImport("Kernel32", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
internal static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode,
|
||||
IntPtr securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
|
@ -23,212 +23,210 @@ using System.Collections.Generic;
|
|||
using System.Threading;
|
||||
using Server.Network;
|
||||
|
||||
namespace Server {
|
||||
public delegate void FileCommitCallback( FileQueue.Chunk chunk );
|
||||
namespace Server
|
||||
{
|
||||
public delegate void FileCommitCallback(FileQueue.Chunk chunk);
|
||||
|
||||
public sealed class FileQueue : IDisposable {
|
||||
public sealed class Chunk {
|
||||
private FileQueue owner;
|
||||
private int slot;
|
||||
public sealed class FileQueue : IDisposable
|
||||
{
|
||||
private static int bufferSize;
|
||||
private static BufferPool bufferPool;
|
||||
|
||||
private int offset;
|
||||
private Chunk[] active;
|
||||
private int activeCount;
|
||||
private Page buffered;
|
||||
|
||||
public byte[] Buffer { get; }
|
||||
private FileCommitCallback callback;
|
||||
|
||||
public int Offset => 0;
|
||||
private ManualResetEvent idle;
|
||||
|
||||
public int Size { get; }
|
||||
private Queue<Page> pending;
|
||||
|
||||
public Chunk( FileQueue owner, int slot, byte[] buffer, int offset, int size ) {
|
||||
this.owner = owner;
|
||||
this.slot = slot;
|
||||
private object syncRoot;
|
||||
|
||||
this.Buffer = buffer;
|
||||
this.offset = offset;
|
||||
this.Size = size;
|
||||
}
|
||||
static FileQueue()
|
||||
{
|
||||
bufferSize = FileOperations.BufferSize;
|
||||
bufferPool = new BufferPool("File Buffers", 64, bufferSize);
|
||||
}
|
||||
|
||||
public void Commit() {
|
||||
owner.Commit( this, slot );
|
||||
}
|
||||
}
|
||||
public FileQueue(int concurrentWrites, FileCommitCallback callback)
|
||||
{
|
||||
if (concurrentWrites < 1) throw new ArgumentOutOfRangeException("concurrentWrites");
|
||||
|
||||
private struct Page {
|
||||
public byte[] buffer;
|
||||
public int length;
|
||||
}
|
||||
if (bufferSize < 1) throw new ArgumentOutOfRangeException("bufferSize");
|
||||
if (callback == null) throw new ArgumentNullException("callback");
|
||||
|
||||
private static int bufferSize;
|
||||
private static BufferPool bufferPool;
|
||||
syncRoot = new object();
|
||||
|
||||
static FileQueue() {
|
||||
bufferSize = FileOperations.BufferSize;
|
||||
bufferPool = new BufferPool( "File Buffers", 64, bufferSize );
|
||||
}
|
||||
active = new Chunk[concurrentWrites];
|
||||
pending = new Queue<Page>();
|
||||
|
||||
private object syncRoot;
|
||||
this.callback = callback;
|
||||
|
||||
private Chunk[] active;
|
||||
private int activeCount;
|
||||
idle = new ManualResetEvent(true);
|
||||
}
|
||||
|
||||
private Queue<Page> pending;
|
||||
private Page buffered;
|
||||
public long Position{ get; private set; }
|
||||
|
||||
private FileCommitCallback callback;
|
||||
public void Dispose()
|
||||
{
|
||||
if (idle != null)
|
||||
{
|
||||
idle.Close();
|
||||
idle = null;
|
||||
}
|
||||
}
|
||||
|
||||
private ManualResetEvent idle;
|
||||
private void Append(Page page)
|
||||
{
|
||||
lock (syncRoot)
|
||||
{
|
||||
if (activeCount == 0) idle.Reset();
|
||||
|
||||
public long Position { get; private set; }
|
||||
++activeCount;
|
||||
|
||||
public FileQueue( int concurrentWrites, FileCommitCallback callback ) {
|
||||
if ( concurrentWrites < 1 ) {
|
||||
throw new ArgumentOutOfRangeException( "concurrentWrites" );
|
||||
}
|
||||
for (int slot = 0; slot < active.Length; ++slot)
|
||||
if (active[slot] == null)
|
||||
{
|
||||
active[slot] = new Chunk(this, slot, page.buffer, 0, page.length);
|
||||
|
||||
if ( bufferSize < 1 ) {
|
||||
throw new ArgumentOutOfRangeException( "bufferSize" );
|
||||
}
|
||||
if ( callback == null ) {
|
||||
throw new ArgumentNullException( "callback" );
|
||||
}
|
||||
callback(active[slot]);
|
||||
|
||||
syncRoot = new object();
|
||||
return;
|
||||
}
|
||||
|
||||
active = new Chunk[concurrentWrites];
|
||||
pending = new Queue<Page>();
|
||||
pending.Enqueue(page);
|
||||
}
|
||||
}
|
||||
|
||||
this.callback = callback;
|
||||
public void Flush()
|
||||
{
|
||||
if (buffered.buffer != null)
|
||||
{
|
||||
Append(buffered);
|
||||
|
||||
idle = new ManualResetEvent( true );
|
||||
}
|
||||
buffered.buffer = null;
|
||||
buffered.length = 0;
|
||||
}
|
||||
|
||||
private void Append( Page page ) {
|
||||
lock ( syncRoot ) {
|
||||
if ( activeCount == 0 ) {
|
||||
idle.Reset();
|
||||
}
|
||||
/*lock ( syncRoot ) {
|
||||
if ( pending.Count > 0 ) {
|
||||
idle.Reset();
|
||||
}
|
||||
|
||||
++activeCount;
|
||||
for ( int slot = 0; slot < active.Length && pending.Count > 0; ++slot ) {
|
||||
if ( active[slot] == null ) {
|
||||
Page page = pending.Dequeue();
|
||||
|
||||
for ( int slot = 0; slot < active.Length; ++slot ) {
|
||||
if ( active[slot] == null ) {
|
||||
active[slot] = new Chunk( this, slot, page.buffer, 0, page.length );
|
||||
active[slot] = new Chunk( this, slot, page.buffer, 0, page.length );
|
||||
|
||||
callback( active[slot] );
|
||||
++activeCount;
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
callback( active[slot] );
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
pending.Enqueue( page );
|
||||
}
|
||||
}
|
||||
idle.WaitOne();
|
||||
}
|
||||
|
||||
public void Dispose() {
|
||||
if ( idle != null ) {
|
||||
idle.Close();
|
||||
idle = null;
|
||||
}
|
||||
}
|
||||
private void Commit(Chunk chunk, int slot)
|
||||
{
|
||||
if (slot < 0 || slot >= active.Length) throw new ArgumentOutOfRangeException("slot");
|
||||
|
||||
public void Flush() {
|
||||
if ( buffered.buffer != null ) {
|
||||
Append( buffered );
|
||||
lock (syncRoot)
|
||||
{
|
||||
if (active[slot] != chunk) throw new ArgumentException();
|
||||
|
||||
buffered.buffer = null;
|
||||
buffered.length = 0;
|
||||
}
|
||||
bufferPool.ReleaseBuffer(chunk.Buffer);
|
||||
|
||||
/*lock ( syncRoot ) {
|
||||
if ( pending.Count > 0 ) {
|
||||
idle.Reset();
|
||||
}
|
||||
if (pending.Count > 0)
|
||||
{
|
||||
Page page = pending.Dequeue();
|
||||
|
||||
for ( int slot = 0; slot < active.Length && pending.Count > 0; ++slot ) {
|
||||
if ( active[slot] == null ) {
|
||||
Page page = pending.Dequeue();
|
||||
active[slot] = new Chunk(this, slot, page.buffer, 0, page.length);
|
||||
|
||||
active[slot] = new Chunk( this, slot, page.buffer, 0, page.length );
|
||||
callback(active[slot]);
|
||||
}
|
||||
else
|
||||
{
|
||||
active[slot] = null;
|
||||
}
|
||||
|
||||
++activeCount;
|
||||
--activeCount;
|
||||
|
||||
callback( active[slot] );
|
||||
}
|
||||
}
|
||||
}*/
|
||||
if (activeCount == 0) idle.Set();
|
||||
}
|
||||
}
|
||||
|
||||
idle.WaitOne();
|
||||
}
|
||||
public void Enqueue(byte[] buffer, int offset, int size)
|
||||
{
|
||||
if (buffer == null) throw new ArgumentNullException("buffer");
|
||||
|
||||
private void Commit( Chunk chunk, int slot ) {
|
||||
if ( slot < 0 || slot >= active.Length ) {
|
||||
throw new ArgumentOutOfRangeException( "slot" );
|
||||
}
|
||||
if (offset < 0) throw new ArgumentOutOfRangeException("offset");
|
||||
if (size < 0) throw new ArgumentOutOfRangeException("size");
|
||||
if (buffer.Length - offset < size) throw new ArgumentException();
|
||||
|
||||
lock ( syncRoot ) {
|
||||
if ( active[slot] != chunk ) {
|
||||
throw new ArgumentException();
|
||||
}
|
||||
Position += size;
|
||||
|
||||
bufferPool.ReleaseBuffer( chunk.Buffer );
|
||||
while (size > 0)
|
||||
{
|
||||
if (buffered.buffer == null) buffered.buffer = bufferPool.AcquireBuffer();
|
||||
|
||||
if ( pending.Count > 0 ) {
|
||||
Page page = pending.Dequeue();
|
||||
byte[] page = buffered.buffer; // buffer page
|
||||
int pageSpace = page.Length - buffered.length; // available bytes in page
|
||||
int byteCount = size > pageSpace ? pageSpace : size; // how many bytes we can copy over
|
||||
|
||||
active[slot] = new Chunk( this, slot, page.buffer, 0, page.length );
|
||||
Buffer.BlockCopy(buffer, offset, page, buffered.length, byteCount);
|
||||
|
||||
callback( active[slot] );
|
||||
} else {
|
||||
active[slot] = null;
|
||||
}
|
||||
buffered.length += byteCount;
|
||||
offset += byteCount;
|
||||
size -= byteCount;
|
||||
|
||||
--activeCount;
|
||||
if (buffered.length == page.Length)
|
||||
{
|
||||
// page full
|
||||
Append(buffered);
|
||||
|
||||
if ( activeCount == 0 ) {
|
||||
idle.Set();
|
||||
}
|
||||
}
|
||||
}
|
||||
buffered.buffer = null;
|
||||
buffered.length = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Enqueue( byte[] buffer, int offset, int size ) {
|
||||
if ( buffer == null ) {
|
||||
throw new ArgumentNullException( "buffer" );
|
||||
}
|
||||
public sealed class Chunk
|
||||
{
|
||||
private int offset;
|
||||
private FileQueue owner;
|
||||
private int slot;
|
||||
|
||||
if ( offset < 0 ) {
|
||||
throw new ArgumentOutOfRangeException( "offset" );
|
||||
}
|
||||
if ( size < 0 ) {
|
||||
throw new ArgumentOutOfRangeException( "size" );
|
||||
}
|
||||
if ( ( buffer.Length - offset ) < size ) {
|
||||
throw new ArgumentException();
|
||||
}
|
||||
public Chunk(FileQueue owner, int slot, byte[] buffer, int offset, int size)
|
||||
{
|
||||
this.owner = owner;
|
||||
this.slot = slot;
|
||||
|
||||
Position += size;
|
||||
Buffer = buffer;
|
||||
this.offset = offset;
|
||||
Size = size;
|
||||
}
|
||||
|
||||
while ( size > 0 ) {
|
||||
if ( buffered.buffer == null ) { // nothing yet buffered
|
||||
buffered.buffer = bufferPool.AcquireBuffer();
|
||||
}
|
||||
public byte[] Buffer{ get; }
|
||||
|
||||
byte[] page = buffered.buffer; // buffer page
|
||||
int pageSpace = page.Length - buffered.length; // available bytes in page
|
||||
int byteCount = ( size > pageSpace ? pageSpace : size ); // how many bytes we can copy over
|
||||
public int Offset => 0;
|
||||
|
||||
Buffer.BlockCopy( buffer, offset, page, buffered.length, byteCount );
|
||||
public int Size{ get; }
|
||||
|
||||
buffered.length += byteCount;
|
||||
offset += byteCount;
|
||||
size -= byteCount;
|
||||
public void Commit()
|
||||
{
|
||||
owner.Commit(this, slot);
|
||||
}
|
||||
}
|
||||
|
||||
if ( buffered.length == page.Length ) { // page full
|
||||
Append( buffered );
|
||||
|
||||
buffered.buffer = null;
|
||||
buffered.length = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private struct Page
|
||||
{
|
||||
public byte[] buffer;
|
||||
public int length;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -24,299 +24,312 @@ using System.Collections.Generic;
|
|||
using System.Threading;
|
||||
using Server.Guilds;
|
||||
|
||||
namespace Server {
|
||||
public sealed class ParallelSaveStrategy : SaveStrategy {
|
||||
public override string Name => "Parallel";
|
||||
namespace Server
|
||||
{
|
||||
public sealed class ParallelSaveStrategy : SaveStrategy
|
||||
{
|
||||
private Queue<Item> _decayQueue;
|
||||
|
||||
private int processorCount;
|
||||
private Consumer[] consumers;
|
||||
private int cycle;
|
||||
|
||||
public ParallelSaveStrategy( int processorCount ) {
|
||||
this.processorCount = processorCount;
|
||||
private bool finished;
|
||||
private SequentialFileWriter guildData, guildIndex;
|
||||
|
||||
_decayQueue = new Queue<Item>();
|
||||
}
|
||||
private SequentialFileWriter itemData, itemIndex;
|
||||
|
||||
private int GetThreadCount() {
|
||||
return processorCount - 1;
|
||||
}
|
||||
private SaveMetrics metrics;
|
||||
private SequentialFileWriter mobileData, mobileIndex;
|
||||
|
||||
private SaveMetrics metrics;
|
||||
private int processorCount;
|
||||
|
||||
private SequentialFileWriter itemData, itemIndex;
|
||||
private SequentialFileWriter mobileData, mobileIndex;
|
||||
private SequentialFileWriter guildData, guildIndex;
|
||||
public ParallelSaveStrategy(int processorCount)
|
||||
{
|
||||
this.processorCount = processorCount;
|
||||
|
||||
private Queue<Item> _decayQueue;
|
||||
_decayQueue = new Queue<Item>();
|
||||
}
|
||||
|
||||
private Consumer[] consumers;
|
||||
private int cycle;
|
||||
public override string Name => "Parallel";
|
||||
|
||||
private bool finished;
|
||||
private int GetThreadCount()
|
||||
{
|
||||
return processorCount - 1;
|
||||
}
|
||||
|
||||
public override void Save(SaveMetrics metrics, bool permitBackgroundWrite)
|
||||
{
|
||||
this.metrics = metrics;
|
||||
public override void Save(SaveMetrics metrics, bool permitBackgroundWrite)
|
||||
{
|
||||
this.metrics = metrics;
|
||||
|
||||
OpenFiles();
|
||||
OpenFiles();
|
||||
|
||||
consumers = new Consumer[GetThreadCount()];
|
||||
consumers = new Consumer[GetThreadCount()];
|
||||
|
||||
for ( int i = 0; i < consumers.Length; ++i ) {
|
||||
consumers[i] = new Consumer( this, 256 );
|
||||
}
|
||||
for (int i = 0; i < consumers.Length; ++i) consumers[i] = new Consumer(this, 256);
|
||||
|
||||
IEnumerable<ISerializable> collection = new Producer();
|
||||
IEnumerable<ISerializable> collection = new Producer();
|
||||
|
||||
foreach ( ISerializable value in collection ) {
|
||||
while ( !Enqueue( value ) ) {
|
||||
if ( !Commit() ) {
|
||||
Thread.Sleep( 0 );
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (ISerializable value in collection)
|
||||
while (!Enqueue(value))
|
||||
if (!Commit())
|
||||
Thread.Sleep(0);
|
||||
|
||||
finished = true;
|
||||
finished = true;
|
||||
|
||||
SaveTypeDatabases();
|
||||
SaveTypeDatabases();
|
||||
|
||||
WaitHandle.WaitAll(
|
||||
Array.ConvertAll<Consumer, WaitHandle>(
|
||||
consumers,
|
||||
delegate( Consumer input ) {
|
||||
return input.completionEvent;
|
||||
}
|
||||
)
|
||||
);
|
||||
WaitHandle.WaitAll(
|
||||
Array.ConvertAll<Consumer, WaitHandle>(
|
||||
consumers,
|
||||
delegate(Consumer input) { return input.completionEvent; }
|
||||
)
|
||||
);
|
||||
|
||||
Commit();
|
||||
Commit();
|
||||
|
||||
CloseFiles();
|
||||
}
|
||||
CloseFiles();
|
||||
}
|
||||
|
||||
public override void ProcessDecay() {
|
||||
while ( _decayQueue.Count > 0 ) {
|
||||
Item item = _decayQueue.Dequeue();
|
||||
public override void ProcessDecay()
|
||||
{
|
||||
while (_decayQueue.Count > 0)
|
||||
{
|
||||
Item item = _decayQueue.Dequeue();
|
||||
|
||||
if ( item.OnDecay() ) {
|
||||
item.Delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (item.OnDecay()) item.Delete();
|
||||
}
|
||||
}
|
||||
|
||||
private void SaveTypeDatabases() {
|
||||
SaveTypeDatabase( World.ItemTypesPath, World.m_ItemTypes );
|
||||
SaveTypeDatabase( World.MobileTypesPath, World.m_MobileTypes );
|
||||
}
|
||||
private void SaveTypeDatabases()
|
||||
{
|
||||
SaveTypeDatabase(World.ItemTypesPath, World.m_ItemTypes);
|
||||
SaveTypeDatabase(World.MobileTypesPath, World.m_MobileTypes);
|
||||
}
|
||||
|
||||
private void SaveTypeDatabase( string path, List<Type> types ) {
|
||||
BinaryFileWriter bfw = new BinaryFileWriter( path, false );
|
||||
private void SaveTypeDatabase(string path, List<Type> types)
|
||||
{
|
||||
BinaryFileWriter bfw = new BinaryFileWriter(path, false);
|
||||
|
||||
bfw.Write( types.Count );
|
||||
bfw.Write(types.Count);
|
||||
|
||||
foreach ( Type type in types ) {
|
||||
bfw.Write( type.FullName );
|
||||
}
|
||||
foreach (Type type in types) bfw.Write(type.FullName);
|
||||
|
||||
bfw.Flush();
|
||||
bfw.Flush();
|
||||
|
||||
bfw.Close();
|
||||
}
|
||||
bfw.Close();
|
||||
}
|
||||
|
||||
private void OpenFiles() {
|
||||
itemData = new SequentialFileWriter( World.ItemDataPath, metrics );
|
||||
itemIndex = new SequentialFileWriter( World.ItemIndexPath, metrics );
|
||||
private void OpenFiles()
|
||||
{
|
||||
itemData = new SequentialFileWriter(World.ItemDataPath, metrics);
|
||||
itemIndex = new SequentialFileWriter(World.ItemIndexPath, metrics);
|
||||
|
||||
mobileData = new SequentialFileWriter( World.MobileDataPath, metrics );
|
||||
mobileIndex = new SequentialFileWriter( World.MobileIndexPath, metrics );
|
||||
mobileData = new SequentialFileWriter(World.MobileDataPath, metrics);
|
||||
mobileIndex = new SequentialFileWriter(World.MobileIndexPath, metrics);
|
||||
|
||||
guildData = new SequentialFileWriter( World.GuildDataPath, metrics );
|
||||
guildIndex = new SequentialFileWriter( World.GuildIndexPath, metrics );
|
||||
guildData = new SequentialFileWriter(World.GuildDataPath, metrics);
|
||||
guildIndex = new SequentialFileWriter(World.GuildIndexPath, metrics);
|
||||
|
||||
WriteCount( itemIndex, World.Items.Count );
|
||||
WriteCount( mobileIndex, World.Mobiles.Count );
|
||||
WriteCount( guildIndex, BaseGuild.List.Count );
|
||||
}
|
||||
WriteCount(itemIndex, World.Items.Count);
|
||||
WriteCount(mobileIndex, World.Mobiles.Count);
|
||||
WriteCount(guildIndex, BaseGuild.List.Count);
|
||||
}
|
||||
|
||||
private void WriteCount( SequentialFileWriter indexFile, int count ) {
|
||||
byte[] buffer = new byte[4];
|
||||
private void WriteCount(SequentialFileWriter indexFile, int count)
|
||||
{
|
||||
byte[] buffer = new byte[4];
|
||||
|
||||
buffer[0] = ( byte ) ( count );
|
||||
buffer[1] = ( byte ) ( count >> 8 );
|
||||
buffer[2] = ( byte ) ( count >> 16 );
|
||||
buffer[3] = ( byte ) ( count >> 24 );
|
||||
buffer[0] = (byte)count;
|
||||
buffer[1] = (byte)(count >> 8);
|
||||
buffer[2] = (byte)(count >> 16);
|
||||
buffer[3] = (byte)(count >> 24);
|
||||
|
||||
indexFile.Write( buffer, 0, buffer.Length );
|
||||
}
|
||||
indexFile.Write(buffer, 0, buffer.Length);
|
||||
}
|
||||
|
||||
private void CloseFiles() {
|
||||
itemData.Close();
|
||||
itemIndex.Close();
|
||||
private void CloseFiles()
|
||||
{
|
||||
itemData.Close();
|
||||
itemIndex.Close();
|
||||
|
||||
mobileData.Close();
|
||||
mobileIndex.Close();
|
||||
mobileData.Close();
|
||||
mobileIndex.Close();
|
||||
|
||||
guildData.Close();
|
||||
guildIndex.Close();
|
||||
guildData.Close();
|
||||
guildIndex.Close();
|
||||
|
||||
World.NotifyDiskWriteComplete();
|
||||
}
|
||||
World.NotifyDiskWriteComplete();
|
||||
}
|
||||
|
||||
private void OnSerialized( ConsumableEntry entry ) {
|
||||
ISerializable value = entry.value;
|
||||
BinaryMemoryWriter writer = entry.writer;
|
||||
private void OnSerialized(ConsumableEntry entry)
|
||||
{
|
||||
ISerializable value = entry.value;
|
||||
BinaryMemoryWriter writer = entry.writer;
|
||||
|
||||
if ( value is Item item )
|
||||
Save( item, writer );
|
||||
else if ( value is Mobile mob )
|
||||
Save( mob, writer );
|
||||
else if ( value is BaseGuild guild )
|
||||
Save( guild, writer );
|
||||
}
|
||||
if (value is Item item)
|
||||
Save(item, writer);
|
||||
else if (value is Mobile mob)
|
||||
Save(mob, writer);
|
||||
else if (value is BaseGuild guild)
|
||||
Save(guild, writer);
|
||||
}
|
||||
|
||||
private void Save( Item item, BinaryMemoryWriter writer ) {
|
||||
int length = writer.CommitTo( itemData, itemIndex, item.m_TypeRef, item.Serial );
|
||||
private void Save(Item item, BinaryMemoryWriter writer)
|
||||
{
|
||||
int length = writer.CommitTo(itemData, itemIndex, item.m_TypeRef, item.Serial);
|
||||
|
||||
metrics?.OnItemSaved( length );
|
||||
metrics?.OnItemSaved(length);
|
||||
|
||||
if (item.Decays && item.Parent == null && item.Map != Map.Internal && DateTime.UtcNow > (item.LastMoved + item.DecayTime))
|
||||
{
|
||||
_decayQueue.Enqueue( item );
|
||||
}
|
||||
}
|
||||
if (item.Decays && item.Parent == null && item.Map != Map.Internal &&
|
||||
DateTime.UtcNow > item.LastMoved + item.DecayTime) _decayQueue.Enqueue(item);
|
||||
}
|
||||
|
||||
private void Save( Mobile mob, BinaryMemoryWriter writer ) {
|
||||
int length = writer.CommitTo( mobileData, mobileIndex, mob.m_TypeRef, mob.Serial );
|
||||
private void Save(Mobile mob, BinaryMemoryWriter writer)
|
||||
{
|
||||
int length = writer.CommitTo(mobileData, mobileIndex, mob.m_TypeRef, mob.Serial);
|
||||
|
||||
metrics?.OnMobileSaved( length );
|
||||
}
|
||||
metrics?.OnMobileSaved(length);
|
||||
}
|
||||
|
||||
private void Save( BaseGuild guild, BinaryMemoryWriter writer ) {
|
||||
int length = writer.CommitTo( guildData, guildIndex, 0, guild.Id );
|
||||
private void Save(BaseGuild guild, BinaryMemoryWriter writer)
|
||||
{
|
||||
int length = writer.CommitTo(guildData, guildIndex, 0, guild.Id);
|
||||
|
||||
metrics?.OnGuildSaved( length );
|
||||
}
|
||||
metrics?.OnGuildSaved(length);
|
||||
}
|
||||
|
||||
private bool Enqueue( ISerializable value ) {
|
||||
for ( int i = 0; i < consumers.Length; ++i ) {
|
||||
Consumer consumer = consumers[cycle++ % consumers.Length];
|
||||
private bool Enqueue(ISerializable value)
|
||||
{
|
||||
for (int i = 0; i < consumers.Length; ++i)
|
||||
{
|
||||
Consumer consumer = consumers[cycle++ % consumers.Length];
|
||||
|
||||
if ( ( consumer.tail - consumer.head ) < consumer.buffer.Length ) {
|
||||
consumer.buffer[consumer.tail % consumer.buffer.Length].value = value;
|
||||
consumer.tail++;
|
||||
if (consumer.tail - consumer.head < consumer.buffer.Length)
|
||||
{
|
||||
consumer.buffer[consumer.tail % consumer.buffer.Length].value = value;
|
||||
consumer.tail++;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool Commit() {
|
||||
bool committed = false;
|
||||
private bool Commit()
|
||||
{
|
||||
bool committed = false;
|
||||
|
||||
for (int i = 0; i < consumers.Length; ++i)
|
||||
{
|
||||
Consumer consumer = consumers[i];
|
||||
|
||||
for ( int i = 0; i < consumers.Length; ++i ) {
|
||||
Consumer consumer = consumers[i];
|
||||
while (consumer.head < consumer.done)
|
||||
{
|
||||
OnSerialized(consumer.buffer[consumer.head % consumer.buffer.Length]);
|
||||
consumer.head++;
|
||||
|
||||
while ( consumer.head < consumer.done ) {
|
||||
OnSerialized( consumer.buffer[consumer.head % consumer.buffer.Length] );
|
||||
consumer.head++;
|
||||
committed = true;
|
||||
}
|
||||
}
|
||||
|
||||
return committed;
|
||||
}
|
||||
|
||||
private sealed class Producer : IEnumerable<ISerializable>
|
||||
{
|
||||
private IEnumerable<BaseGuild> guilds;
|
||||
private IEnumerable<Item> items;
|
||||
private IEnumerable<Mobile> mobiles;
|
||||
|
||||
public Producer()
|
||||
{
|
||||
items = World.Items.Values;
|
||||
mobiles = World.Mobiles.Values;
|
||||
guilds = BaseGuild.List.Values;
|
||||
}
|
||||
|
||||
public IEnumerator<ISerializable> GetEnumerator()
|
||||
{
|
||||
foreach (Item item in items) yield return item;
|
||||
|
||||
foreach (Mobile mob in mobiles) yield return mob;
|
||||
|
||||
committed = true;
|
||||
}
|
||||
}
|
||||
foreach (BaseGuild guild in guilds) yield return guild;
|
||||
}
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
private struct ConsumableEntry
|
||||
{
|
||||
public ISerializable value;
|
||||
public BinaryMemoryWriter writer;
|
||||
}
|
||||
|
||||
private sealed class Consumer
|
||||
{
|
||||
public ConsumableEntry[] buffer;
|
||||
|
||||
return committed;
|
||||
}
|
||||
public ManualResetEvent completionEvent;
|
||||
public int head, done, tail;
|
||||
private ParallelSaveStrategy owner;
|
||||
|
||||
private sealed class Producer : IEnumerable<ISerializable> {
|
||||
private IEnumerable<Item> items;
|
||||
private IEnumerable<Mobile> mobiles;
|
||||
private IEnumerable<BaseGuild> guilds;
|
||||
private Thread thread;
|
||||
|
||||
public Producer() {
|
||||
items = World.Items.Values;
|
||||
mobiles = World.Mobiles.Values;
|
||||
guilds = BaseGuild.List.Values;
|
||||
}
|
||||
public Consumer(ParallelSaveStrategy owner, int bufferSize)
|
||||
{
|
||||
this.owner = owner;
|
||||
|
||||
public IEnumerator<ISerializable> GetEnumerator() {
|
||||
foreach ( Item item in items ) {
|
||||
yield return item;
|
||||
}
|
||||
buffer = new ConsumableEntry[bufferSize];
|
||||
|
||||
for (int i = 0; i < buffer.Length; ++i) buffer[i].writer = new BinaryMemoryWriter();
|
||||
|
||||
foreach ( Mobile mob in mobiles ) {
|
||||
yield return mob;
|
||||
}
|
||||
completionEvent = new ManualResetEvent(false);
|
||||
|
||||
thread = new Thread(Processor);
|
||||
|
||||
thread.Name = "Parallel Serialization Thread";
|
||||
|
||||
thread.Start();
|
||||
}
|
||||
|
||||
private void Processor()
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!owner.finished)
|
||||
{
|
||||
Process();
|
||||
Thread.Sleep(0);
|
||||
}
|
||||
|
||||
foreach ( BaseGuild guild in guilds ) {
|
||||
yield return guild;
|
||||
}
|
||||
}
|
||||
Process();
|
||||
|
||||
IEnumerator IEnumerable.GetEnumerator() {
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
completionEvent.Set();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void Process()
|
||||
{
|
||||
ConsumableEntry entry;
|
||||
|
||||
while (done < tail)
|
||||
{
|
||||
entry = buffer[done % buffer.Length];
|
||||
|
||||
entry.value.Serialize(entry.writer);
|
||||
|
||||
private struct ConsumableEntry {
|
||||
public ISerializable value;
|
||||
public BinaryMemoryWriter writer;
|
||||
}
|
||||
|
||||
private sealed class Consumer {
|
||||
private ParallelSaveStrategy owner;
|
||||
|
||||
public ManualResetEvent completionEvent;
|
||||
|
||||
public ConsumableEntry[] buffer;
|
||||
public int head, done, tail;
|
||||
|
||||
private Thread thread;
|
||||
|
||||
public Consumer( ParallelSaveStrategy owner, int bufferSize ) {
|
||||
this.owner = owner;
|
||||
|
||||
buffer = new ConsumableEntry[bufferSize];
|
||||
|
||||
for ( int i = 0; i < buffer.Length; ++i ) {
|
||||
buffer[i].writer = new BinaryMemoryWriter();
|
||||
}
|
||||
|
||||
completionEvent = new ManualResetEvent( false );
|
||||
|
||||
thread = new Thread( Processor );
|
||||
|
||||
thread.Name = "Parallel Serialization Thread";
|
||||
|
||||
thread.Start();
|
||||
}
|
||||
|
||||
private void Processor() {
|
||||
try {
|
||||
while ( !owner.finished ) {
|
||||
Process();
|
||||
Thread.Sleep( 0 );
|
||||
}
|
||||
|
||||
Process();
|
||||
|
||||
completionEvent.Set();
|
||||
} catch ( Exception ex ) {
|
||||
Console.WriteLine( ex );
|
||||
}
|
||||
}
|
||||
|
||||
private void Process() {
|
||||
ConsumableEntry entry;
|
||||
|
||||
while ( done < tail ) {
|
||||
entry = buffer[done % buffer.Length];
|
||||
|
||||
entry.value.Serialize( entry.writer );
|
||||
|
||||
++done;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
++done;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,117 +1,105 @@
|
|||
#region References
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
#endregion
|
||||
|
||||
namespace Server
|
||||
{
|
||||
public static class Persistence
|
||||
{
|
||||
public static void Serialize(string path, Action<GenericWriter> serializer)
|
||||
{
|
||||
Serialize(new FileInfo(path), serializer);
|
||||
}
|
||||
public static class Persistence
|
||||
{
|
||||
public static void Serialize(string path, Action<GenericWriter> serializer)
|
||||
{
|
||||
Serialize(new FileInfo(path), serializer);
|
||||
}
|
||||
|
||||
public static void Serialize(FileInfo file, Action<GenericWriter> serializer)
|
||||
{
|
||||
file.Refresh();
|
||||
public static void Serialize(FileInfo file, Action<GenericWriter> serializer)
|
||||
{
|
||||
file.Refresh();
|
||||
|
||||
if (file.Directory != null && !file.Directory.Exists)
|
||||
{
|
||||
file.Directory.Create();
|
||||
}
|
||||
if (file.Directory != null && !file.Directory.Exists) file.Directory.Create();
|
||||
|
||||
if (!file.Exists)
|
||||
{
|
||||
file.Create().Close();
|
||||
}
|
||||
|
||||
file.Refresh();
|
||||
if (!file.Exists) file.Create().Close();
|
||||
|
||||
using (var fs = file.OpenWrite())
|
||||
{
|
||||
var writer = new BinaryFileWriter(fs, true);
|
||||
file.Refresh();
|
||||
|
||||
try
|
||||
{
|
||||
serializer(writer);
|
||||
}
|
||||
finally
|
||||
{
|
||||
writer.Flush();
|
||||
writer.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
using (FileStream fs = file.OpenWrite())
|
||||
{
|
||||
BinaryFileWriter writer = new BinaryFileWriter(fs, true);
|
||||
|
||||
public static void Deserialize(string path, Action<GenericReader> deserializer)
|
||||
{
|
||||
Deserialize(path, deserializer, true);
|
||||
}
|
||||
try
|
||||
{
|
||||
serializer(writer);
|
||||
}
|
||||
finally
|
||||
{
|
||||
writer.Flush();
|
||||
writer.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void Deserialize(FileInfo file, Action<GenericReader> deserializer)
|
||||
{
|
||||
Deserialize(file, deserializer, true);
|
||||
}
|
||||
public static void Deserialize(string path, Action<GenericReader> deserializer)
|
||||
{
|
||||
Deserialize(path, deserializer, true);
|
||||
}
|
||||
|
||||
public static void Deserialize(string path, Action<GenericReader> deserializer, bool ensure)
|
||||
{
|
||||
Deserialize(new FileInfo(path), deserializer, ensure);
|
||||
}
|
||||
public static void Deserialize(FileInfo file, Action<GenericReader> deserializer)
|
||||
{
|
||||
Deserialize(file, deserializer, true);
|
||||
}
|
||||
|
||||
public static void Deserialize(FileInfo file, Action<GenericReader> deserializer, bool ensure)
|
||||
{
|
||||
file.Refresh();
|
||||
public static void Deserialize(string path, Action<GenericReader> deserializer, bool ensure)
|
||||
{
|
||||
Deserialize(new FileInfo(path), deserializer, ensure);
|
||||
}
|
||||
|
||||
if (file.Directory != null && !file.Directory.Exists)
|
||||
{
|
||||
if (!ensure)
|
||||
{
|
||||
throw new DirectoryNotFoundException();
|
||||
}
|
||||
public static void Deserialize(FileInfo file, Action<GenericReader> deserializer, bool ensure)
|
||||
{
|
||||
file.Refresh();
|
||||
|
||||
file.Directory.Create();
|
||||
}
|
||||
|
||||
if (!file.Exists)
|
||||
{
|
||||
if (!ensure)
|
||||
{
|
||||
throw new FileNotFoundException
|
||||
{
|
||||
Source = file.FullName
|
||||
};
|
||||
}
|
||||
if (file.Directory != null && !file.Directory.Exists)
|
||||
{
|
||||
if (!ensure) throw new DirectoryNotFoundException();
|
||||
|
||||
file.Create().Close();
|
||||
}
|
||||
|
||||
file.Refresh();
|
||||
file.Directory.Create();
|
||||
}
|
||||
|
||||
using (var fs = file.OpenRead())
|
||||
{
|
||||
var reader = new BinaryFileReader(new BinaryReader(fs));
|
||||
if (!file.Exists)
|
||||
{
|
||||
if (!ensure)
|
||||
throw new FileNotFoundException
|
||||
{
|
||||
Source = file.FullName
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
deserializer(reader);
|
||||
}
|
||||
catch (EndOfStreamException eos)
|
||||
{
|
||||
if (file.Length > 0)
|
||||
{
|
||||
Console.WriteLine("[Persistence]: {0}", eos);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine("[Persistence]: {0}", e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
reader.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
file.Create().Close();
|
||||
}
|
||||
|
||||
file.Refresh();
|
||||
|
||||
using (FileStream fs = file.OpenRead())
|
||||
{
|
||||
BinaryFileReader reader = new BinaryFileReader(new BinaryReader(fs));
|
||||
|
||||
try
|
||||
{
|
||||
deserializer(reader);
|
||||
}
|
||||
catch (EndOfStreamException eos)
|
||||
{
|
||||
if (file.Length > 0) Console.WriteLine("[Persistence]: {0}", eos);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine("[Persistence]: {0}", e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
reader.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -18,104 +18,104 @@
|
|||
*
|
||||
***************************************************************************/
|
||||
|
||||
using System.IO;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace Server
|
||||
{
|
||||
public sealed class QueuedMemoryWriter : BinaryFileWriter
|
||||
{
|
||||
private struct IndexInfo
|
||||
{
|
||||
public int size;
|
||||
public int typeCode;
|
||||
public int serial;
|
||||
}
|
||||
public sealed class QueuedMemoryWriter : BinaryFileWriter
|
||||
{
|
||||
private MemoryStream _memStream;
|
||||
private List<IndexInfo> _orderedIndexInfo = new List<IndexInfo>();
|
||||
|
||||
private MemoryStream _memStream;
|
||||
private List<IndexInfo> _orderedIndexInfo = new List<IndexInfo>();
|
||||
public QueuedMemoryWriter()
|
||||
: base(new MemoryStream(1024 * 1024), true)
|
||||
{
|
||||
_memStream = UnderlyingStream as MemoryStream;
|
||||
}
|
||||
|
||||
protected override int BufferSize => 512;
|
||||
protected override int BufferSize => 512;
|
||||
|
||||
public QueuedMemoryWriter()
|
||||
: base(new MemoryStream(1024 * 1024), true)
|
||||
{
|
||||
_memStream = UnderlyingStream as MemoryStream;
|
||||
}
|
||||
public void QueueForIndex(ISerializable serializable, int size)
|
||||
{
|
||||
IndexInfo info;
|
||||
|
||||
public void QueueForIndex(ISerializable serializable, int size)
|
||||
{
|
||||
IndexInfo info;
|
||||
info.size = size;
|
||||
|
||||
info.size = size;
|
||||
info.typeCode = serializable.TypeReference; //For guilds, this will automagically be zero.
|
||||
info.serial = serializable.SerialIdentity;
|
||||
|
||||
info.typeCode = serializable.TypeReference; //For guilds, this will automagically be zero.
|
||||
info.serial = serializable.SerialIdentity;
|
||||
_orderedIndexInfo.Add(info);
|
||||
}
|
||||
|
||||
_orderedIndexInfo.Add(info);
|
||||
}
|
||||
public void CommitTo(SequentialFileWriter dataFile, SequentialFileWriter indexFile)
|
||||
{
|
||||
Flush();
|
||||
|
||||
public void CommitTo(SequentialFileWriter dataFile, SequentialFileWriter indexFile)
|
||||
{
|
||||
Flush();
|
||||
int memLength = (int)_memStream.Position;
|
||||
|
||||
int memLength = (int)_memStream.Position;
|
||||
if (memLength > 0)
|
||||
{
|
||||
byte[] memBuffer = _memStream.GetBuffer();
|
||||
|
||||
if (memLength > 0)
|
||||
{
|
||||
byte[] memBuffer = _memStream.GetBuffer();
|
||||
long actualPosition = dataFile.Position;
|
||||
|
||||
long actualPosition = dataFile.Position;
|
||||
dataFile.Write(memBuffer, 0, memLength); //The buffer contains the data from many items.
|
||||
|
||||
dataFile.Write(memBuffer, 0, memLength); //The buffer contains the data from many items.
|
||||
//Console.WriteLine("Writing {0} bytes starting at {1}, with {2} things", memLength, actualPosition, _orderedIndexInfo.Count);
|
||||
|
||||
//Console.WriteLine("Writing {0} bytes starting at {1}, with {2} things", memLength, actualPosition, _orderedIndexInfo.Count);
|
||||
byte[] indexBuffer = new byte[20];
|
||||
|
||||
byte[] indexBuffer = new byte[20];
|
||||
//int indexWritten = _orderedIndexInfo.Count * indexBuffer.Length;
|
||||
//int totalWritten = memLength + indexWritten
|
||||
|
||||
//int indexWritten = _orderedIndexInfo.Count * indexBuffer.Length;
|
||||
//int totalWritten = memLength + indexWritten
|
||||
for (int i = 0; i < _orderedIndexInfo.Count; i++)
|
||||
{
|
||||
IndexInfo info = _orderedIndexInfo[i];
|
||||
|
||||
for (int i = 0; i < _orderedIndexInfo.Count; i++)
|
||||
{
|
||||
IndexInfo info = _orderedIndexInfo[i];
|
||||
|
||||
int typeCode = info.typeCode;
|
||||
int serial = info.serial;
|
||||
int length = info.size;
|
||||
int typeCode = info.typeCode;
|
||||
int serial = info.serial;
|
||||
int length = info.size;
|
||||
|
||||
|
||||
indexBuffer[0] = (byte)(info.typeCode);
|
||||
indexBuffer[1] = (byte)(info.typeCode >> 8);
|
||||
indexBuffer[2] = (byte)(info.typeCode >> 16);
|
||||
indexBuffer[3] = (byte)(info.typeCode >> 24);
|
||||
indexBuffer[0] = (byte)info.typeCode;
|
||||
indexBuffer[1] = (byte)(info.typeCode >> 8);
|
||||
indexBuffer[2] = (byte)(info.typeCode >> 16);
|
||||
indexBuffer[3] = (byte)(info.typeCode >> 24);
|
||||
|
||||
indexBuffer[4] = (byte)(info.serial);
|
||||
indexBuffer[5] = (byte)(info.serial >> 8);
|
||||
indexBuffer[6] = (byte)(info.serial >> 16);
|
||||
indexBuffer[7] = (byte)(info.serial >> 24);
|
||||
indexBuffer[4] = (byte)info.serial;
|
||||
indexBuffer[5] = (byte)(info.serial >> 8);
|
||||
indexBuffer[6] = (byte)(info.serial >> 16);
|
||||
indexBuffer[7] = (byte)(info.serial >> 24);
|
||||
|
||||
indexBuffer[8] = (byte)(actualPosition);
|
||||
indexBuffer[9] = (byte)(actualPosition >> 8);
|
||||
indexBuffer[10] = (byte)(actualPosition >> 16);
|
||||
indexBuffer[11] = (byte)(actualPosition >> 24);
|
||||
indexBuffer[12] = (byte)(actualPosition >> 32);
|
||||
indexBuffer[13] = (byte)(actualPosition >> 40);
|
||||
indexBuffer[14] = (byte)(actualPosition >> 48);
|
||||
indexBuffer[15] = (byte)(actualPosition >> 56);
|
||||
indexBuffer[8] = (byte)actualPosition;
|
||||
indexBuffer[9] = (byte)(actualPosition >> 8);
|
||||
indexBuffer[10] = (byte)(actualPosition >> 16);
|
||||
indexBuffer[11] = (byte)(actualPosition >> 24);
|
||||
indexBuffer[12] = (byte)(actualPosition >> 32);
|
||||
indexBuffer[13] = (byte)(actualPosition >> 40);
|
||||
indexBuffer[14] = (byte)(actualPosition >> 48);
|
||||
indexBuffer[15] = (byte)(actualPosition >> 56);
|
||||
|
||||
indexBuffer[16] = (byte)(info.size);
|
||||
indexBuffer[17] = (byte)(info.size >> 8);
|
||||
indexBuffer[18] = (byte)(info.size >> 16);
|
||||
indexBuffer[19] = (byte)(info.size >> 24);
|
||||
indexBuffer[16] = (byte)info.size;
|
||||
indexBuffer[17] = (byte)(info.size >> 8);
|
||||
indexBuffer[18] = (byte)(info.size >> 16);
|
||||
indexBuffer[19] = (byte)(info.size >> 24);
|
||||
|
||||
indexFile.Write(indexBuffer, 0, indexBuffer.Length);
|
||||
indexFile.Write(indexBuffer, 0, indexBuffer.Length);
|
||||
|
||||
actualPosition += info.size;
|
||||
}
|
||||
}
|
||||
actualPosition += info.size;
|
||||
}
|
||||
}
|
||||
|
||||
Close(); //We're done with this writer.
|
||||
}
|
||||
}
|
||||
Close(); //We're done with this writer.
|
||||
}
|
||||
|
||||
private struct IndexInfo
|
||||
{
|
||||
public int size;
|
||||
public int typeCode;
|
||||
public int serial;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -21,109 +21,120 @@
|
|||
using System;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Server {
|
||||
public sealed class SaveMetrics : IDisposable {
|
||||
private const string PerformanceCategoryName = "RunUO 2.1";
|
||||
private const string PerformanceCategoryDesc = "Performance counters for RunUO 2.1.";
|
||||
namespace Server
|
||||
{
|
||||
public sealed class SaveMetrics : IDisposable
|
||||
{
|
||||
private const string PerformanceCategoryName = "RunUO 2.1";
|
||||
private const string PerformanceCategoryDesc = "Performance counters for RunUO 2.1.";
|
||||
|
||||
private PerformanceCounter numberOfWorldSaves;
|
||||
private bool isDisposed;
|
||||
|
||||
private PerformanceCounter itemsPerSecond;
|
||||
private PerformanceCounter mobilesPerSecond;
|
||||
private PerformanceCounter itemsPerSecond;
|
||||
private PerformanceCounter mobilesPerSecond;
|
||||
|
||||
private PerformanceCounter serializedBytesPerSecond;
|
||||
private PerformanceCounter writtenBytesPerSecond;
|
||||
private PerformanceCounter numberOfWorldSaves;
|
||||
|
||||
public SaveMetrics() {
|
||||
if ( !PerformanceCounterCategory.Exists( PerformanceCategoryName ) ) {
|
||||
CounterCreationDataCollection counters = new CounterCreationDataCollection();
|
||||
private PerformanceCounter serializedBytesPerSecond;
|
||||
private PerformanceCounter writtenBytesPerSecond;
|
||||
|
||||
counters.Add( new CounterCreationData(
|
||||
"Save - Count",
|
||||
"Number of world saves.",
|
||||
PerformanceCounterType.NumberOfItems32
|
||||
)
|
||||
);
|
||||
public SaveMetrics()
|
||||
{
|
||||
if (!PerformanceCounterCategory.Exists(PerformanceCategoryName))
|
||||
{
|
||||
CounterCreationDataCollection counters = new CounterCreationDataCollection();
|
||||
|
||||
counters.Add( new CounterCreationData(
|
||||
"Save - Items/sec",
|
||||
"Number of items saved per second.",
|
||||
PerformanceCounterType.RateOfCountsPerSecond32
|
||||
)
|
||||
);
|
||||
counters.Add(new CounterCreationData(
|
||||
"Save - Count",
|
||||
"Number of world saves.",
|
||||
PerformanceCounterType.NumberOfItems32
|
||||
)
|
||||
);
|
||||
|
||||
counters.Add( new CounterCreationData(
|
||||
"Save - Mobiles/sec",
|
||||
"Number of mobiles saved per second.",
|
||||
PerformanceCounterType.RateOfCountsPerSecond32
|
||||
)
|
||||
);
|
||||
counters.Add(new CounterCreationData(
|
||||
"Save - Items/sec",
|
||||
"Number of items saved per second.",
|
||||
PerformanceCounterType.RateOfCountsPerSecond32
|
||||
)
|
||||
);
|
||||
|
||||
counters.Add( new CounterCreationData(
|
||||
"Save - Serialized bytes/sec",
|
||||
"Amount of world-save bytes serialized per second.",
|
||||
PerformanceCounterType.RateOfCountsPerSecond32
|
||||
)
|
||||
);
|
||||
counters.Add(new CounterCreationData(
|
||||
"Save - Mobiles/sec",
|
||||
"Number of mobiles saved per second.",
|
||||
PerformanceCounterType.RateOfCountsPerSecond32
|
||||
)
|
||||
);
|
||||
|
||||
counters.Add( new CounterCreationData(
|
||||
"Save - Written bytes/sec",
|
||||
"Amount of world-save bytes written to disk per second.",
|
||||
PerformanceCounterType.RateOfCountsPerSecond32
|
||||
)
|
||||
);
|
||||
counters.Add(new CounterCreationData(
|
||||
"Save - Serialized bytes/sec",
|
||||
"Amount of world-save bytes serialized per second.",
|
||||
PerformanceCounterType.RateOfCountsPerSecond32
|
||||
)
|
||||
);
|
||||
|
||||
counters.Add(new CounterCreationData(
|
||||
"Save - Written bytes/sec",
|
||||
"Amount of world-save bytes written to disk per second.",
|
||||
PerformanceCounterType.RateOfCountsPerSecond32
|
||||
)
|
||||
);
|
||||
|
||||
#if !MONO
|
||||
PerformanceCounterCategory.Create( PerformanceCategoryName, PerformanceCategoryDesc, PerformanceCounterCategoryType.SingleInstance, counters );
|
||||
PerformanceCounterCategory.Create(PerformanceCategoryName, PerformanceCategoryDesc,
|
||||
PerformanceCounterCategoryType.SingleInstance, counters);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
numberOfWorldSaves = new PerformanceCounter( PerformanceCategoryName, "Save - Count", false );
|
||||
numberOfWorldSaves = new PerformanceCounter(PerformanceCategoryName, "Save - Count", false);
|
||||
|
||||
itemsPerSecond = new PerformanceCounter( PerformanceCategoryName, "Save - Items/sec", false );
|
||||
mobilesPerSecond = new PerformanceCounter( PerformanceCategoryName, "Save - Mobiles/sec", false );
|
||||
itemsPerSecond = new PerformanceCounter(PerformanceCategoryName, "Save - Items/sec", false);
|
||||
mobilesPerSecond = new PerformanceCounter(PerformanceCategoryName, "Save - Mobiles/sec", false);
|
||||
|
||||
serializedBytesPerSecond = new PerformanceCounter( PerformanceCategoryName, "Save - Serialized bytes/sec", false );
|
||||
writtenBytesPerSecond = new PerformanceCounter( PerformanceCategoryName, "Save - Written bytes/sec", false );
|
||||
serializedBytesPerSecond = new PerformanceCounter(PerformanceCategoryName, "Save - Serialized bytes/sec", false);
|
||||
writtenBytesPerSecond = new PerformanceCounter(PerformanceCategoryName, "Save - Written bytes/sec", false);
|
||||
|
||||
// increment number of world saves
|
||||
numberOfWorldSaves.Increment();
|
||||
}
|
||||
// increment number of world saves
|
||||
numberOfWorldSaves.Increment();
|
||||
}
|
||||
|
||||
public void OnItemSaved( int numberOfBytes ) {
|
||||
itemsPerSecond.Increment();
|
||||
public void Dispose()
|
||||
{
|
||||
if (!isDisposed)
|
||||
{
|
||||
isDisposed = true;
|
||||
|
||||
serializedBytesPerSecond.IncrementBy( numberOfBytes );
|
||||
}
|
||||
numberOfWorldSaves.Dispose();
|
||||
|
||||
public void OnMobileSaved( int numberOfBytes ) {
|
||||
mobilesPerSecond.Increment();
|
||||
itemsPerSecond.Dispose();
|
||||
mobilesPerSecond.Dispose();
|
||||
|
||||
serializedBytesPerSecond.IncrementBy( numberOfBytes );
|
||||
}
|
||||
serializedBytesPerSecond.Dispose();
|
||||
writtenBytesPerSecond.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public void OnGuildSaved( int numberOfBytes ) {
|
||||
serializedBytesPerSecond.IncrementBy( numberOfBytes );
|
||||
}
|
||||
public void OnItemSaved(int numberOfBytes)
|
||||
{
|
||||
itemsPerSecond.Increment();
|
||||
|
||||
public void OnFileWritten( int numberOfBytes ) {
|
||||
writtenBytesPerSecond.IncrementBy( numberOfBytes );
|
||||
}
|
||||
serializedBytesPerSecond.IncrementBy(numberOfBytes);
|
||||
}
|
||||
|
||||
private bool isDisposed;
|
||||
public void OnMobileSaved(int numberOfBytes)
|
||||
{
|
||||
mobilesPerSecond.Increment();
|
||||
|
||||
public void Dispose() {
|
||||
if ( !isDisposed ) {
|
||||
isDisposed = true;
|
||||
serializedBytesPerSecond.IncrementBy(numberOfBytes);
|
||||
}
|
||||
|
||||
numberOfWorldSaves.Dispose();
|
||||
public void OnGuildSaved(int numberOfBytes)
|
||||
{
|
||||
serializedBytesPerSecond.IncrementBy(numberOfBytes);
|
||||
}
|
||||
|
||||
itemsPerSecond.Dispose();
|
||||
mobilesPerSecond.Dispose();
|
||||
|
||||
serializedBytesPerSecond.Dispose();
|
||||
writtenBytesPerSecond.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public void OnFileWritten(int numberOfBytes)
|
||||
{
|
||||
writtenBytesPerSecond.IncrementBy(numberOfBytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -20,28 +20,28 @@
|
|||
|
||||
namespace Server
|
||||
{
|
||||
public abstract class SaveStrategy
|
||||
{
|
||||
public static SaveStrategy Acquire()
|
||||
{
|
||||
if (Core.MultiProcessor)
|
||||
{
|
||||
int processorCount = Core.ProcessorCount;
|
||||
public abstract class SaveStrategy
|
||||
{
|
||||
public abstract string Name{ get; }
|
||||
|
||||
if (processorCount > 2)
|
||||
{
|
||||
return new DualSaveStrategy(); // return new DynamicSaveStrategy(); (4.0 or return new ParallelSaveStrategy(processorCount); (2.0)
|
||||
}
|
||||
public static SaveStrategy Acquire()
|
||||
{
|
||||
if (Core.MultiProcessor)
|
||||
{
|
||||
int processorCount = Core.ProcessorCount;
|
||||
|
||||
return new DualSaveStrategy();
|
||||
}
|
||||
if (processorCount > 2)
|
||||
return
|
||||
new DualSaveStrategy(); // return new DynamicSaveStrategy(); (4.0 or return new ParallelSaveStrategy(processorCount); (2.0)
|
||||
|
||||
return new StandardSaveStrategy();
|
||||
}
|
||||
return new DualSaveStrategy();
|
||||
}
|
||||
|
||||
public abstract string Name { get; }
|
||||
public abstract void Save(SaveMetrics metrics, bool permitBackgroundWrite);
|
||||
return new StandardSaveStrategy();
|
||||
}
|
||||
|
||||
public abstract void ProcessDecay();
|
||||
}
|
||||
public abstract void Save(SaveMetrics metrics, bool permitBackgroundWrite);
|
||||
|
||||
public abstract void ProcessDecay();
|
||||
}
|
||||
}
|
||||
|
|
@ -21,102 +21,114 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace Server {
|
||||
public sealed class SequentialFileWriter : Stream {
|
||||
private FileStream fileStream;
|
||||
private FileQueue fileQueue;
|
||||
namespace Server
|
||||
{
|
||||
public sealed class SequentialFileWriter : Stream
|
||||
{
|
||||
private FileQueue fileQueue;
|
||||
private FileStream fileStream;
|
||||
|
||||
private AsyncCallback writeCallback;
|
||||
private SaveMetrics metrics;
|
||||
|
||||
private SaveMetrics metrics;
|
||||
private AsyncCallback writeCallback;
|
||||
|
||||
public SequentialFileWriter( string path, SaveMetrics metrics ) {
|
||||
if ( path == null ) {
|
||||
throw new ArgumentNullException( "path" );
|
||||
}
|
||||
public SequentialFileWriter(string path, SaveMetrics metrics)
|
||||
{
|
||||
if (path == null) throw new ArgumentNullException("path");
|
||||
|
||||
this.metrics = metrics;
|
||||
this.metrics = metrics;
|
||||
|
||||
fileStream = FileOperations.OpenSequentialStream( path, FileMode.Create, FileAccess.Write, FileShare.None );
|
||||
fileStream = FileOperations.OpenSequentialStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
|
||||
|
||||
fileQueue = new FileQueue(
|
||||
Math.Max( 1, FileOperations.Concurrency ),
|
||||
FileCallback
|
||||
);
|
||||
}
|
||||
fileQueue = new FileQueue(
|
||||
Math.Max(1, FileOperations.Concurrency),
|
||||
FileCallback
|
||||
);
|
||||
}
|
||||
|
||||
public override long Position {
|
||||
get => fileQueue.Position;
|
||||
set => throw new InvalidOperationException();
|
||||
}
|
||||
public override long Position
|
||||
{
|
||||
get => fileQueue.Position;
|
||||
set => throw new InvalidOperationException();
|
||||
}
|
||||
|
||||
private void FileCallback( FileQueue.Chunk chunk ) {
|
||||
if ( FileOperations.AreSynchronous ) {
|
||||
fileStream.Write( chunk.Buffer, chunk.Offset, chunk.Size );
|
||||
public override bool CanRead => false;
|
||||
|
||||
metrics?.OnFileWritten( chunk.Size );
|
||||
public override bool CanSeek => false;
|
||||
|
||||
chunk.Commit();
|
||||
} else {
|
||||
if ( writeCallback == null ) {
|
||||
writeCallback = OnWrite;
|
||||
}
|
||||
public override bool CanWrite => true;
|
||||
|
||||
fileStream.BeginWrite( chunk.Buffer, chunk.Offset, chunk.Size, writeCallback, chunk );
|
||||
}
|
||||
}
|
||||
public override long Length => Position;
|
||||
|
||||
private void OnWrite( IAsyncResult asyncResult ) {
|
||||
FileQueue.Chunk chunk = asyncResult.AsyncState as FileQueue.Chunk;
|
||||
private void FileCallback(FileQueue.Chunk chunk)
|
||||
{
|
||||
if (FileOperations.AreSynchronous)
|
||||
{
|
||||
fileStream.Write(chunk.Buffer, chunk.Offset, chunk.Size);
|
||||
|
||||
fileStream.EndWrite( asyncResult );
|
||||
metrics?.OnFileWritten(chunk.Size);
|
||||
|
||||
metrics?.OnFileWritten( chunk.Size );
|
||||
chunk.Commit();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (writeCallback == null) writeCallback = OnWrite;
|
||||
|
||||
chunk.Commit();
|
||||
}
|
||||
fileStream.BeginWrite(chunk.Buffer, chunk.Offset, chunk.Size, writeCallback, chunk);
|
||||
}
|
||||
}
|
||||
|
||||
public override void Write( byte[] buffer, int offset, int size ) {
|
||||
fileQueue.Enqueue( buffer, offset, size );
|
||||
}
|
||||
private void OnWrite(IAsyncResult asyncResult)
|
||||
{
|
||||
FileQueue.Chunk chunk = asyncResult.AsyncState as FileQueue.Chunk;
|
||||
|
||||
public override void Flush() {
|
||||
fileQueue.Flush();
|
||||
fileStream.Flush();
|
||||
}
|
||||
fileStream.EndWrite(asyncResult);
|
||||
|
||||
protected override void Dispose( bool disposing ) {
|
||||
if ( fileStream != null ) {
|
||||
Flush();
|
||||
metrics?.OnFileWritten(chunk.Size);
|
||||
|
||||
fileQueue.Dispose();
|
||||
fileQueue = null;
|
||||
chunk.Commit();
|
||||
}
|
||||
|
||||
fileStream.Close();
|
||||
fileStream = null;
|
||||
}
|
||||
public override void Write(byte[] buffer, int offset, int size)
|
||||
{
|
||||
fileQueue.Enqueue(buffer, offset, size);
|
||||
}
|
||||
|
||||
base.Dispose( disposing );
|
||||
}
|
||||
public override void Flush()
|
||||
{
|
||||
fileQueue.Flush();
|
||||
fileStream.Flush();
|
||||
}
|
||||
|
||||
public override bool CanRead => false;
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (fileStream != null)
|
||||
{
|
||||
Flush();
|
||||
|
||||
public override bool CanSeek => false;
|
||||
fileQueue.Dispose();
|
||||
fileQueue = null;
|
||||
|
||||
public override bool CanWrite => true;
|
||||
fileStream.Close();
|
||||
fileStream = null;
|
||||
}
|
||||
|
||||
public override long Length => Position;
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
public override int Read( byte[] buffer, int offset, int count ) {
|
||||
throw new InvalidOperationException();
|
||||
}
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
{
|
||||
throw new InvalidOperationException();
|
||||
}
|
||||
|
||||
public override long Seek( long offset, SeekOrigin origin ) {
|
||||
throw new InvalidOperationException();
|
||||
}
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
{
|
||||
throw new InvalidOperationException();
|
||||
}
|
||||
|
||||
public override void SetLength( long value ) {
|
||||
fileStream.SetLength( value );
|
||||
}
|
||||
}
|
||||
}
|
||||
public override void SetLength(long value)
|
||||
{
|
||||
fileStream.SetLength(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -22,180 +22,191 @@ using System;
|
|||
using System.Collections.Generic;
|
||||
using Server.Guilds;
|
||||
|
||||
namespace Server {
|
||||
public class StandardSaveStrategy : SaveStrategy {
|
||||
public enum SaveOption
|
||||
{
|
||||
Normal,
|
||||
Threaded
|
||||
}
|
||||
namespace Server
|
||||
{
|
||||
public class StandardSaveStrategy : SaveStrategy
|
||||
{
|
||||
public enum SaveOption
|
||||
{
|
||||
Normal,
|
||||
Threaded
|
||||
}
|
||||
|
||||
public static SaveOption SaveType = SaveOption.Normal;
|
||||
public static SaveOption SaveType = SaveOption.Normal;
|
||||
|
||||
public override string Name => "Standard";
|
||||
private Queue<Item> _decayQueue;
|
||||
|
||||
private Queue<Item> _decayQueue;
|
||||
public StandardSaveStrategy()
|
||||
{
|
||||
_decayQueue = new Queue<Item>();
|
||||
}
|
||||
|
||||
public StandardSaveStrategy() {
|
||||
_decayQueue = new Queue<Item>();
|
||||
}
|
||||
public override string Name => "Standard";
|
||||
|
||||
protected bool PermitBackgroundWrite { get; set; }
|
||||
protected bool PermitBackgroundWrite{ get; set; }
|
||||
|
||||
protected bool UseSequentialWriters => (SaveType == SaveOption.Normal || !PermitBackgroundWrite);
|
||||
protected bool UseSequentialWriters => SaveType == SaveOption.Normal || !PermitBackgroundWrite;
|
||||
|
||||
public override void Save(SaveMetrics metrics, bool permitBackgroundWrite)
|
||||
{
|
||||
PermitBackgroundWrite = permitBackgroundWrite;
|
||||
public override void Save(SaveMetrics metrics, bool permitBackgroundWrite)
|
||||
{
|
||||
PermitBackgroundWrite = permitBackgroundWrite;
|
||||
|
||||
SaveMobiles(metrics);
|
||||
SaveItems(metrics);
|
||||
SaveGuilds(metrics);
|
||||
SaveMobiles(metrics);
|
||||
SaveItems(metrics);
|
||||
SaveGuilds(metrics);
|
||||
|
||||
if (permitBackgroundWrite && UseSequentialWriters) //If we're permitted to write in the background, but we don't anyways, then notify.
|
||||
World.NotifyDiskWriteComplete();
|
||||
}
|
||||
if (permitBackgroundWrite && UseSequentialWriters
|
||||
) //If we're permitted to write in the background, but we don't anyways, then notify.
|
||||
World.NotifyDiskWriteComplete();
|
||||
}
|
||||
|
||||
protected void SaveMobiles(SaveMetrics metrics)
|
||||
{
|
||||
Dictionary<Serial, Mobile> mobiles = World.Mobiles;
|
||||
protected void SaveMobiles(SaveMetrics metrics)
|
||||
{
|
||||
Dictionary<Serial, Mobile> mobiles = World.Mobiles;
|
||||
|
||||
GenericWriter idx;
|
||||
GenericWriter tdb;
|
||||
GenericWriter bin;
|
||||
GenericWriter idx;
|
||||
GenericWriter tdb;
|
||||
GenericWriter bin;
|
||||
|
||||
if (UseSequentialWriters)
|
||||
{
|
||||
idx = new BinaryFileWriter( World.MobileIndexPath, false );
|
||||
tdb = new BinaryFileWriter( World.MobileTypesPath, false );
|
||||
bin = new BinaryFileWriter( World.MobileDataPath, true );
|
||||
} else {
|
||||
idx = new AsyncWriter( World.MobileIndexPath, false );
|
||||
tdb = new AsyncWriter( World.MobileTypesPath, false );
|
||||
bin = new AsyncWriter( World.MobileDataPath, true );
|
||||
}
|
||||
if (UseSequentialWriters)
|
||||
{
|
||||
idx = new BinaryFileWriter(World.MobileIndexPath, false);
|
||||
tdb = new BinaryFileWriter(World.MobileTypesPath, false);
|
||||
bin = new BinaryFileWriter(World.MobileDataPath, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
idx = new AsyncWriter(World.MobileIndexPath, false);
|
||||
tdb = new AsyncWriter(World.MobileTypesPath, false);
|
||||
bin = new AsyncWriter(World.MobileDataPath, true);
|
||||
}
|
||||
|
||||
idx.Write( ( int ) mobiles.Count );
|
||||
foreach ( Mobile m in mobiles.Values ) {
|
||||
long start = bin.Position;
|
||||
idx.Write(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 );
|
||||
idx.Write(m.m_TypeRef);
|
||||
idx.Write(m.Serial);
|
||||
idx.Write(start);
|
||||
|
||||
m.Serialize( bin );
|
||||
m.Serialize(bin);
|
||||
|
||||
metrics?.OnMobileSaved( ( int ) ( bin.Position - start ) );
|
||||
metrics?.OnMobileSaved((int)(bin.Position - start));
|
||||
|
||||
idx.Write( ( int ) ( bin.Position - start ) );
|
||||
idx.Write((int)(bin.Position - start));
|
||||
|
||||
m.FreeCache();
|
||||
}
|
||||
m.FreeCache();
|
||||
}
|
||||
|
||||
tdb.Write( ( int ) World.m_MobileTypes.Count );
|
||||
tdb.Write(World.m_MobileTypes.Count);
|
||||
|
||||
for ( int i = 0; i < World.m_MobileTypes.Count; ++i )
|
||||
tdb.Write( World.m_MobileTypes[i].FullName );
|
||||
for (int i = 0; i < World.m_MobileTypes.Count; ++i)
|
||||
tdb.Write(World.m_MobileTypes[i].FullName);
|
||||
|
||||
idx.Close();
|
||||
tdb.Close();
|
||||
bin.Close();
|
||||
}
|
||||
idx.Close();
|
||||
tdb.Close();
|
||||
bin.Close();
|
||||
}
|
||||
|
||||
protected void SaveItems(SaveMetrics metrics)
|
||||
{
|
||||
Dictionary<Serial, Item> items = World.Items;
|
||||
protected void SaveItems(SaveMetrics metrics)
|
||||
{
|
||||
Dictionary<Serial, Item> items = World.Items;
|
||||
|
||||
GenericWriter idx;
|
||||
GenericWriter tdb;
|
||||
GenericWriter bin;
|
||||
GenericWriter idx;
|
||||
GenericWriter tdb;
|
||||
GenericWriter bin;
|
||||
|
||||
if (UseSequentialWriters)
|
||||
{
|
||||
idx = new BinaryFileWriter( World.ItemIndexPath, false );
|
||||
tdb = new BinaryFileWriter( World.ItemTypesPath, false );
|
||||
bin = new BinaryFileWriter( World.ItemDataPath, true );
|
||||
} else {
|
||||
idx = new AsyncWriter( World.ItemIndexPath, false );
|
||||
tdb = new AsyncWriter( World.ItemTypesPath, false );
|
||||
bin = new AsyncWriter( World.ItemDataPath, true );
|
||||
}
|
||||
if (UseSequentialWriters)
|
||||
{
|
||||
idx = new BinaryFileWriter(World.ItemIndexPath, false);
|
||||
tdb = new BinaryFileWriter(World.ItemTypesPath, false);
|
||||
bin = new BinaryFileWriter(World.ItemDataPath, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
idx = new AsyncWriter(World.ItemIndexPath, false);
|
||||
tdb = new AsyncWriter(World.ItemTypesPath, false);
|
||||
bin = new AsyncWriter(World.ItemDataPath, true);
|
||||
}
|
||||
|
||||
idx.Write( ( int ) items.Count );
|
||||
idx.Write(items.Count);
|
||||
|
||||
DateTime n = DateTime.UtcNow;
|
||||
DateTime n = DateTime.UtcNow;
|
||||
|
||||
foreach ( Item item in items.Values ) {
|
||||
if (item.Decays && item.Parent == null && item.Map != Map.Internal && (item.LastMoved + item.DecayTime) <= n)
|
||||
{
|
||||
_decayQueue.Enqueue( item );
|
||||
}
|
||||
foreach (Item item in items.Values)
|
||||
{
|
||||
if (item.Decays && item.Parent == null && item.Map != Map.Internal && item.LastMoved + item.DecayTime <= n)
|
||||
_decayQueue.Enqueue(item);
|
||||
|
||||
long start = bin.Position;
|
||||
long start = bin.Position;
|
||||
|
||||
idx.Write( ( int ) item.m_TypeRef );
|
||||
idx.Write( ( int ) item.Serial );
|
||||
idx.Write( ( long ) start );
|
||||
idx.Write(item.m_TypeRef);
|
||||
idx.Write(item.Serial);
|
||||
idx.Write(start);
|
||||
|
||||
item.Serialize( bin );
|
||||
item.Serialize(bin);
|
||||
|
||||
metrics?.OnItemSaved( ( int ) ( bin.Position - start ) );
|
||||
metrics?.OnItemSaved((int)(bin.Position - start));
|
||||
|
||||
idx.Write( ( int ) ( bin.Position - start ) );
|
||||
idx.Write((int)(bin.Position - start));
|
||||
|
||||
item.FreeCache();
|
||||
}
|
||||
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 );
|
||||
tdb.Write(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();
|
||||
}
|
||||
idx.Close();
|
||||
tdb.Close();
|
||||
bin.Close();
|
||||
}
|
||||
|
||||
protected void SaveGuilds(SaveMetrics metrics)
|
||||
{
|
||||
GenericWriter idx;
|
||||
GenericWriter bin;
|
||||
protected void SaveGuilds(SaveMetrics metrics)
|
||||
{
|
||||
GenericWriter idx;
|
||||
GenericWriter bin;
|
||||
|
||||
if (UseSequentialWriters)
|
||||
{
|
||||
idx = new BinaryFileWriter( World.GuildIndexPath, false );
|
||||
bin = new BinaryFileWriter( World.GuildDataPath, true );
|
||||
} else {
|
||||
idx = new AsyncWriter( World.GuildIndexPath, false );
|
||||
bin = new AsyncWriter( World.GuildDataPath, true );
|
||||
}
|
||||
if (UseSequentialWriters)
|
||||
{
|
||||
idx = new BinaryFileWriter(World.GuildIndexPath, false);
|
||||
bin = new BinaryFileWriter(World.GuildDataPath, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
idx = new AsyncWriter(World.GuildIndexPath, false);
|
||||
bin = new AsyncWriter(World.GuildDataPath, true);
|
||||
}
|
||||
|
||||
idx.Write( ( int ) BaseGuild.List.Count );
|
||||
foreach ( BaseGuild guild in BaseGuild.List.Values ) {
|
||||
long start = bin.Position;
|
||||
idx.Write(BaseGuild.List.Count);
|
||||
foreach (BaseGuild guild in BaseGuild.List.Values)
|
||||
{
|
||||
long start = bin.Position;
|
||||
|
||||
idx.Write( ( int ) 0 );//guilds have no typeid
|
||||
idx.Write( ( int ) guild.Id );
|
||||
idx.Write( ( long ) start );
|
||||
idx.Write(0); //guilds have no typeid
|
||||
idx.Write(guild.Id);
|
||||
idx.Write(start);
|
||||
|
||||
guild.Serialize( bin );
|
||||
guild.Serialize(bin);
|
||||
|
||||
metrics?.OnGuildSaved( ( int ) ( bin.Position - start ) );
|
||||
metrics?.OnGuildSaved((int)(bin.Position - start));
|
||||
|
||||
idx.Write( ( int ) ( bin.Position - start ) );
|
||||
}
|
||||
idx.Write((int)(bin.Position - start));
|
||||
}
|
||||
|
||||
idx.Close();
|
||||
bin.Close();
|
||||
}
|
||||
idx.Close();
|
||||
bin.Close();
|
||||
}
|
||||
|
||||
public override void ProcessDecay() {
|
||||
while ( _decayQueue.Count > 0 ) {
|
||||
Item item = _decayQueue.Dequeue();
|
||||
public override void ProcessDecay()
|
||||
{
|
||||
while (_decayQueue.Count > 0)
|
||||
{
|
||||
Item item = _decayQueue.Dequeue();
|
||||
|
||||
if ( item.OnDecay() ) {
|
||||
item.Delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (item.OnDecay()) item.Delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue