Răsfoiți Sursa

1.buff计时器是非托管资源,不过即使没有马上Dispose也没关系,在垃圾回收的时候再从TimerComponent中删除也可以,所以还是设计成不需要Dispose比较方便
2.整理一下代码

tanghai 11 ani în urmă
părinte
comite
c60fe0c17b
100 a modificat fișierele cu 4201 adăugiri și 4262 ștergeri
  1. 14 14
      CSharp/App/Editor/App.xaml.cs
  2. 26 28
      CSharp/App/Editor/Bootstrapper.cs
  3. 16 16
      CSharp/App/Editor/Shell.xaml.cs
  4. 5 5
      CSharp/App/Editor/ShellViewModel.cs
  5. 39 41
      CSharp/App/Infrastructure/AutoPopulateExportedViewsBehavior.cs
  6. 4 4
      CSharp/App/Infrastructure/IViewRegionRegistration.cs
  7. 11 11
      CSharp/App/Infrastructure/ViewExportAttribute.cs
  8. 13 13
      CSharp/App/Modules/BehaviorTreeModule/AllTreeData.cs
  9. 73 73
      CSharp/App/Modules/BehaviorTreeModule/AllTreeView.xaml.cs
  10. 84 88
      CSharp/App/Modules/BehaviorTreeModule/AllTreeViewModel.cs
  11. 21 22
      CSharp/App/Modules/BehaviorTreeModule/FolderVisiableConverter.cs
  12. 32 33
      CSharp/App/Modules/BehaviorTreeModule/ListToStringConverter.cs
  13. 46 46
      CSharp/App/Modules/BehaviorTreeModule/NodeDataEditor.xaml.cs
  14. 31 31
      CSharp/App/Modules/BehaviorTreeModule/NodeType.cs
  15. 33 34
      CSharp/App/Modules/BehaviorTreeModule/NodeTypeColorConverter.cs
  16. 16 17
      CSharp/App/Modules/BehaviorTreeModule/NodeTypeToStringConverter.cs
  17. 24 24
      CSharp/App/Modules/BehaviorTreeModule/TreeInfoViewModel.cs
  18. 172 176
      CSharp/App/Modules/BehaviorTreeModule/TreeLayout.cs
  19. 7 7
      CSharp/App/Modules/BehaviorTreeModule/TreeModule.cs
  20. 53 53
      CSharp/App/Modules/BehaviorTreeModule/TreeNodeData.cs
  21. 404 404
      CSharp/App/Modules/BehaviorTreeModule/TreeNodeViewModel.cs
  22. 232 232
      CSharp/App/Modules/BehaviorTreeModule/TreeView.xaml.cs
  23. 257 258
      CSharp/App/Modules/BehaviorTreeModule/TreeViewModel.cs
  24. 11 11
      CSharp/Game/Controller/BehaviorTreeNode/Not.cs
  25. 18 18
      CSharp/Game/Controller/BehaviorTreeNode/Selector.cs
  26. 18 18
      CSharp/Game/Controller/BehaviorTreeNode/Sequence.cs
  27. 14 14
      CSharp/Game/Controller/Callback/BuffTimeoutCallback.cs
  28. 5 5
      CSharp/Game/Controller/ConfigCategory/BuffCategory.cs
  29. 5 5
      CSharp/Game/Controller/ConfigCategory/GlobalCategory.cs
  30. 5 5
      CSharp/Game/Controller/ConfigCategory/NodeCategory.cs
  31. 5 5
      CSharp/Game/Controller/ConfigCategory/UnitCategory.cs
  32. 8 9
      CSharp/Game/Controller/Event/AfterAddBuff.cs
  33. 14 14
      CSharp/Game/Controller/Factory/UnitFactory.cs
  34. 6 6
      CSharp/Game/Controller/NodeType.cs
  35. 7 7
      CSharp/Game/Controller/UnitType.cs
  36. 12 12
      CSharp/Game/Model/BehaviorTree/BehaviorTree.cs
  37. 59 60
      CSharp/Game/Model/BehaviorTree/BehaviorTreeFactory.cs
  38. 3 3
      CSharp/Game/Model/BehaviorTree/BlackBoard.cs
  39. 14 14
      CSharp/Game/Model/BehaviorTree/Node.cs
  40. 9 9
      CSharp/Game/Model/BehaviorTree/NodeAttribute.cs
  41. 55 59
      CSharp/Game/Model/Buff.cs
  42. 6 6
      CSharp/Game/Model/BuffType.cs
  43. 16 16
      CSharp/Game/Model/Component/BehaviorTreeComponent.cs
  44. 116 115
      CSharp/Game/Model/Component/BuffComponent.cs
  45. 54 55
      CSharp/Game/Model/Component/ConfigComponent.cs
  46. 43 43
      CSharp/Game/Model/Component/EventComponent.cs
  47. 35 36
      CSharp/Game/Model/Component/FactoryComponent.cs
  48. 7 12
      CSharp/Game/Model/Component/MessageComponent.cs
  49. 66 65
      CSharp/Game/Model/Component/TimerComponent.cs
  50. 55 56
      CSharp/Game/Model/Component/UnitComponent.cs
  51. 14 14
      CSharp/Game/Model/Config/BuffConfig.cs
  52. 4 4
      CSharp/Game/Model/Config/GlobalConfig.cs
  53. 5 5
      CSharp/Game/Model/Config/NodeConfig.cs
  54. 5 5
      CSharp/Game/Model/Config/UnitConfig.cs
  55. 8 8
      CSharp/Game/Model/EnvKey.cs
  56. 13 13
      CSharp/Game/Model/EventAttribute.cs
  57. 12 12
      CSharp/Game/Model/EventType.cs
  58. 11 11
      CSharp/Game/Model/FactoryAttribute.cs
  59. 6 5
      CSharp/Game/Model/IAssemblyLoader.cs
  60. 4 4
      CSharp/Game/Model/IFactory.cs
  61. 10 10
      CSharp/Game/Model/MessageAttribute.cs
  62. 17 17
      CSharp/Game/Model/Unit.cs
  63. 28 28
      CSharp/Game/Model/World.cs
  64. 46 48
      CSharp/Game/MongoDBTest/MongoDBTest.cs
  65. 28 28
      CSharp/Platform/Common/Base/Component.cs
  66. 106 107
      CSharp/Platform/Common/Base/Entity.cs
  67. 98 99
      CSharp/Platform/Common/Base/MultiMap.cs
  68. 97 98
      CSharp/Platform/Common/Base/Object.cs
  69. 47 47
      CSharp/Platform/Common/Config/ACategory.cs
  70. 11 11
      CSharp/Platform/Common/Config/AConfig.cs
  71. 4 4
      CSharp/Platform/Common/Config/ConfigAttribute.cs
  72. 4 4
      CSharp/Platform/Common/Config/ICategory.cs
  73. 9 9
      CSharp/Platform/Common/Event/AEventAttribute.cs
  74. 3 3
      CSharp/Platform/Common/Event/Env.cs
  75. 4 4
      CSharp/Platform/Common/Event/IEvent.cs
  76. 67 67
      CSharp/Platform/Common/Helper/BigIntegerHelper.cs
  77. 25 25
      CSharp/Platform/Common/Helper/ByteHelper.cs
  78. 17 17
      CSharp/Platform/Common/Helper/EnumHelper.cs
  79. 13 13
      CSharp/Platform/Common/Helper/LoaderHelper.cs
  80. 27 27
      CSharp/Platform/Common/Helper/MongoHelper.cs
  81. 33 33
      CSharp/Platform/Common/Helper/ProtobufHelper.cs
  82. 10 10
      CSharp/Platform/Common/Helper/RandomHelper.cs
  83. 30 31
      CSharp/Platform/Common/Helper/StringHelper.cs
  84. 8 8
      CSharp/Platform/Common/Helper/TimeHelper.cs
  85. 32 32
      CSharp/Platform/Common/Helper/XmlHelper.cs
  86. 13 13
      CSharp/Platform/Common/Hooks/Native.cs
  87. 34 34
      CSharp/Platform/Common/Logger/ALogDecorater.cs
  88. 5 5
      CSharp/Platform/Common/Logger/ILog.cs
  89. 27 27
      CSharp/Platform/Common/Logger/Log.cs
  90. 15 15
      CSharp/Platform/Common/Logger/NLogAdapter.cs
  91. 35 35
      CSharp/Platform/Common/Logger/StackInfoDecorater.cs
  92. 52 52
      CSharp/Platform/ENet/Address.cs
  93. 53 53
      CSharp/Platform/ENet/EEvent.cs
  94. 16 16
      CSharp/Platform/ENet/EException.cs
  95. 81 81
      CSharp/Platform/ENet/EPacket.cs
  96. 304 308
      CSharp/Platform/ENet/EService.cs
  97. 269 272
      CSharp/Platform/ENet/ESocket.cs
  98. 4 4
      CSharp/Platform/ENet/ErrorCode.cs
  99. 27 28
      CSharp/Platform/ENet/Library.cs
  100. 131 150
      CSharp/Platform/ENet/NativeMethods.cs

+ 14 - 14
CSharp/App/Editor/App.xaml.cs

@@ -2,19 +2,19 @@
 
 namespace Editor
 {
-    public partial class App: Application
-    {
-        protected override void OnStartup(StartupEventArgs e)
-        {
-            base.OnStartup(e);
-            RunInDebugMode();
-            this.ShutdownMode = ShutdownMode.OnMainWindowClose;
-        }
+	public partial class App: Application
+	{
+		protected override void OnStartup(StartupEventArgs e)
+		{
+			base.OnStartup(e);
+			RunInDebugMode();
+			this.ShutdownMode = ShutdownMode.OnMainWindowClose;
+		}
 
-        private static void RunInDebugMode()
-        {
-            var bootstrapper = new Bootstrapper();
-            bootstrapper.Run();
-        }
-    }
+		private static void RunInDebugMode()
+		{
+			var bootstrapper = new Bootstrapper();
+			bootstrapper.Run();
+		}
+	}
 }

+ 26 - 28
CSharp/App/Editor/Bootstrapper.cs

@@ -7,35 +7,33 @@ using Modules.BehaviorTreeModule;
 
 namespace Editor
 {
-    public class Bootstrapper: MefBootstrapper
-    {
-        protected override void ConfigureAggregateCatalog()
-        {
-            this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof (Bootstrapper).Assembly));
-            this.AggregateCatalog.Catalogs.Add(
-                                               new AssemblyCatalog(
-                                                       typeof (ViewExportAttribute).Assembly));
-            this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof (TreeModule).Assembly));
-        }
+	public class Bootstrapper: MefBootstrapper
+	{
+		protected override void ConfigureAggregateCatalog()
+		{
+			this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof (Bootstrapper).Assembly));
+			this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof (ViewExportAttribute).Assembly));
+			this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof (TreeModule).Assembly));
+		}
 
-        protected override void InitializeShell()
-        {
-            base.InitializeShell();
-            Application.Current.MainWindow = (Shell) this.Shell;
-            Application.Current.MainWindow.Show();
-        }
+		protected override void InitializeShell()
+		{
+			base.InitializeShell();
+			Application.Current.MainWindow = (Shell) this.Shell;
+			Application.Current.MainWindow.Show();
+		}
 
-        protected override IRegionBehaviorFactory ConfigureDefaultRegionBehaviors()
-        {
-            IRegionBehaviorFactory factory = base.ConfigureDefaultRegionBehaviors();
-            factory.AddIfMissing("AutoPopulateExportedViewsBehavior",
-                    typeof (AutoPopulateExportedViewsBehavior));
-            return factory;
-        }
+		protected override IRegionBehaviorFactory ConfigureDefaultRegionBehaviors()
+		{
+			IRegionBehaviorFactory factory = base.ConfigureDefaultRegionBehaviors();
+			factory.AddIfMissing("AutoPopulateExportedViewsBehavior",
+					typeof (AutoPopulateExportedViewsBehavior));
+			return factory;
+		}
 
-        protected override DependencyObject CreateShell()
-        {
-            return this.Container.GetExportedValue<Shell>();
-        }
-    }
+		protected override DependencyObject CreateShell()
+		{
+			return this.Container.GetExportedValue<Shell>();
+		}
+	}
 }

+ 16 - 16
CSharp/App/Editor/Shell.xaml.cs

@@ -3,21 +3,21 @@ using System.Windows;
 
 namespace Editor
 {
-    [Export]
-    public partial class Shell: Window
-    {
-        public Shell()
-        {
-            this.InitializeComponent();
-        }
+	[Export]
+	public partial class Shell: Window
+	{
+		public Shell()
+		{
+			this.InitializeComponent();
+		}
 
-        [Import]
-        private ShellViewModel ViewModel
-        {
-            set
-            {
-                this.DataContext = value;
-            }
-        }
-    }
+		[Import]
+		private ShellViewModel ViewModel
+		{
+			set
+			{
+				this.DataContext = value;
+			}
+		}
+	}
 }

+ 5 - 5
CSharp/App/Editor/ShellViewModel.cs

@@ -3,9 +3,9 @@ using Microsoft.Practices.Prism.Mvvm;
 
 namespace Editor
 {
-    [Export]
-    public class ShellViewModel: BindableBase
-    {
-        // This is where any view model logic for the shell would go.
-    }
+	[Export]
+	public class ShellViewModel: BindableBase
+	{
+		// This is where any view model logic for the shell would go.
+	}
 }

+ 39 - 41
CSharp/App/Infrastructure/AutoPopulateExportedViewsBehavior.cs

@@ -21,45 +21,43 @@ using Microsoft.Practices.Prism.Regions;
 
 namespace Infrastructure
 {
-    [Export(typeof (AutoPopulateExportedViewsBehavior)),
-     PartCreationPolicy(CreationPolicy.NonShared)]
-    public class AutoPopulateExportedViewsBehavior: RegionBehavior,
-            IPartImportsSatisfiedNotification
-    {
-        [ImportMany(AllowRecomposition = true)]
-        public Lazy<object, IViewRegionRegistration>[] RegisteredViews { get; set; }
-
-        public void OnImportsSatisfied()
-        {
-            this.AddRegisteredViews();
-        }
-
-        protected override void OnAttach()
-        {
-            this.AddRegisteredViews();
-        }
-
-        private void AddRegisteredViews()
-        {
-            if (this.Region == null)
-            {
-                return;
-            }
-
-            foreach (var viewEntry in this.RegisteredViews)
-            {
-                if (viewEntry.Metadata.RegionName != this.Region.Name)
-                {
-                    continue;
-                }
-
-                object view = viewEntry.Value;
-
-                if (!this.Region.Views.Contains(view))
-                {
-                    this.Region.Add(view);
-                }
-            }
-        }
-    }
+	[Export(typeof (AutoPopulateExportedViewsBehavior)), PartCreationPolicy(CreationPolicy.NonShared)]
+	public class AutoPopulateExportedViewsBehavior: RegionBehavior, IPartImportsSatisfiedNotification
+	{
+		[ImportMany(AllowRecomposition = true)]
+		public Lazy<object, IViewRegionRegistration>[] RegisteredViews { get; set; }
+
+		public void OnImportsSatisfied()
+		{
+			this.AddRegisteredViews();
+		}
+
+		protected override void OnAttach()
+		{
+			this.AddRegisteredViews();
+		}
+
+		private void AddRegisteredViews()
+		{
+			if (this.Region == null)
+			{
+				return;
+			}
+
+			foreach (var viewEntry in this.RegisteredViews)
+			{
+				if (viewEntry.Metadata.RegionName != this.Region.Name)
+				{
+					continue;
+				}
+
+				object view = viewEntry.Value;
+
+				if (!this.Region.Views.Contains(view))
+				{
+					this.Region.Add(view);
+				}
+			}
+		}
+	}
 }

+ 4 - 4
CSharp/App/Infrastructure/IViewRegionRegistration.cs

@@ -17,8 +17,8 @@
 
 namespace Infrastructure
 {
-    public interface IViewRegionRegistration
-    {
-        string RegionName { get; }
-    }
+	public interface IViewRegionRegistration
+	{
+		string RegionName { get; }
+	}
 }

+ 11 - 11
CSharp/App/Infrastructure/ViewExportAttribute.cs

@@ -20,17 +20,17 @@ using System.ComponentModel.Composition;
 
 namespace Infrastructure
 {
-    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false), MetadataAttribute]
-    public class ViewExportAttribute: ExportAttribute, IViewRegionRegistration
-    {
-        public ViewExportAttribute(): base(typeof (object))
-        {
-        }
+	[AttributeUsage(AttributeTargets.Class, AllowMultiple = false), MetadataAttribute]
+	public class ViewExportAttribute: ExportAttribute, IViewRegionRegistration
+	{
+		public ViewExportAttribute(): base(typeof (object))
+		{
+		}
 
-        public ViewExportAttribute(string viewName): base(viewName, typeof (object))
-        {
-        }
+		public ViewExportAttribute(string viewName): base(viewName, typeof (object))
+		{
+		}
 
-        public string RegionName { get; set; }
-    }
+		public string RegionName { get; set; }
+	}
 }

+ 13 - 13
CSharp/App/Modules/BehaviorTreeModule/AllTreeData.cs

@@ -3,18 +3,18 @@ using System.Runtime.Serialization;
 
 namespace Modules.BehaviorTreeModule
 {
-    [DataContract]
-    public class AllTreeData
-    {
-        private readonly List<TreeNodeData> treeNodeDatas = new List<TreeNodeData>();
+	[DataContract]
+	public class AllTreeData
+	{
+		private readonly List<TreeNodeData> treeNodeDatas = new List<TreeNodeData>();
 
-        [DataMember(Order = 1)]
-        public List<TreeNodeData> TreeNodeDatas
-        {
-            get
-            {
-                return this.treeNodeDatas;
-            }
-        }
-    }
+		[DataMember(Order = 1)]
+		public List<TreeNodeData> TreeNodeDatas
+		{
+			get
+			{
+				return this.treeNodeDatas;
+			}
+		}
+	}
 }

+ 73 - 73
CSharp/App/Modules/BehaviorTreeModule/AllTreeView.xaml.cs

@@ -6,86 +6,86 @@ using Infrastructure;
 
 namespace Modules.BehaviorTreeModule
 {
-    /// <summary>
-    /// BehaviorTreeView.xaml 的交互逻辑
-    /// </summary>
-    [ViewExport(RegionName = "BehaviorTreeRegion"), PartCreationPolicy(CreationPolicy.NonShared)]
-    public partial class AllTreeView
-    {
-        public AllTreeView()
-        {
-            this.InitializeComponent();
+	/// <summary>
+	/// BehaviorTreeView.xaml 的交互逻辑
+	/// </summary>
+	[ViewExport(RegionName = "BehaviorTreeRegion"), PartCreationPolicy(CreationPolicy.NonShared)]
+	public partial class AllTreeView
+	{
+		public AllTreeView()
+		{
+			this.InitializeComponent();
 
-            this.nodeDataEditor.AllTreeView = this;
-            this.treeView.AllTreeView = this;
-        }
+			this.nodeDataEditor.AllTreeView = this;
+			this.treeView.AllTreeView = this;
+		}
 
-        [Import]
-        private AllTreeViewModel ViewModel
-        {
-            get
-            {
-                return this.DataContext as AllTreeViewModel;
-            }
-            set
-            {
-                this.DataContext = value;
-            }
-        }
+		[Import]
+		private AllTreeViewModel ViewModel
+		{
+			get
+			{
+				return this.DataContext as AllTreeViewModel;
+			}
+			set
+			{
+				this.DataContext = value;
+			}
+		}
 
-        private void MenuItem_Open(object sender, RoutedEventArgs e)
-        {
-            string nodePath = ConfigurationManager.AppSettings["NodePath"];
-            this.ViewModel.Open(nodePath);
-            this.lbTreeRoots.SelectedIndex = -1;
-            this.treeView.ViewModel = null;
-        }
+		private void MenuItem_Open(object sender, RoutedEventArgs e)
+		{
+			string nodePath = ConfigurationManager.AppSettings["NodePath"];
+			this.ViewModel.Open(nodePath);
+			this.lbTreeRoots.SelectedIndex = -1;
+			this.treeView.ViewModel = null;
+		}
 
-        private void MenuItem_Save(object sender, RoutedEventArgs e)
-        {
-            string nodePath = ConfigurationManager.AppSettings["NodePath"];
-            this.ViewModel.Save(nodePath);
-        }
+		private void MenuItem_Save(object sender, RoutedEventArgs e)
+		{
+			string nodePath = ConfigurationManager.AppSettings["NodePath"];
+			this.ViewModel.Save(nodePath);
+		}
 
-        private void MenuItem_New(object sender, RoutedEventArgs e)
-        {
-            TreeViewModel treeViewModel = new TreeViewModel(this.ViewModel);
-            this.ViewModel.Add(treeViewModel);
-            this.treeView.ViewModel = treeViewModel;
-        }
+		private void MenuItem_New(object sender, RoutedEventArgs e)
+		{
+			TreeViewModel treeViewModel = new TreeViewModel(this.ViewModel);
+			this.ViewModel.Add(treeViewModel);
+			this.treeView.ViewModel = treeViewModel;
+		}
 
-        private void MenuItem_Remove(object sender, RoutedEventArgs e)
-        {
-            if (this.lbTreeRoots.SelectedItem == null)
-            {
-                return;
-            }
-            var treeNodeViewModel = this.lbTreeRoots.SelectedItem as TreeNodeViewModel;
-            this.ViewModel.Remove(treeNodeViewModel);
-            this.lbTreeRoots.SelectedItem = null;
-            e.Handled = true;
-        }
+		private void MenuItem_Remove(object sender, RoutedEventArgs e)
+		{
+			if (this.lbTreeRoots.SelectedItem == null)
+			{
+				return;
+			}
+			var treeNodeViewModel = this.lbTreeRoots.SelectedItem as TreeNodeViewModel;
+			this.ViewModel.Remove(treeNodeViewModel);
+			this.lbTreeRoots.SelectedItem = null;
+			e.Handled = true;
+		}
 
-        private void ListBoxItem_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
-        {
-            var item = (FrameworkElement) sender;
-            var treeNodeViewModel = item.DataContext as TreeNodeViewModel;
-            if (this.treeView.ViewModel != null)
-            {
-                if (this.treeView.ViewModel.TreeId == treeNodeViewModel.TreeId)
-                {
-                    return;
-                }
-            }
-            this.treeView.ViewModel = this.ViewModel.Get(treeNodeViewModel.TreeId);
-        }
+		private void ListBoxItem_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+		{
+			var item = (FrameworkElement) sender;
+			var treeNodeViewModel = item.DataContext as TreeNodeViewModel;
+			if (this.treeView.ViewModel != null)
+			{
+				if (this.treeView.ViewModel.TreeId == treeNodeViewModel.TreeId)
+				{
+					return;
+				}
+			}
+			this.treeView.ViewModel = this.ViewModel.Get(treeNodeViewModel.TreeId);
+		}
 
-        private void ListBoxItem_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
-        {
-            var item = (FrameworkElement) sender;
-            var treeNodeViewModel = item.DataContext as TreeNodeViewModel;
+		private void ListBoxItem_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
+		{
+			var item = (FrameworkElement) sender;
+			var treeNodeViewModel = item.DataContext as TreeNodeViewModel;
 
-            this.lbTreeRoots.SelectedItem = treeNodeViewModel;
-        }
-    }
+			this.lbTreeRoots.SelectedItem = treeNodeViewModel;
+		}
+	}
 }

+ 84 - 88
CSharp/App/Modules/BehaviorTreeModule/AllTreeViewModel.cs

@@ -6,106 +6,102 @@ using Common.Helper;
 
 namespace Modules.BehaviorTreeModule
 {
-    [Export(contractType: typeof (AllTreeViewModel)),
-     PartCreationPolicy(creationPolicy: CreationPolicy.NonShared)]
-    public class AllTreeViewModel
-    {
-        public int MaxNodeId { get; set; }
-        public int MaxTreeId { get; set; }
+	[Export(contractType: typeof (AllTreeViewModel)),
+	 PartCreationPolicy(creationPolicy: CreationPolicy.NonShared)]
+	public class AllTreeViewModel
+	{
+		public int MaxNodeId { get; set; }
+		public int MaxTreeId { get; set; }
 
-        private readonly Dictionary<int, TreeViewModel> treeViewModelsDict =
-                new Dictionary<int, TreeViewModel>();
+		private readonly Dictionary<int, TreeViewModel> treeViewModelsDict =
+				new Dictionary<int, TreeViewModel>();
 
-        public readonly ObservableCollection<TreeNodeViewModel> rootList =
-                new ObservableCollection<TreeNodeViewModel>();
+		public readonly ObservableCollection<TreeNodeViewModel> rootList =
+				new ObservableCollection<TreeNodeViewModel>();
 
-        public ObservableCollection<TreeNodeViewModel> RootList
-        {
-            get
-            {
-                return this.rootList;
-            }
-        }
+		public ObservableCollection<TreeNodeViewModel> RootList
+		{
+			get
+			{
+				return this.rootList;
+			}
+		}
 
-        public void Open(string file)
-        {
-            this.rootList.Clear();
-            this.treeViewModelsDict.Clear();
+		public void Open(string file)
+		{
+			this.rootList.Clear();
+			this.treeViewModelsDict.Clear();
 
-            var treeDict = new Dictionary<int, List<TreeNodeData>>();
+			var treeDict = new Dictionary<int, List<TreeNodeData>>();
 
-            byte[] bytes = File.ReadAllBytes(file);
-            var allTreeData = ProtobufHelper.FromBytes<AllTreeData>(bytes);
+			byte[] bytes = File.ReadAllBytes(file);
+			var allTreeData = ProtobufHelper.FromBytes<AllTreeData>(bytes);
 
-            this.MaxNodeId = 0;
-            this.MaxTreeId = 0;
-            foreach (TreeNodeData treeNodeData in allTreeData.TreeNodeDatas)
-            {
-                List<TreeNodeData> tree;
-                treeDict.TryGetValue(treeNodeData.TreeId, out tree);
-                if (tree == null)
-                {
-                    tree = new List<TreeNodeData>();
-                    treeDict[treeNodeData.TreeId] = tree;
-                }
-                tree.Add(treeNodeData);
-                if (treeNodeData.Id > this.MaxNodeId)
-                {
-                    this.MaxNodeId = treeNodeData.Id;
-                }
-                if (treeNodeData.TreeId > this.MaxTreeId)
-                {
-                    this.MaxTreeId = treeNodeData.TreeId;
-                }
-            }
+			this.MaxNodeId = 0;
+			this.MaxTreeId = 0;
+			foreach (TreeNodeData treeNodeData in allTreeData.TreeNodeDatas)
+			{
+				List<TreeNodeData> tree;
+				treeDict.TryGetValue(treeNodeData.TreeId, out tree);
+				if (tree == null)
+				{
+					tree = new List<TreeNodeData>();
+					treeDict[treeNodeData.TreeId] = tree;
+				}
+				tree.Add(treeNodeData);
+				if (treeNodeData.Id > this.MaxNodeId)
+				{
+					this.MaxNodeId = treeNodeData.Id;
+				}
+				if (treeNodeData.TreeId > this.MaxTreeId)
+				{
+					this.MaxTreeId = treeNodeData.TreeId;
+				}
+			}
 
-            foreach (KeyValuePair<int, List<TreeNodeData>> pair in treeDict)
-            {
-                var treeViewModel = new TreeViewModel(pair.Value)
-                {
-                    AllTreeViewModel = this,
-                    TreeId = pair.Key
-                };
-                this.treeViewModelsDict[pair.Key] = treeViewModel;
-                this.RootList.Add(treeViewModel.Root);
-            }
-        }
+			foreach (KeyValuePair<int, List<TreeNodeData>> pair in treeDict)
+			{
+				var treeViewModel = new TreeViewModel(pair.Value) { AllTreeViewModel = this, TreeId = pair.Key };
+				this.treeViewModelsDict[pair.Key] = treeViewModel;
+				this.RootList.Add(treeViewModel.Root);
+			}
+		}
 
-        public void Save(string file)
-        {
-            AllTreeData allTreeData = new AllTreeData();
-            foreach (var value in this.treeViewModelsDict.Values)
-            {
-                List<TreeNodeData> list = value.GetDatas();
-                allTreeData.TreeNodeDatas.AddRange(list);
-            }
+		public void Save(string file)
+		{
+			AllTreeData allTreeData = new AllTreeData();
+			foreach (var value in this.treeViewModelsDict.Values)
+			{
+				List<TreeNodeData> list = value.GetDatas();
+				allTreeData.TreeNodeDatas.AddRange(list);
+			}
 
-            using (Stream stream = new FileStream(file, FileMode.Create, FileAccess.Write))
-            {
-                byte[] bytes = ProtobufHelper.ToBytes(allTreeData);
-                stream.Write(bytes, 0, bytes.Length);
-            }
-        }
+			using (Stream stream = new FileStream(file, FileMode.Create, FileAccess.Write))
+			{
+				byte[] bytes = ProtobufHelper.ToBytes(allTreeData);
+				stream.Write(bytes, 0, bytes.Length);
+			}
+		}
 
-        public void New(TreeViewModel treeViewModel)
-        {
-        }
+		public void New(TreeViewModel treeViewModel)
+		{
+		}
 
-        public void Add(TreeViewModel treeViewModel)
-        {
-            this.treeViewModelsDict[treeViewModel.TreeId] = treeViewModel;
-            this.rootList.Add(treeViewModel.Root);
-        }
+		public void Add(TreeViewModel treeViewModel)
+		{
+			this.treeViewModelsDict[treeViewModel.TreeId] = treeViewModel;
+			this.rootList.Add(treeViewModel.Root);
+		}
 
-        public void Remove(TreeNodeViewModel treeViewModel)
-        {
-            this.treeViewModelsDict.Remove(treeViewModel.TreeId);
-            this.rootList.Remove(treeViewModel);
-        }
+		public void Remove(TreeNodeViewModel treeViewModel)
+		{
+			this.treeViewModelsDict.Remove(treeViewModel.TreeId);
+			this.rootList.Remove(treeViewModel);
+		}
 
-        public TreeViewModel Get(int treeId)
-        {
-            return this.treeViewModelsDict[treeId];
-        }
-    }
+		public TreeViewModel Get(int treeId)
+		{
+			return this.treeViewModelsDict[treeId];
+		}
+	}
 }

+ 21 - 22
CSharp/App/Modules/BehaviorTreeModule/FolderVisiableConverter.cs

@@ -5,27 +5,26 @@ using System.Windows.Data;
 
 namespace Modules.BehaviorTreeModule
 {
-    [ValueConversion(typeof (bool), typeof (Visibility))]
-    public class FolderVisiableConverter: IValueConverter
-    {
-        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
-        {
-            if (value == null)
-            {
-                return 0;
-            }
-            bool isFolder = (bool) value;
-            if (isFolder)
-            {
-                return Visibility.Visible;
-            }
-            return Visibility.Hidden;
-        }
+	[ValueConversion(typeof (bool), typeof (Visibility))]
+	public class FolderVisiableConverter: IValueConverter
+	{
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return 0;
+			}
+			bool isFolder = (bool) value;
+			if (isFolder)
+			{
+				return Visibility.Visible;
+			}
+			return Visibility.Hidden;
+		}
 
-        public object ConvertBack(
-                object value, Type targetType, object parameter, CultureInfo culture)
-        {
-            return null;
-        }
-    }
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+	}
 }

+ 32 - 33
CSharp/App/Modules/BehaviorTreeModule/ListToStringConverter.cs

@@ -6,38 +6,37 @@ using System.Windows.Data;
 
 namespace Modules.BehaviorTreeModule
 {
-    [ValueConversion(typeof (List<string>), typeof (string))]
-    public class ListToStringConverter: IValueConverter
-    {
-        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
-        {
-            if (value == null)
-            {
-                return "";
-            }
-            var list = (List<string>) value;
-            return String.Join(",", list);
-        }
+	[ValueConversion(typeof (List<string>), typeof (string))]
+	public class ListToStringConverter: IValueConverter
+	{
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return "";
+			}
+			var list = (List<string>) value;
+			return String.Join(",", list);
+		}
 
-        public object ConvertBack(
-                object value, Type targetType, object parameter, CultureInfo culture)
-        {
-            if (value == null)
-            {
-                return new List<string>();
-            }
-            var s = (string) value;
-            s = s.Trim();
-            if (s == "")
-            {
-                return new List<string>();
-            }
-            string[] ss = s.Split(',');
-            for (int i = 0; i < ss.Length; ++i)
-            {
-                ss[i] = ss[i].Trim();
-            }
-            return ss.ToList();
-        }
-    }
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return new List<string>();
+			}
+			var s = (string) value;
+			s = s.Trim();
+			if (s == "")
+			{
+				return new List<string>();
+			}
+			string[] ss = s.Split(',');
+			for (int i = 0; i < ss.Length; ++i)
+			{
+				ss[i] = ss[i].Trim();
+			}
+			return ss.ToList();
+		}
+	}
 }

+ 46 - 46
CSharp/App/Modules/BehaviorTreeModule/NodeDataEditor.xaml.cs

@@ -5,55 +5,55 @@ using Common.Helper;
 
 namespace Modules.BehaviorTreeModule
 {
-    /// <summary>
-    /// NodeDataEditor.xaml 的交互逻辑
-    /// </summary>
-    public partial class NodeDataEditor
-    {
-        public NodeDataEditor()
-        {
-            this.InitializeComponent();
+	/// <summary>
+	/// NodeDataEditor.xaml 的交互逻辑
+	/// </summary>
+	public partial class NodeDataEditor
+	{
+		public NodeDataEditor()
+		{
+			this.InitializeComponent();
 
-            string[] nodeTypes = Enum.GetNames(typeof (NodeType));
-            this.cbType.ItemsSource = nodeTypes;
-        }
+			string[] nodeTypes = Enum.GetNames(typeof (NodeType));
+			this.cbType.ItemsSource = nodeTypes;
+		}
 
-        public AllTreeView AllTreeView { get; set; }
+		public AllTreeView AllTreeView { get; set; }
 
-        public TreeNodeViewModel TreeNodeViewModel
-        {
-            get
-            {
-                return this.DataContext as TreeNodeViewModel;
-            }
-            set
-            {
-                this.DataContext = value;
-            }
-        }
+		public TreeNodeViewModel TreeNodeViewModel
+		{
+			get
+			{
+				return this.DataContext as TreeNodeViewModel;
+			}
+			set
+			{
+				this.DataContext = value;
+			}
+		}
 
-        private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
-        {
-            if (this.TreeNodeViewModel == null)
-            {
-                return;
-            }
-            this.cbType.SelectedIndex = EnumHelper.EnumIndex<NodeType>(this.TreeNodeViewModel.Type);
-        }
+		private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
+		{
+			if (this.TreeNodeViewModel == null)
+			{
+				return;
+			}
+			this.cbType.SelectedIndex = EnumHelper.EnumIndex<NodeType>(this.TreeNodeViewModel.Type);
+		}
 
-        private void CbType_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
-        {
-            if (this.TreeNodeViewModel == null)
-            {
-                return;
-            }
-            if (this.cbType.SelectedValue == null)
-            {
-                this.TreeNodeViewModel.Type = 0;
-                return;
-            }
-            this.TreeNodeViewModel.Type =
-                    (int) Enum.Parse(typeof (NodeType), this.cbType.SelectedValue.ToString().Trim());
-        }
-    }
+		private void CbType_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
+		{
+			if (this.TreeNodeViewModel == null)
+			{
+				return;
+			}
+			if (this.cbType.SelectedValue == null)
+			{
+				this.TreeNodeViewModel.Type = 0;
+				return;
+			}
+			this.TreeNodeViewModel.Type =
+					(int) Enum.Parse(typeof (NodeType), this.cbType.SelectedValue.ToString().Trim());
+		}
+	}
 }

+ 31 - 31
CSharp/App/Modules/BehaviorTreeModule/NodeType.cs

@@ -1,36 +1,36 @@
 namespace Modules.BehaviorTreeModule
 {
-    public enum NodeType
-    {
-        Selector = 1,
-        Sequence = 2,
-        Not = 10,
-        Weight = 11,
+	public enum NodeType
+	{
+		Selector = 1,
+		Sequence = 2,
+		Not = 10,
+		Weight = 11,
 
-        // condition节点 10000开始
-        SelectTarget = 10000,
-        Roll = 10001,
-        Compare = 10002,
-        BulletDistance = 10003,
-        OwnBuff = 10004,
-        FriendDieInDistance = 10005,
-        LessHp = 10007,
-        InGlobalCD = 10008,
-        TargetDie = 100010,
-        TargetDistance = 100011,
-        UnitState = 100012,
+		// condition节点 10000开始
+		SelectTarget = 10000,
+		Roll = 10001,
+		Compare = 10002,
+		BulletDistance = 10003,
+		OwnBuff = 10004,
+		FriendDieInDistance = 10005,
+		LessHp = 10007,
+		InGlobalCD = 10008,
+		TargetDie = 100010,
+		TargetDistance = 100011,
+		UnitState = 100012,
 
-        // action节点 20000开始
-        CastSpell = 20000,
-        Chase = 20001,
-        Empty = 20002,
-        Patrol = 20003,
-        Idle = 20004,
-        CastDefaultSpell = 20005,
-        Destroy = 20006,
-        Move = 20007,
-        CloseTarget = 20008,
-        LeaveTarget = 20009,
-        PathPatrol = 20010,
-    }
+		// action节点 20000开始
+		CastSpell = 20000,
+		Chase = 20001,
+		Empty = 20002,
+		Patrol = 20003,
+		Idle = 20004,
+		CastDefaultSpell = 20005,
+		Destroy = 20006,
+		Move = 20007,
+		CloseTarget = 20008,
+		LeaveTarget = 20009,
+		PathPatrol = 20010,
+	}
 }

+ 33 - 34
CSharp/App/Modules/BehaviorTreeModule/NodeTypeColorConverter.cs

@@ -4,39 +4,38 @@ using System.Windows.Data;
 
 namespace Modules.BehaviorTreeModule
 {
-    [ValueConversion(typeof (int), typeof (int))]
-    public class NodeTypeColorConverter: IValueConverter
-    {
-        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
-        {
-            if (value == null)
-            {
-                return 0;
-            }
-            int nodeType = (int) value;
-            if (nodeType == (int) NodeType.Selector)
-            {
-                return "selector";
-            }
-            if (nodeType == (int) NodeType.Sequence)
-            {
-                return "sequence";
-            }
-            if (nodeType < 20000 && nodeType >= 10000)
-            {
-                return "condition";
-            }
-            if (nodeType < 30000 && nodeType >= 20000)
-            {
-                return "action";
-            }
-            return "other";
-        }
+	[ValueConversion(typeof (int), typeof (int))]
+	public class NodeTypeColorConverter: IValueConverter
+	{
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return 0;
+			}
+			int nodeType = (int) value;
+			if (nodeType == (int) NodeType.Selector)
+			{
+				return "selector";
+			}
+			if (nodeType == (int) NodeType.Sequence)
+			{
+				return "sequence";
+			}
+			if (nodeType < 20000 && nodeType >= 10000)
+			{
+				return "condition";
+			}
+			if (nodeType < 30000 && nodeType >= 20000)
+			{
+				return "action";
+			}
+			return "other";
+		}
 
-        public object ConvertBack(
-                object value, Type targetType, object parameter, CultureInfo culture)
-        {
-            return null;
-        }
-    }
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+	}
 }

+ 16 - 17
CSharp/App/Modules/BehaviorTreeModule/NodeTypeToStringConverter.cs

@@ -4,22 +4,21 @@ using System.Windows.Data;
 
 namespace Modules.BehaviorTreeModule
 {
-    [ValueConversion(typeof (int), typeof (string))]
-    public class NodeTypeToStringConverter: IValueConverter
-    {
-        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
-        {
-            if (value == null)
-            {
-                return "";
-            }
-            return ((NodeType) (int) value).ToString();
-        }
+	[ValueConversion(typeof (int), typeof (string))]
+	public class NodeTypeToStringConverter: IValueConverter
+	{
+		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			if (value == null)
+			{
+				return "";
+			}
+			return ((NodeType) (int) value).ToString();
+		}
 
-        public object ConvertBack(
-                object value, Type targetType, object parameter, CultureInfo culture)
-        {
-            return null;
-        }
-    }
+		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+		{
+			return null;
+		}
+	}
 }

+ 24 - 24
CSharp/App/Modules/BehaviorTreeModule/TreeInfoViewModel.cs

@@ -1,30 +1,30 @@
 namespace Modules.BehaviorTreeModule
 {
-    public class TreeInfoViewModel
-    {
-        private readonly int id;
-        private readonly string comment;
+	public class TreeInfoViewModel
+	{
+		private readonly int id;
+		private readonly string comment;
 
-        public TreeInfoViewModel(int id, string comment)
-        {
-            this.id = id;
-            this.comment = comment;
-        }
+		public TreeInfoViewModel(int id, string comment)
+		{
+			this.id = id;
+			this.comment = comment;
+		}
 
-        public int Id
-        {
-            get
-            {
-                return this.id;
-            }
-        }
+		public int Id
+		{
+			get
+			{
+				return this.id;
+			}
+		}
 
-        public string Comment
-        {
-            get
-            {
-                return this.comment;
-            }
-        }
-    }
+		public string Comment
+		{
+			get
+			{
+				return this.comment;
+			}
+		}
+	}
 }

+ 172 - 176
CSharp/App/Modules/BehaviorTreeModule/TreeLayout.cs

@@ -1,192 +1,188 @@
 namespace Modules.BehaviorTreeModule
 {
-    public class TreeLayout
-    {
-        private readonly TreeViewModel treeViewModel;
-        private const double XGap = 20;
-        private const double YGap = 10;
-        private double rootOrigX;
-        private double rootOrigY;
-        private double rootOffsetX;
-        private double rootOffsetY;
+	public class TreeLayout
+	{
+		private readonly TreeViewModel treeViewModel;
+		private const double XGap = 20;
+		private const double YGap = 10;
+		private double rootOrigX;
+		private double rootOrigY;
+		private double rootOffsetX;
+		private double rootOffsetY;
 
-        public TreeLayout(TreeViewModel treeViewModel)
-        {
-            this.treeViewModel = treeViewModel;
-        }
+		public TreeLayout(TreeViewModel treeViewModel)
+		{
+			this.treeViewModel = treeViewModel;
+		}
 
-        private TreeNodeViewModel LeftMostOffspring(
-                TreeNodeViewModel treeNodeViewModel, int currentLevel, int searchLevel)
-        {
-            if (currentLevel == searchLevel)
-            {
-                return treeNodeViewModel;
-            }
-            for (int i = 0; i < treeNodeViewModel.Children.Count; ++i)
-            {
-                TreeNodeViewModel child = this.treeViewModel.Get(treeNodeViewModel.Children[i]);
-                child.AncestorModify = treeNodeViewModel.Modify + treeNodeViewModel.AncestorModify;
-                TreeNodeViewModel offspring = this.LeftMostOffspring(child, currentLevel + 1,
-                        searchLevel);
-                if (offspring == null)
-                {
-                    continue;
-                }
-                return offspring;
-            }
-            return null;
-        }
+		private TreeNodeViewModel LeftMostOffspring(
+				TreeNodeViewModel treeNodeViewModel, int currentLevel, int searchLevel)
+		{
+			if (currentLevel == searchLevel)
+			{
+				return treeNodeViewModel;
+			}
+			for (int i = 0; i < treeNodeViewModel.Children.Count; ++i)
+			{
+				TreeNodeViewModel child = this.treeViewModel.Get(treeNodeViewModel.Children[i]);
+				child.AncestorModify = treeNodeViewModel.Modify + treeNodeViewModel.AncestorModify;
+				TreeNodeViewModel offspring = this.LeftMostOffspring(child, currentLevel + 1, searchLevel);
+				if (offspring == null)
+				{
+					continue;
+				}
+				return offspring;
+			}
+			return null;
+		}
 
-        private TreeNodeViewModel RightMostOffspring(
-                TreeNodeViewModel treeNodeViewModel, int currentLevel, int searchLevel)
-        {
-            if (currentLevel == searchLevel)
-            {
-                return treeNodeViewModel;
-            }
-            for (int i = treeNodeViewModel.Children.Count - 1; i >= 0; --i)
-            {
-                TreeNodeViewModel child = this.treeViewModel.Get(treeNodeViewModel.Children[i]);
-                child.AncestorModify = treeNodeViewModel.Modify + treeNodeViewModel.AncestorModify;
-                TreeNodeViewModel offspring = this.RightMostOffspring(child, currentLevel + 1,
-                        searchLevel);
-                if (offspring == null)
-                {
-                    continue;
-                }
-                return offspring;
-            }
-            return null;
-        }
+		private TreeNodeViewModel RightMostOffspring(
+				TreeNodeViewModel treeNodeViewModel, int currentLevel, int searchLevel)
+		{
+			if (currentLevel == searchLevel)
+			{
+				return treeNodeViewModel;
+			}
+			for (int i = treeNodeViewModel.Children.Count - 1; i >= 0; --i)
+			{
+				TreeNodeViewModel child = this.treeViewModel.Get(treeNodeViewModel.Children[i]);
+				child.AncestorModify = treeNodeViewModel.Modify + treeNodeViewModel.AncestorModify;
+				TreeNodeViewModel offspring = this.RightMostOffspring(child, currentLevel + 1, searchLevel);
+				if (offspring == null)
+				{
+					continue;
+				}
+				return offspring;
+			}
+			return null;
+		}
 
-        private void AjustSubTreeGap(TreeNodeViewModel left, TreeNodeViewModel right)
-        {
-            double offset = 0;
-            TreeNodeViewModel tLeft = left;
-            TreeNodeViewModel tRight = right;
-            left.AncestorModify = 0;
-            right.AncestorModify = 0;
-            for (int i = 0; tLeft != null && tRight != null; ++i)
-            {
-                double tGap = (tRight.Prelim + tRight.AncestorModify) -
-                              (tLeft.Prelim + tLeft.AncestorModify);
-                if (XGap + TreeNodeViewModel.Width - tGap > offset)
-                {
-                    offset = XGap + TreeNodeViewModel.Width - tGap;
-                }
-                tLeft = this.RightMostOffspring(left, 0, i + 1);
-                tRight = this.LeftMostOffspring(right, 0, i + 1);
-            }
-            right.Modify += offset;
-            right.Prelim += offset;
-        }
+		private void AjustSubTreeGap(TreeNodeViewModel left, TreeNodeViewModel right)
+		{
+			double offset = 0;
+			TreeNodeViewModel tLeft = left;
+			TreeNodeViewModel tRight = right;
+			left.AncestorModify = 0;
+			right.AncestorModify = 0;
+			for (int i = 0; tLeft != null && tRight != null; ++i)
+			{
+				double tGap = (tRight.Prelim + tRight.AncestorModify) - (tLeft.Prelim + tLeft.AncestorModify);
+				if (XGap + TreeNodeViewModel.Width - tGap > offset)
+				{
+					offset = XGap + TreeNodeViewModel.Width - tGap;
+				}
+				tLeft = this.RightMostOffspring(left, 0, i + 1);
+				tRight = this.LeftMostOffspring(right, 0, i + 1);
+			}
+			right.Modify += offset;
+			right.Prelim += offset;
+		}
 
-        private void AjustTreeGap(TreeNodeViewModel treeNodeViewModel)
-        {
-            for (int i = 0; i < treeNodeViewModel.Children.Count - 1; ++i)
-            {
-                for (int j = i + 1; j < treeNodeViewModel.Children.Count; ++j)
-                {
-                    TreeNodeViewModel left = this.treeViewModel.Get(treeNodeViewModel.Children[i]);
-                    TreeNodeViewModel right = this.treeViewModel.Get(treeNodeViewModel.Children[j]);
-                    this.AjustSubTreeGap(left, right);
-                }
-            }
-        }
+		private void AjustTreeGap(TreeNodeViewModel treeNodeViewModel)
+		{
+			for (int i = 0; i < treeNodeViewModel.Children.Count - 1; ++i)
+			{
+				for (int j = i + 1; j < treeNodeViewModel.Children.Count; ++j)
+				{
+					TreeNodeViewModel left = this.treeViewModel.Get(treeNodeViewModel.Children[i]);
+					TreeNodeViewModel right = this.treeViewModel.Get(treeNodeViewModel.Children[j]);
+					this.AjustSubTreeGap(left, right);
+				}
+			}
+		}
 
-        private void CalculatePrelimAndModify(TreeNodeViewModel treeNodeViewModel)
-        {
-            foreach (int childId in treeNodeViewModel.Children)
-            {
-                TreeNodeViewModel child = this.treeViewModel.Get(childId);
-                this.CalculatePrelimAndModify(child);
-            }
+		private void CalculatePrelimAndModify(TreeNodeViewModel treeNodeViewModel)
+		{
+			foreach (int childId in treeNodeViewModel.Children)
+			{
+				TreeNodeViewModel child = this.treeViewModel.Get(childId);
+				this.CalculatePrelimAndModify(child);
+			}
 
-            double prelim = 0;
-            double modify = 0;
+			double prelim = 0;
+			double modify = 0;
 
-            if (treeNodeViewModel.IsLeaf)
-            {
-                if (treeNodeViewModel.LeftSibling == null)
-                {
-                    // 如果没有左邻居,不需要设置modify
-                    prelim = 0;
-                }
-                else
-                {
-                    prelim = treeNodeViewModel.LeftSibling.Prelim + TreeNodeViewModel.Width + XGap;
-                }
-            }
-            else
-            {
-                // 调整子树间的间距
-                this.AjustTreeGap(treeNodeViewModel);
-                double childrenCenter = (treeNodeViewModel.FirstChild.Prelim +
-                                         treeNodeViewModel.LastChild.Prelim) / 2;
-                if (treeNodeViewModel.LeftSibling == null)
-                {
-                    // 如果没有左邻居,不需要设置modify
-                    prelim = childrenCenter;
-                }
-                else
-                {
-                    prelim = treeNodeViewModel.LeftSibling.Prelim + TreeNodeViewModel.Width + XGap;
-                    modify = prelim - childrenCenter;
-                }
-            }
-            treeNodeViewModel.Prelim = prelim;
-            treeNodeViewModel.Modify = modify;
+			if (treeNodeViewModel.IsLeaf)
+			{
+				if (treeNodeViewModel.LeftSibling == null)
+				{
+					// 如果没有左邻居,不需要设置modify
+					prelim = 0;
+				}
+				else
+				{
+					prelim = treeNodeViewModel.LeftSibling.Prelim + TreeNodeViewModel.Width + XGap;
+				}
+			}
+			else
+			{
+				// 调整子树间的间距
+				this.AjustTreeGap(treeNodeViewModel);
+				double childrenCenter = (treeNodeViewModel.FirstChild.Prelim +
+				                         treeNodeViewModel.LastChild.Prelim) / 2;
+				if (treeNodeViewModel.LeftSibling == null)
+				{
+					// 如果没有左邻居,不需要设置modify
+					prelim = childrenCenter;
+				}
+				else
+				{
+					prelim = treeNodeViewModel.LeftSibling.Prelim + TreeNodeViewModel.Width + XGap;
+					modify = prelim - childrenCenter;
+				}
+			}
+			treeNodeViewModel.Prelim = prelim;
+			treeNodeViewModel.Modify = modify;
 
-            // Log.Debug("Id: " + treeNodeViewModel.Id + " Prelim: " + treeNodeViewModel.Prelim + " Modify: " +
-            // 	treeNodeViewModel.Modify);
-        }
+			// Log.Debug("Id: " + treeNodeViewModel.Id + " Prelim: " + treeNodeViewModel.Prelim + " Modify: " +
+			// 	treeNodeViewModel.Modify);
+		}
 
-        private void CalculateRelativeXAndY(
-                TreeNodeViewModel treeNodeViewModel, int level, double totalModify)
-        {
-            foreach (int childId in treeNodeViewModel.Children)
-            {
-                TreeNodeViewModel child = this.treeViewModel.Get(childId);
-                this.CalculateRelativeXAndY(child, level + 1, treeNodeViewModel.Modify + totalModify);
-            }
-            if (treeNodeViewModel.IsLeaf)
-            {
-                treeNodeViewModel.X = treeNodeViewModel.Prelim + totalModify;
-            }
-            else
-            {
-                treeNodeViewModel.X = (treeNodeViewModel.FirstChild.X +
-                                       treeNodeViewModel.LastChild.X) / 2;
-            }
-            treeNodeViewModel.Y = level * (TreeNodeViewModel.Height + YGap);
-        }
+		private void CalculateRelativeXAndY(
+				TreeNodeViewModel treeNodeViewModel, int level, double totalModify)
+		{
+			foreach (int childId in treeNodeViewModel.Children)
+			{
+				TreeNodeViewModel child = this.treeViewModel.Get(childId);
+				this.CalculateRelativeXAndY(child, level + 1, treeNodeViewModel.Modify + totalModify);
+			}
+			if (treeNodeViewModel.IsLeaf)
+			{
+				treeNodeViewModel.X = treeNodeViewModel.Prelim + totalModify;
+			}
+			else
+			{
+				treeNodeViewModel.X = (treeNodeViewModel.FirstChild.X + treeNodeViewModel.LastChild.X) / 2;
+			}
+			treeNodeViewModel.Y = level * (TreeNodeViewModel.Height + YGap);
+		}
 
-        private void FixXAndY(TreeNodeViewModel treeNode)
-        {
-            treeNode.X += this.rootOffsetX;
-            treeNode.Y += this.rootOffsetY;
-            foreach (var childId in treeNode.Children)
-            {
-                TreeNodeViewModel child = this.treeViewModel.Get(childId);
-                this.FixXAndY(child);
-            }
-        }
+		private void FixXAndY(TreeNodeViewModel treeNode)
+		{
+			treeNode.X += this.rootOffsetX;
+			treeNode.Y += this.rootOffsetY;
+			foreach (var childId in treeNode.Children)
+			{
+				TreeNodeViewModel child = this.treeViewModel.Get(childId);
+				this.FixXAndY(child);
+			}
+		}
 
-        public void ExcuteLayout()
-        {
-            TreeNodeViewModel root = this.treeViewModel.Root;
-            if (root == null)
-            {
-                return;
-            }
-            this.rootOrigX = root.X;
-            this.rootOrigY = root.Y;
-            this.CalculatePrelimAndModify(root);
-            this.CalculateRelativeXAndY(root, 0, 0);
+		public void ExcuteLayout()
+		{
+			TreeNodeViewModel root = this.treeViewModel.Root;
+			if (root == null)
+			{
+				return;
+			}
+			this.rootOrigX = root.X;
+			this.rootOrigY = root.Y;
+			this.CalculatePrelimAndModify(root);
+			this.CalculateRelativeXAndY(root, 0, 0);
 
-            this.rootOffsetX = this.rootOrigX - root.X;
-            this.rootOffsetY = this.rootOrigY - root.Y;
-            this.FixXAndY(root);
-        }
-    }
+			this.rootOffsetX = this.rootOrigX - root.X;
+			this.rootOffsetY = this.rootOrigY - root.Y;
+			this.FixXAndY(root);
+		}
+	}
 }

+ 7 - 7
CSharp/App/Modules/BehaviorTreeModule/TreeModule.cs

@@ -3,11 +3,11 @@ using Microsoft.Practices.Prism.Modularity;
 
 namespace Modules.BehaviorTreeModule
 {
-    [ModuleExport(moduleType: typeof (TreeModule))]
-    public class TreeModule: IModule
-    {
-        public void Initialize()
-        {
-        }
-    }
+	[ModuleExport(moduleType: typeof (TreeModule))]
+	public class TreeModule: IModule
+	{
+		public void Initialize()
+		{
+		}
+	}
 }

+ 53 - 53
CSharp/App/Modules/BehaviorTreeModule/TreeNodeData.cs

@@ -3,57 +3,57 @@ using System.Runtime.Serialization;
 
 namespace Modules.BehaviorTreeModule
 {
-    [DataContract]
-    public class TreeNodeData
-    {
-        private readonly List<int> children = new List<int>();
-
-        /// <summary>
-        /// 节点唯一Id
-        /// </summary>
-        [DataMember(Order = 1)]
-        public int Id { get; set; }
-
-        /// <summary>
-        /// 节点类型
-        /// </summary>
-        [DataMember(Order = 2)]
-        public int Type { get; set; }
-
-        /// <summary>
-        /// 节点配置参数
-        /// </summary>
-        [DataMember(Order = 3)]
-        public List<string> Args { get; set; }
-
-        /// <summary>
-        /// 父节点
-        /// </summary>
-        [DataMember(Order = 4)]
-        public int Parent { get; set; }
-
-        /// <summary>
-        /// 子节点
-        /// </summary>
-        [DataMember(Order = 5)]
-        public List<int> Children
-        {
-            get
-            {
-                return this.children;
-            }
-        }
-
-        /// <summary>
-        /// 该节点属于哪颗树
-        /// </summary>
-        [DataMember(Order = 6)]
-        public int TreeId { get; set; }
-
-        /// <summary>
-        /// 节点说明
-        /// </summary>
-        [DataMember(Order = 7)]
-        public string Comment { get; set; }
-    }
+	[DataContract]
+	public class TreeNodeData
+	{
+		private readonly List<int> children = new List<int>();
+
+		/// <summary>
+		/// 节点唯一Id
+		/// </summary>
+		[DataMember(Order = 1)]
+		public int Id { get; set; }
+
+		/// <summary>
+		/// 节点类型
+		/// </summary>
+		[DataMember(Order = 2)]
+		public int Type { get; set; }
+
+		/// <summary>
+		/// 节点配置参数
+		/// </summary>
+		[DataMember(Order = 3)]
+		public List<string> Args { get; set; }
+
+		/// <summary>
+		/// 父节点
+		/// </summary>
+		[DataMember(Order = 4)]
+		public int Parent { get; set; }
+
+		/// <summary>
+		/// 子节点
+		/// </summary>
+		[DataMember(Order = 5)]
+		public List<int> Children
+		{
+			get
+			{
+				return this.children;
+			}
+		}
+
+		/// <summary>
+		/// 该节点属于哪颗树
+		/// </summary>
+		[DataMember(Order = 6)]
+		public int TreeId { get; set; }
+
+		/// <summary>
+		/// 节点说明
+		/// </summary>
+		[DataMember(Order = 7)]
+		public string Comment { get; set; }
+	}
 }

+ 404 - 404
CSharp/App/Modules/BehaviorTreeModule/TreeNodeViewModel.cs

@@ -4,408 +4,408 @@ using Microsoft.Practices.Prism.Mvvm;
 
 namespace Modules.BehaviorTreeModule
 {
-    public class TreeNodeViewModel: BindableBase
-    {
-        private static double width = 80;
-        private static double height = 50;
-        private readonly TreeViewModel treeViewModel;
-        private readonly TreeNodeData data;
-        private double x;
-        private double y;
-        private double connectorX2;
-        private double connectorY2;
-        private double prelim;
-        private double modify;
-        private double ancestorModify;
-        private bool isFold;
-
-        public TreeNodeViewModel(TreeViewModel treeViewModel, double x, double y)
-        {
-            this.treeViewModel = treeViewModel;
-            this.x = x;
-            this.y = y;
-            this.data = new TreeNodeData();
-            this.data.Id = ++treeViewModel.AllTreeViewModel.MaxNodeId;
-            this.data.TreeId = treeViewModel.TreeId;
-            this.data.Parent = 0;
-            this.connectorX2 = 0;
-            this.connectorY2 = Height / 2;
-        }
-
-        public TreeNodeViewModel(TreeViewModel treeViewModel, TreeNodeViewModel parent)
-        {
-            this.treeViewModel = treeViewModel;
-            this.data = new TreeNodeData();
-            this.data.Id = ++treeViewModel.AllTreeViewModel.MaxNodeId;
-            this.data.TreeId = treeViewModel.TreeId;
-            this.Parent = parent;
-
-            this.connectorX2 = Width + this.Parent.X - this.X;
-            this.connectorY2 = Height / 2 + this.Parent.Y - this.Y;
-        }
-
-        public TreeNodeViewModel(TreeViewModel treeViewModel, TreeNodeData data)
-        {
-            this.treeViewModel = treeViewModel;
-            this.data = data;
-            if (this.IsRoot)
-            {
-                this.x = 300;
-                this.y = 100;
-                this.connectorX2 = 0;
-                this.connectorY2 = Height / 2;
-            }
-            else
-            {
-                this.connectorX2 = Width + this.Parent.X - this.X;
-                this.connectorY2 = Height / 2 + this.Parent.Y - this.Y;
-            }
-        }
-
-        public TreeNodeData Data
-        {
-            get
-            {
-                return this.data;
-            }
-        }
-
-        public int Id
-        {
-            get
-            {
-                return this.data.Id;
-            }
-            set
-            {
-                if (this.data.Id == value)
-                {
-                    return;
-                }
-                this.data.Id = value;
-                this.OnPropertyChanged("Id");
-            }
-        }
-
-        public string Comment
-        {
-            get
-            {
-                return this.data.Comment;
-            }
-            set
-            {
-                if (this.data.Comment == value)
-                {
-                    return;
-                }
-                this.data.Comment = value;
-                this.OnPropertyChanged("Comment");
-            }
-        }
-
-        public static double Width
-        {
-            get
-            {
-                return width;
-            }
-            set
-            {
-                width = value;
-            }
-        }
-
-        public static double Height
-        {
-            get
-            {
-                return height;
-            }
-            set
-            {
-                height = value;
-            }
-        }
-
-        public bool IsRoot
-        {
-            get
-            {
-                return this.Parent == null;
-            }
-        }
-
-        public double Prelim
-        {
-            get
-            {
-                return this.prelim;
-            }
-            set
-            {
-                this.prelim = value;
-            }
-        }
-
-        public double Modify
-        {
-            get
-            {
-                return this.modify;
-            }
-            set
-            {
-                this.modify = value;
-            }
-        }
-
-        public double X
-        {
-            get
-            {
-                return this.x;
-            }
-            set
-            {
-                if (Math.Abs(this.x - value) < 0.1)
-                {
-                    return;
-                }
-                this.x = value;
-                this.OnPropertyChanged("X");
-
-                if (this.Parent != null)
-                {
-                    this.ConnectorX2 = Width / 2 + this.Parent.X - this.X;
-                }
-
-                foreach (var childId in this.Children)
-                {
-                    TreeNodeViewModel child = this.treeViewModel.Get(childId);
-                    child.ConnectorX2 = Width / 2 + this.X - child.X;
-                }
-            }
-        }
-
-        public double Y
-        {
-            get
-            {
-                return this.y;
-            }
-            set
-            {
-                if (Math.Abs(this.Y - value) < 0.1)
-                {
-                    return;
-                }
-
-                this.y = value;
-                this.OnPropertyChanged("Y");
-
-                if (this.Parent != null)
-                {
-                    this.ConnectorY2 = Height + this.Parent.Y - this.Y;
-                }
-
-                foreach (var childId in this.Children)
-                {
-                    TreeNodeViewModel child = this.treeViewModel.Get(childId);
-                    child.ConnectorY2 = Height + this.Y - child.Y;
-                }
-            }
-        }
-
-        public double ConnectorX1
-        {
-            get
-            {
-                return Width / 2;
-            }
-        }
-
-        public double ConnectorY1
-        {
-            get
-            {
-                return 0;
-            }
-        }
-
-        public double ConnectorX2
-        {
-            get
-            {
-                return this.IsRoot? Width / 2 : this.connectorX2;
-            }
-            set
-            {
-                this.SetProperty(ref this.connectorX2, value);
-            }
-        }
-
-        public double ConnectorY2
-        {
-            get
-            {
-                return this.IsRoot? 0 : this.connectorY2;
-            }
-            set
-            {
-                this.SetProperty(ref this.connectorY2, value);
-            }
-        }
-
-        public int Type
-        {
-            get
-            {
-                return this.data.Type;
-            }
-            set
-            {
-                if (this.data.Type == value)
-                {
-                    return;
-                }
-                this.data.Type = value;
-                this.OnPropertyChanged("Type");
-            }
-        }
-
-        public List<string> Args
-        {
-            get
-            {
-                return this.data.Args;
-            }
-            set
-            {
-                if (this.data.Args == value)
-                {
-                    return;
-                }
-                this.data.Args = value;
-                this.OnPropertyChanged("Args");
-            }
-        }
-
-        public int TreeId
-        {
-            get
-            {
-                return this.data.TreeId;
-            }
-        }
-
-        public TreeNodeViewModel Parent
-        {
-            get
-            {
-                if (this.data.Parent == 0)
-                {
-                    return null;
-                }
-                TreeNodeViewModel parent = this.treeViewModel.Get(this.data.Parent);
-                return parent;
-            }
-            set
-            {
-                if (value == null)
-                {
-                    this.data.Parent = 0;
-                }
-                this.data.Parent = value.Id;
-            }
-        }
-
-        /// <summary>
-        /// 节点是否折叠
-        /// </summary>
-        public bool IsFold
-        {
-            get
-            {
-                return this.isFold;
-            }
-            set
-            {
-                if (this.isFold == value)
-                {
-                    return;
-                }
-                this.isFold = value;
-                this.OnPropertyChanged("IsFold");
-            }
-        }
-
-        public List<int> Children
-        {
-            get
-            {
-                if (this.isFold)
-                {
-                    return new List<int>();
-                }
-                return this.data.Children;
-            }
-        }
-
-        public TreeNodeViewModel LeftSibling
-        {
-            get
-            {
-                if (this.IsRoot)
-                {
-                    return null;
-                }
-
-                int index = this.Parent.Children.IndexOf(this.Id);
-                return index == 0? null : this.treeViewModel.Get(this.Parent.Children[index - 1]);
-            }
-        }
-
-        public TreeNodeViewModel LastChild
-        {
-            get
-            {
-                if (this.Children.Count == 0)
-                {
-                    return null;
-                }
-
-                int maxIndex = this.Children.Count - 1;
-                return this.treeViewModel.Get(this.Children[maxIndex]);
-            }
-        }
-
-        public TreeNodeViewModel FirstChild
-        {
-            get
-            {
-                return this.Children.Count == 0? null : this.treeViewModel.Get(this.Children[0]);
-            }
-        }
-
-        public bool IsLeaf
-        {
-            get
-            {
-                return this.Children.Count == 0;
-            }
-        }
-
-        public double AncestorModify
-        {
-            get
-            {
-                return this.ancestorModify;
-            }
-            set
-            {
-                this.ancestorModify = value;
-            }
-        }
-    }
+	public class TreeNodeViewModel: BindableBase
+	{
+		private static double width = 80;
+		private static double height = 50;
+		private readonly TreeViewModel treeViewModel;
+		private readonly TreeNodeData data;
+		private double x;
+		private double y;
+		private double connectorX2;
+		private double connectorY2;
+		private double prelim;
+		private double modify;
+		private double ancestorModify;
+		private bool isFold;
+
+		public TreeNodeViewModel(TreeViewModel treeViewModel, double x, double y)
+		{
+			this.treeViewModel = treeViewModel;
+			this.x = x;
+			this.y = y;
+			this.data = new TreeNodeData();
+			this.data.Id = ++treeViewModel.AllTreeViewModel.MaxNodeId;
+			this.data.TreeId = treeViewModel.TreeId;
+			this.data.Parent = 0;
+			this.connectorX2 = 0;
+			this.connectorY2 = Height / 2;
+		}
+
+		public TreeNodeViewModel(TreeViewModel treeViewModel, TreeNodeViewModel parent)
+		{
+			this.treeViewModel = treeViewModel;
+			this.data = new TreeNodeData();
+			this.data.Id = ++treeViewModel.AllTreeViewModel.MaxNodeId;
+			this.data.TreeId = treeViewModel.TreeId;
+			this.Parent = parent;
+
+			this.connectorX2 = Width + this.Parent.X - this.X;
+			this.connectorY2 = Height / 2 + this.Parent.Y - this.Y;
+		}
+
+		public TreeNodeViewModel(TreeViewModel treeViewModel, TreeNodeData data)
+		{
+			this.treeViewModel = treeViewModel;
+			this.data = data;
+			if (this.IsRoot)
+			{
+				this.x = 300;
+				this.y = 100;
+				this.connectorX2 = 0;
+				this.connectorY2 = Height / 2;
+			}
+			else
+			{
+				this.connectorX2 = Width + this.Parent.X - this.X;
+				this.connectorY2 = Height / 2 + this.Parent.Y - this.Y;
+			}
+		}
+
+		public TreeNodeData Data
+		{
+			get
+			{
+				return this.data;
+			}
+		}
+
+		public int Id
+		{
+			get
+			{
+				return this.data.Id;
+			}
+			set
+			{
+				if (this.data.Id == value)
+				{
+					return;
+				}
+				this.data.Id = value;
+				this.OnPropertyChanged("Id");
+			}
+		}
+
+		public string Comment
+		{
+			get
+			{
+				return this.data.Comment;
+			}
+			set
+			{
+				if (this.data.Comment == value)
+				{
+					return;
+				}
+				this.data.Comment = value;
+				this.OnPropertyChanged("Comment");
+			}
+		}
+
+		public static double Width
+		{
+			get
+			{
+				return width;
+			}
+			set
+			{
+				width = value;
+			}
+		}
+
+		public static double Height
+		{
+			get
+			{
+				return height;
+			}
+			set
+			{
+				height = value;
+			}
+		}
+
+		public bool IsRoot
+		{
+			get
+			{
+				return this.Parent == null;
+			}
+		}
+
+		public double Prelim
+		{
+			get
+			{
+				return this.prelim;
+			}
+			set
+			{
+				this.prelim = value;
+			}
+		}
+
+		public double Modify
+		{
+			get
+			{
+				return this.modify;
+			}
+			set
+			{
+				this.modify = value;
+			}
+		}
+
+		public double X
+		{
+			get
+			{
+				return this.x;
+			}
+			set
+			{
+				if (Math.Abs(this.x - value) < 0.1)
+				{
+					return;
+				}
+				this.x = value;
+				this.OnPropertyChanged("X");
+
+				if (this.Parent != null)
+				{
+					this.ConnectorX2 = Width / 2 + this.Parent.X - this.X;
+				}
+
+				foreach (var childId in this.Children)
+				{
+					TreeNodeViewModel child = this.treeViewModel.Get(childId);
+					child.ConnectorX2 = Width / 2 + this.X - child.X;
+				}
+			}
+		}
+
+		public double Y
+		{
+			get
+			{
+				return this.y;
+			}
+			set
+			{
+				if (Math.Abs(this.Y - value) < 0.1)
+				{
+					return;
+				}
+
+				this.y = value;
+				this.OnPropertyChanged("Y");
+
+				if (this.Parent != null)
+				{
+					this.ConnectorY2 = Height + this.Parent.Y - this.Y;
+				}
+
+				foreach (var childId in this.Children)
+				{
+					TreeNodeViewModel child = this.treeViewModel.Get(childId);
+					child.ConnectorY2 = Height + this.Y - child.Y;
+				}
+			}
+		}
+
+		public double ConnectorX1
+		{
+			get
+			{
+				return Width / 2;
+			}
+		}
+
+		public double ConnectorY1
+		{
+			get
+			{
+				return 0;
+			}
+		}
+
+		public double ConnectorX2
+		{
+			get
+			{
+				return this.IsRoot? Width / 2 : this.connectorX2;
+			}
+			set
+			{
+				this.SetProperty(ref this.connectorX2, value);
+			}
+		}
+
+		public double ConnectorY2
+		{
+			get
+			{
+				return this.IsRoot? 0 : this.connectorY2;
+			}
+			set
+			{
+				this.SetProperty(ref this.connectorY2, value);
+			}
+		}
+
+		public int Type
+		{
+			get
+			{
+				return this.data.Type;
+			}
+			set
+			{
+				if (this.data.Type == value)
+				{
+					return;
+				}
+				this.data.Type = value;
+				this.OnPropertyChanged("Type");
+			}
+		}
+
+		public List<string> Args
+		{
+			get
+			{
+				return this.data.Args;
+			}
+			set
+			{
+				if (this.data.Args == value)
+				{
+					return;
+				}
+				this.data.Args = value;
+				this.OnPropertyChanged("Args");
+			}
+		}
+
+		public int TreeId
+		{
+			get
+			{
+				return this.data.TreeId;
+			}
+		}
+
+		public TreeNodeViewModel Parent
+		{
+			get
+			{
+				if (this.data.Parent == 0)
+				{
+					return null;
+				}
+				TreeNodeViewModel parent = this.treeViewModel.Get(this.data.Parent);
+				return parent;
+			}
+			set
+			{
+				if (value == null)
+				{
+					this.data.Parent = 0;
+				}
+				this.data.Parent = value.Id;
+			}
+		}
+
+		/// <summary>
+		/// 节点是否折叠
+		/// </summary>
+		public bool IsFold
+		{
+			get
+			{
+				return this.isFold;
+			}
+			set
+			{
+				if (this.isFold == value)
+				{
+					return;
+				}
+				this.isFold = value;
+				this.OnPropertyChanged("IsFold");
+			}
+		}
+
+		public List<int> Children
+		{
+			get
+			{
+				if (this.isFold)
+				{
+					return new List<int>();
+				}
+				return this.data.Children;
+			}
+		}
+
+		public TreeNodeViewModel LeftSibling
+		{
+			get
+			{
+				if (this.IsRoot)
+				{
+					return null;
+				}
+
+				int index = this.Parent.Children.IndexOf(this.Id);
+				return index == 0? null : this.treeViewModel.Get(this.Parent.Children[index - 1]);
+			}
+		}
+
+		public TreeNodeViewModel LastChild
+		{
+			get
+			{
+				if (this.Children.Count == 0)
+				{
+					return null;
+				}
+
+				int maxIndex = this.Children.Count - 1;
+				return this.treeViewModel.Get(this.Children[maxIndex]);
+			}
+		}
+
+		public TreeNodeViewModel FirstChild
+		{
+			get
+			{
+				return this.Children.Count == 0? null : this.treeViewModel.Get(this.Children[0]);
+			}
+		}
+
+		public bool IsLeaf
+		{
+			get
+			{
+				return this.Children.Count == 0;
+			}
+		}
+
+		public double AncestorModify
+		{
+			get
+			{
+				return this.ancestorModify;
+			}
+			set
+			{
+				this.ancestorModify = value;
+			}
+		}
+	}
 }

+ 232 - 232
CSharp/App/Modules/BehaviorTreeModule/TreeView.xaml.cs

@@ -5,236 +5,236 @@ using Common.Logger;
 
 namespace Modules.BehaviorTreeModule
 {
-    public partial class TreeView
-    {
-        private const double DragThreshold = 5;
-        private bool isDragging;
-        private bool isLeftButtonDown;
-        private Point origMouseDownPoint;
-        private TreeNodeViewModel moveFromNode;
-
-        public AllTreeView AllTreeView { get; set; }
-
-        public TreeView()
-        {
-            this.InitializeComponent();
-        }
-
-        public TreeViewModel ViewModel
-        {
-            get
-            {
-                return this.DataContext as TreeViewModel;
-            }
-            set
-            {
-                this.DataContext = value;
-            }
-        }
-
-        public bool IsDragging
-        {
-            get
-            {
-                return this.isDragging;
-            }
-            set
-            {
-                //Mouse.SetCursor(value == false? Cursors.Arrow : Cursors.Hand);
-                this.isDragging = value;
-            }
-        }
-
-        private void ListBoxItem_MouseDown(object sender, MouseButtonEventArgs e)
-        {
-        }
-
-        private void ListBoxItem_MouseUp(object sender, MouseButtonEventArgs e)
-        {
-            if (!this.isLeftButtonDown)
-            {
-                this.IsDragging = false;
-                return;
-            }
-
-            var item = (FrameworkElement) sender;
-            var treeNodeViewModel = item.DataContext as TreeNodeViewModel;
-
-            if (!this.IsDragging)
-            {
-                this.listBox.SelectedItem = treeNodeViewModel;
-            }
-
-            this.isLeftButtonDown = false;
-            this.IsDragging = false;
-
-            item.ReleaseMouseCapture();
-            e.Handled = true;
-        }
-
-        private void ListBoxItem_MouseMove(object sender, MouseEventArgs e)
-        {
-            var item = (FrameworkElement) sender;
-            var treeNodeViewModel = item.DataContext as TreeNodeViewModel;
-            if (treeNodeViewModel == null)
-            {
-                return;
-            }
-
-            Point curMouseDownPoint;
-            Vector dragDelta;
-            // 拖动根节点,移动整个树
-            if (this.IsDragging && treeNodeViewModel.IsRoot)
-            {
-                if (this.moveFromNode == null || !this.moveFromNode.IsRoot)
-                {
-                    return;
-                }
-                curMouseDownPoint = e.GetPosition(this);
-                dragDelta = curMouseDownPoint - this.origMouseDownPoint;
-
-                this.origMouseDownPoint = curMouseDownPoint;
-
-                this.ViewModel.MoveToPosition(dragDelta.X, dragDelta.Y);
-                return;
-            }
-
-            if (e.LeftButton != MouseButtonState.Pressed)
-            {
-                this.IsDragging = false;
-                this.moveFromNode = null;
-                return;
-            }
-
-            curMouseDownPoint = e.GetPosition(this);
-            dragDelta = curMouseDownPoint - this.origMouseDownPoint;
-            double dragDistance = Math.Abs(dragDelta.Length);
-            if (dragDistance > DragThreshold)
-            {
-                this.IsDragging = true;
-            }
-            e.Handled = true;
-        }
-
-        private void ListBoxItem_PreviewMouseLeftButtonDown(object sender, MouseEventArgs e)
-        {
-            this.origMouseDownPoint = e.GetPosition(this);
-            var item = (FrameworkElement) sender;
-            var treeNodeViewModel = item.DataContext as TreeNodeViewModel;
-
-            this.listBox.SelectedItem = treeNodeViewModel;
-            this.moveFromNode = treeNodeViewModel;
-
-            this.AllTreeView.nodeDataEditor.DataContext = treeNodeViewModel;
-        }
-
-        private void ListBoxItem_PreviewMouseLeftButtonUp(object sender, MouseEventArgs e)
-        {
-            if (this.moveFromNode == null)
-            {
-                return;
-            }
-            if (this.moveFromNode.IsRoot)
-            {
-                return;
-            }
-            var item = (FrameworkElement) sender;
-            var moveToNode = item.DataContext as TreeNodeViewModel;
-            Log.Debug("move to node: {0} {1}", this.moveFromNode.Id, moveToNode.Id);
-            if (this.moveFromNode.Id == moveToNode.Id)
-            {
-                return;
-            }
-            this.ViewModel.MoveToNode(this.moveFromNode, moveToNode);
-            this.moveFromNode = null;
-        }
-
-        private void MenuItem_New(object sender, RoutedEventArgs e)
-        {
-            if (this.ViewModel == null)
-            {
-                return;
-            }
-
-            Point point = Mouse.GetPosition(this.listBox);
-
-            // one root node
-            if (this.ViewModel.TreeNodes.Count == 0)
-            {
-                var addTreeNode = new TreeNodeViewModel(this.ViewModel, point.X, point.Y)
-                {
-                    Type = (int) NodeType.Selector
-                };
-                this.ViewModel.Add(addTreeNode, null);
-            }
-            else
-            {
-                if (this.listBox.SelectedItem != null)
-                {
-                    var parentNode = this.listBox.SelectedItem as TreeNodeViewModel;
-                    var addTreeNode = new TreeNodeViewModel(this.ViewModel, parentNode)
-                    {
-                        Type = (int) NodeType.Selector,
-                    };
-                    this.ViewModel.Add(addTreeNode, parentNode);
-                }
-            }
-            this.listBox.SelectedItem = null;
-            e.Handled = true;
-        }
-
-        private void MenuItem_Remove(object sender, RoutedEventArgs e)
-        {
-            if (this.listBox.SelectedItem == null)
-            {
-                return;
-            }
-            var treeNodeViewModel = this.listBox.SelectedItem as TreeNodeViewModel;
-            if (treeNodeViewModel.IsRoot)
-            {
-                return;
-            }
-            this.ViewModel.Remove(treeNodeViewModel);
-            this.listBox.SelectedItem = null;
-            e.Handled = true;
-        }
-
-        private void MenuItem_Fold(object sender, RoutedEventArgs e)
-        {
-            if (this.listBox.SelectedItem == null)
-            {
-                return;
-            }
-            var treeNodeViewModel = this.listBox.SelectedItem as TreeNodeViewModel;
-
-            if (treeNodeViewModel.IsFold)
-            {
-                this.ViewModel.UnFold(treeNodeViewModel);
-            }
-            else
-            {
-                this.ViewModel.Fold(treeNodeViewModel);
-            }
-        }
-
-        private void MenuItem_MoveLeft(object sender, RoutedEventArgs e)
-        {
-            if (this.listBox.SelectedItem == null)
-            {
-                return;
-            }
-            var treeNodeViewModel = this.listBox.SelectedItem as TreeNodeViewModel;
-            this.ViewModel.MoveLeft(treeNodeViewModel);
-        }
-
-        private void MenuItem_MoveRight(object sender, RoutedEventArgs e)
-        {
-            if (this.listBox.SelectedItem == null)
-            {
-                return;
-            }
-            var treeNodeViewModel = this.listBox.SelectedItem as TreeNodeViewModel;
-            this.ViewModel.MoveRight(treeNodeViewModel);
-        }
-    }
+	public partial class TreeView
+	{
+		private const double DragThreshold = 5;
+		private bool isDragging;
+		private bool isLeftButtonDown;
+		private Point origMouseDownPoint;
+		private TreeNodeViewModel moveFromNode;
+
+		public AllTreeView AllTreeView { get; set; }
+
+		public TreeView()
+		{
+			this.InitializeComponent();
+		}
+
+		public TreeViewModel ViewModel
+		{
+			get
+			{
+				return this.DataContext as TreeViewModel;
+			}
+			set
+			{
+				this.DataContext = value;
+			}
+		}
+
+		public bool IsDragging
+		{
+			get
+			{
+				return this.isDragging;
+			}
+			set
+			{
+				//Mouse.SetCursor(value == false? Cursors.Arrow : Cursors.Hand);
+				this.isDragging = value;
+			}
+		}
+
+		private void ListBoxItem_MouseDown(object sender, MouseButtonEventArgs e)
+		{
+		}
+
+		private void ListBoxItem_MouseUp(object sender, MouseButtonEventArgs e)
+		{
+			if (!this.isLeftButtonDown)
+			{
+				this.IsDragging = false;
+				return;
+			}
+
+			var item = (FrameworkElement) sender;
+			var treeNodeViewModel = item.DataContext as TreeNodeViewModel;
+
+			if (!this.IsDragging)
+			{
+				this.listBox.SelectedItem = treeNodeViewModel;
+			}
+
+			this.isLeftButtonDown = false;
+			this.IsDragging = false;
+
+			item.ReleaseMouseCapture();
+			e.Handled = true;
+		}
+
+		private void ListBoxItem_MouseMove(object sender, MouseEventArgs e)
+		{
+			var item = (FrameworkElement) sender;
+			var treeNodeViewModel = item.DataContext as TreeNodeViewModel;
+			if (treeNodeViewModel == null)
+			{
+				return;
+			}
+
+			Point curMouseDownPoint;
+			Vector dragDelta;
+			// 拖动根节点,移动整个树
+			if (this.IsDragging && treeNodeViewModel.IsRoot)
+			{
+				if (this.moveFromNode == null || !this.moveFromNode.IsRoot)
+				{
+					return;
+				}
+				curMouseDownPoint = e.GetPosition(this);
+				dragDelta = curMouseDownPoint - this.origMouseDownPoint;
+
+				this.origMouseDownPoint = curMouseDownPoint;
+
+				this.ViewModel.MoveToPosition(dragDelta.X, dragDelta.Y);
+				return;
+			}
+
+			if (e.LeftButton != MouseButtonState.Pressed)
+			{
+				this.IsDragging = false;
+				this.moveFromNode = null;
+				return;
+			}
+
+			curMouseDownPoint = e.GetPosition(this);
+			dragDelta = curMouseDownPoint - this.origMouseDownPoint;
+			double dragDistance = Math.Abs(dragDelta.Length);
+			if (dragDistance > DragThreshold)
+			{
+				this.IsDragging = true;
+			}
+			e.Handled = true;
+		}
+
+		private void ListBoxItem_PreviewMouseLeftButtonDown(object sender, MouseEventArgs e)
+		{
+			this.origMouseDownPoint = e.GetPosition(this);
+			var item = (FrameworkElement) sender;
+			var treeNodeViewModel = item.DataContext as TreeNodeViewModel;
+
+			this.listBox.SelectedItem = treeNodeViewModel;
+			this.moveFromNode = treeNodeViewModel;
+
+			this.AllTreeView.nodeDataEditor.DataContext = treeNodeViewModel;
+		}
+
+		private void ListBoxItem_PreviewMouseLeftButtonUp(object sender, MouseEventArgs e)
+		{
+			if (this.moveFromNode == null)
+			{
+				return;
+			}
+			if (this.moveFromNode.IsRoot)
+			{
+				return;
+			}
+			var item = (FrameworkElement) sender;
+			var moveToNode = item.DataContext as TreeNodeViewModel;
+			Log.Debug("move to node: {0} {1}", this.moveFromNode.Id, moveToNode.Id);
+			if (this.moveFromNode.Id == moveToNode.Id)
+			{
+				return;
+			}
+			this.ViewModel.MoveToNode(this.moveFromNode, moveToNode);
+			this.moveFromNode = null;
+		}
+
+		private void MenuItem_New(object sender, RoutedEventArgs e)
+		{
+			if (this.ViewModel == null)
+			{
+				return;
+			}
+
+			Point point = Mouse.GetPosition(this.listBox);
+
+			// one root node
+			if (this.ViewModel.TreeNodes.Count == 0)
+			{
+				var addTreeNode = new TreeNodeViewModel(this.ViewModel, point.X, point.Y)
+				{
+					Type = (int) NodeType.Selector
+				};
+				this.ViewModel.Add(addTreeNode, null);
+			}
+			else
+			{
+				if (this.listBox.SelectedItem != null)
+				{
+					var parentNode = this.listBox.SelectedItem as TreeNodeViewModel;
+					var addTreeNode = new TreeNodeViewModel(this.ViewModel, parentNode)
+					{
+						Type = (int) NodeType.Selector,
+					};
+					this.ViewModel.Add(addTreeNode, parentNode);
+				}
+			}
+			this.listBox.SelectedItem = null;
+			e.Handled = true;
+		}
+
+		private void MenuItem_Remove(object sender, RoutedEventArgs e)
+		{
+			if (this.listBox.SelectedItem == null)
+			{
+				return;
+			}
+			var treeNodeViewModel = this.listBox.SelectedItem as TreeNodeViewModel;
+			if (treeNodeViewModel.IsRoot)
+			{
+				return;
+			}
+			this.ViewModel.Remove(treeNodeViewModel);
+			this.listBox.SelectedItem = null;
+			e.Handled = true;
+		}
+
+		private void MenuItem_Fold(object sender, RoutedEventArgs e)
+		{
+			if (this.listBox.SelectedItem == null)
+			{
+				return;
+			}
+			var treeNodeViewModel = this.listBox.SelectedItem as TreeNodeViewModel;
+
+			if (treeNodeViewModel.IsFold)
+			{
+				this.ViewModel.UnFold(treeNodeViewModel);
+			}
+			else
+			{
+				this.ViewModel.Fold(treeNodeViewModel);
+			}
+		}
+
+		private void MenuItem_MoveLeft(object sender, RoutedEventArgs e)
+		{
+			if (this.listBox.SelectedItem == null)
+			{
+				return;
+			}
+			var treeNodeViewModel = this.listBox.SelectedItem as TreeNodeViewModel;
+			this.ViewModel.MoveLeft(treeNodeViewModel);
+		}
+
+		private void MenuItem_MoveRight(object sender, RoutedEventArgs e)
+		{
+			if (this.listBox.SelectedItem == null)
+			{
+				return;
+			}
+			var treeNodeViewModel = this.listBox.SelectedItem as TreeNodeViewModel;
+			this.ViewModel.MoveRight(treeNodeViewModel);
+		}
+	}
 }

+ 257 - 258
CSharp/App/Modules/BehaviorTreeModule/TreeViewModel.cs

@@ -5,262 +5,261 @@ using Microsoft.Practices.Prism.Mvvm;
 
 namespace Modules.BehaviorTreeModule
 {
-    [Export(typeof (TreeViewModel)), PartCreationPolicy(CreationPolicy.NonShared)]
-    public class TreeViewModel: BindableBase
-    {
-        private readonly ObservableCollection<TreeNodeViewModel> treeNodes =
-                new ObservableCollection<TreeNodeViewModel>();
-
-        private readonly Dictionary<int, TreeNodeViewModel> treeNodeDict =
-                new Dictionary<int, TreeNodeViewModel>();
-
-        public ObservableCollection<TreeNodeViewModel> TreeNodes
-        {
-            get
-            {
-                return this.treeNodes;
-            }
-        }
-
-        public int TreeId { get; set; }
-
-        public TreeViewModel(AllTreeViewModel allTreeViewModel)
-        {
-            this.AllTreeViewModel = allTreeViewModel;
-            this.TreeId = ++allTreeViewModel.MaxTreeId;
-            TreeNodeViewModel treeNodeViewModel = new TreeNodeViewModel(this, 300, 100);
-            this.treeNodes.Add(treeNodeViewModel);
-            this.treeNodeDict[treeNodeViewModel.Id] = treeNodeViewModel;
-
-            var treeLayout = new TreeLayout(this);
-            treeLayout.ExcuteLayout();
-        }
-
-        public TreeViewModel(List<TreeNodeData> treeNodeDatas)
-        {
-            foreach (TreeNodeData treeNodeData in treeNodeDatas)
-            {
-                TreeNodeViewModel treeNodeViewModel = new TreeNodeViewModel(this, treeNodeData);
-                this.treeNodes.Add(treeNodeViewModel);
-                this.treeNodeDict[treeNodeViewModel.Id] = treeNodeViewModel;
-            }
-            var treeLayout = new TreeLayout(this);
-            treeLayout.ExcuteLayout();
-        }
-
-        public List<TreeNodeData> GetDatas()
-        {
-            List<TreeNodeData> treeNodeDatas = new List<TreeNodeData>();
-            foreach (TreeNodeViewModel treeNodeViewModel in this.treeNodes)
-            {
-                treeNodeDatas.Add(treeNodeViewModel.Data);
-            }
-            return treeNodeDatas;
-        }
-
-        public AllTreeViewModel AllTreeViewModel { get; set; }
-
-        public TreeNodeViewModel Root
-        {
-            get
-            {
-                return this.treeNodes.Count == 0? null : this.treeNodes[0];
-            }
-        }
-
-        public TreeNodeViewModel Get(int id)
-        {
-            TreeNodeViewModel node;
-            this.treeNodeDict.TryGetValue(id, out node);
-            return node;
-        }
-
-        public void Add(TreeNodeViewModel treeNode, TreeNodeViewModel parent)
-        {
-            // 如果父节点是折叠的,需要先展开父节点
-            if (parent != null && parent.IsFold)
-            {
-                this.UnFold(parent);
-            }
-
-            this.treeNodes.Add(treeNode);
-            this.treeNodeDict[treeNode.Id] = treeNode;
-
-            if (parent != null)
-            {
-                parent.Children.Add(treeNode.Id);
-            }
-
-            var treeLayout = new TreeLayout(this);
-            treeLayout.ExcuteLayout();
-        }
-
-        private void GetChildrenIdAndSelf(TreeNodeViewModel treeNodeViewModel, List<int> children)
-        {
-            children.Add(treeNodeViewModel.Id);
-            this.GetAllChildrenId(treeNodeViewModel, children);
-        }
-
-        private void GetAllChildrenId(TreeNodeViewModel treeNodeViewModel, List<int> children)
-        {
-            foreach (int childId in treeNodeViewModel.Children)
-            {
-                TreeNodeViewModel child = this.Get(childId);
-                children.Add(child.Id);
-                this.GetAllChildrenId(child, children);
-            }
-        }
-
-        public void Remove(TreeNodeViewModel treeNodeViewModel)
-        {
-            List<int> allId = new List<int>();
-            this.GetChildrenIdAndSelf(treeNodeViewModel, allId);
-
-            foreach (int childId in allId)
-            {
-                TreeNodeViewModel child = this.Get(childId);
-                this.treeNodes.Remove(child);
-                this.treeNodes.Remove(treeNodeViewModel);
-            }
-
-            TreeNodeViewModel parent = treeNodeViewModel.Parent;
-            if (parent != null)
-            {
-                parent.Children.Remove(treeNodeViewModel.Id);
-            }
-
-            var treeLayout = new TreeLayout(this);
-            treeLayout.ExcuteLayout();
-        }
-
-        private void RecursionMove(
-                TreeNodeViewModel treeNodeViewModel, double offsetX, double offsetY)
-        {
-            treeNodeViewModel.X += offsetX;
-            treeNodeViewModel.Y += offsetY;
-            foreach (var childId in treeNodeViewModel.Children)
-            {
-                TreeNodeViewModel child = this.Get(childId);
-                this.RecursionMove(child, offsetX, offsetY);
-            }
-        }
-
-        public void MoveToPosition(double offsetX, double offsetY)
-        {
-            this.RecursionMove(this.Root, offsetX, offsetY);
-        }
-
-        public void MoveToNode(TreeNodeViewModel from, TreeNodeViewModel to)
-        {
-            // from节点不能是to节点的父级节点
-            TreeNodeViewModel tmpNode = to;
-            while (tmpNode != null)
-            {
-                if (tmpNode.IsRoot)
-                {
-                    break;
-                }
-                if (tmpNode.Id == from.Id)
-                {
-                    return;
-                }
-                tmpNode = tmpNode.Parent;
-            }
-
-            if (from.IsFold)
-            {
-                this.UnFold(from);
-            }
-
-            if (to.IsFold)
-            {
-                this.UnFold(to);
-            }
-            from.Parent.Children.Remove(from.Id);
-            to.Children.Add(from.Id);
-            from.Parent = to;
-            var treeLayout = new TreeLayout(this);
-            treeLayout.ExcuteLayout();
-        }
-
-        /// <summary>
-        /// 折叠节点
-        /// </summary>
-        /// <param name="treeNodeViewModel"></param>
-        public void Fold(TreeNodeViewModel treeNodeViewModel)
-        {
-            List<int> allChildId = new List<int>();
-            this.GetAllChildrenId(treeNodeViewModel, allChildId);
-
-            foreach (int childId in allChildId)
-            {
-                TreeNodeViewModel child = this.Get(childId);
-                this.treeNodes.Remove(child);
-            }
-
-            treeNodeViewModel.IsFold = true;
-
-            var treeLayout = new TreeLayout(this);
-            treeLayout.ExcuteLayout();
-        }
-
-        /// <summary>
-        /// 展开节点,一级一级展开,一次只展开下层子节点,比如下层节点是折叠的,那下下层节点不展开
-        /// </summary>
-        /// <param name="treeNodeViewModel"></param>
-        public void UnFold(TreeNodeViewModel treeNodeViewModel)
-        {
-            treeNodeViewModel.IsFold = false;
-
-            List<int> allChildId = new List<int>();
-            this.GetAllChildrenId(treeNodeViewModel, allChildId);
-
-            foreach (int childId in allChildId)
-            {
-                TreeNodeViewModel child = this.Get(childId);
-                this.treeNodes.Add(child);
-            }
-
-            var treeLayout = new TreeLayout(this);
-            treeLayout.ExcuteLayout();
-        }
-
-        public void MoveLeft(TreeNodeViewModel treeNodeViewModel)
-        {
-            if (treeNodeViewModel.IsRoot)
-            {
-                return;
-            }
-            var parent = treeNodeViewModel.Parent;
-            int index = parent.Children.IndexOf(treeNodeViewModel.Id);
-            if (index == 0)
-            {
-                return;
-            }
-            parent.Children.Remove(treeNodeViewModel.Id);
-            parent.Children.Insert(index - 1, treeNodeViewModel.Id);
-
-            var treeLayout = new TreeLayout(this);
-            treeLayout.ExcuteLayout();
-        }
-
-        public void MoveRight(TreeNodeViewModel treeNodeViewModel)
-        {
-            if (treeNodeViewModel.IsRoot)
-            {
-                return;
-            }
-            var parent = treeNodeViewModel.Parent;
-            int index = parent.Children.IndexOf(treeNodeViewModel.Id);
-            if (index == parent.Children.Count - 1)
-            {
-                return;
-            }
-            parent.Children.Remove(treeNodeViewModel.Id);
-            parent.Children.Insert(index + 1, treeNodeViewModel.Id);
-
-            var treeLayout = new TreeLayout(this);
-            treeLayout.ExcuteLayout();
-        }
-    }
+	[Export(typeof (TreeViewModel)), PartCreationPolicy(CreationPolicy.NonShared)]
+	public class TreeViewModel: BindableBase
+	{
+		private readonly ObservableCollection<TreeNodeViewModel> treeNodes =
+				new ObservableCollection<TreeNodeViewModel>();
+
+		private readonly Dictionary<int, TreeNodeViewModel> treeNodeDict =
+				new Dictionary<int, TreeNodeViewModel>();
+
+		public ObservableCollection<TreeNodeViewModel> TreeNodes
+		{
+			get
+			{
+				return this.treeNodes;
+			}
+		}
+
+		public int TreeId { get; set; }
+
+		public TreeViewModel(AllTreeViewModel allTreeViewModel)
+		{
+			this.AllTreeViewModel = allTreeViewModel;
+			this.TreeId = ++allTreeViewModel.MaxTreeId;
+			TreeNodeViewModel treeNodeViewModel = new TreeNodeViewModel(this, 300, 100);
+			this.treeNodes.Add(treeNodeViewModel);
+			this.treeNodeDict[treeNodeViewModel.Id] = treeNodeViewModel;
+
+			var treeLayout = new TreeLayout(this);
+			treeLayout.ExcuteLayout();
+		}
+
+		public TreeViewModel(List<TreeNodeData> treeNodeDatas)
+		{
+			foreach (TreeNodeData treeNodeData in treeNodeDatas)
+			{
+				TreeNodeViewModel treeNodeViewModel = new TreeNodeViewModel(this, treeNodeData);
+				this.treeNodes.Add(treeNodeViewModel);
+				this.treeNodeDict[treeNodeViewModel.Id] = treeNodeViewModel;
+			}
+			var treeLayout = new TreeLayout(this);
+			treeLayout.ExcuteLayout();
+		}
+
+		public List<TreeNodeData> GetDatas()
+		{
+			List<TreeNodeData> treeNodeDatas = new List<TreeNodeData>();
+			foreach (TreeNodeViewModel treeNodeViewModel in this.treeNodes)
+			{
+				treeNodeDatas.Add(treeNodeViewModel.Data);
+			}
+			return treeNodeDatas;
+		}
+
+		public AllTreeViewModel AllTreeViewModel { get; set; }
+
+		public TreeNodeViewModel Root
+		{
+			get
+			{
+				return this.treeNodes.Count == 0? null : this.treeNodes[0];
+			}
+		}
+
+		public TreeNodeViewModel Get(int id)
+		{
+			TreeNodeViewModel node;
+			this.treeNodeDict.TryGetValue(id, out node);
+			return node;
+		}
+
+		public void Add(TreeNodeViewModel treeNode, TreeNodeViewModel parent)
+		{
+			// 如果父节点是折叠的,需要先展开父节点
+			if (parent != null && parent.IsFold)
+			{
+				this.UnFold(parent);
+			}
+
+			this.treeNodes.Add(treeNode);
+			this.treeNodeDict[treeNode.Id] = treeNode;
+
+			if (parent != null)
+			{
+				parent.Children.Add(treeNode.Id);
+			}
+
+			var treeLayout = new TreeLayout(this);
+			treeLayout.ExcuteLayout();
+		}
+
+		private void GetChildrenIdAndSelf(TreeNodeViewModel treeNodeViewModel, List<int> children)
+		{
+			children.Add(treeNodeViewModel.Id);
+			this.GetAllChildrenId(treeNodeViewModel, children);
+		}
+
+		private void GetAllChildrenId(TreeNodeViewModel treeNodeViewModel, List<int> children)
+		{
+			foreach (int childId in treeNodeViewModel.Children)
+			{
+				TreeNodeViewModel child = this.Get(childId);
+				children.Add(child.Id);
+				this.GetAllChildrenId(child, children);
+			}
+		}
+
+		public void Remove(TreeNodeViewModel treeNodeViewModel)
+		{
+			List<int> allId = new List<int>();
+			this.GetChildrenIdAndSelf(treeNodeViewModel, allId);
+
+			foreach (int childId in allId)
+			{
+				TreeNodeViewModel child = this.Get(childId);
+				this.treeNodes.Remove(child);
+				this.treeNodes.Remove(treeNodeViewModel);
+			}
+
+			TreeNodeViewModel parent = treeNodeViewModel.Parent;
+			if (parent != null)
+			{
+				parent.Children.Remove(treeNodeViewModel.Id);
+			}
+
+			var treeLayout = new TreeLayout(this);
+			treeLayout.ExcuteLayout();
+		}
+
+		private void RecursionMove(TreeNodeViewModel treeNodeViewModel, double offsetX, double offsetY)
+		{
+			treeNodeViewModel.X += offsetX;
+			treeNodeViewModel.Y += offsetY;
+			foreach (var childId in treeNodeViewModel.Children)
+			{
+				TreeNodeViewModel child = this.Get(childId);
+				this.RecursionMove(child, offsetX, offsetY);
+			}
+		}
+
+		public void MoveToPosition(double offsetX, double offsetY)
+		{
+			this.RecursionMove(this.Root, offsetX, offsetY);
+		}
+
+		public void MoveToNode(TreeNodeViewModel from, TreeNodeViewModel to)
+		{
+			// from节点不能是to节点的父级节点
+			TreeNodeViewModel tmpNode = to;
+			while (tmpNode != null)
+			{
+				if (tmpNode.IsRoot)
+				{
+					break;
+				}
+				if (tmpNode.Id == from.Id)
+				{
+					return;
+				}
+				tmpNode = tmpNode.Parent;
+			}
+
+			if (from.IsFold)
+			{
+				this.UnFold(from);
+			}
+
+			if (to.IsFold)
+			{
+				this.UnFold(to);
+			}
+			from.Parent.Children.Remove(from.Id);
+			to.Children.Add(from.Id);
+			from.Parent = to;
+			var treeLayout = new TreeLayout(this);
+			treeLayout.ExcuteLayout();
+		}
+
+		/// <summary>
+		/// 折叠节点
+		/// </summary>
+		/// <param name="treeNodeViewModel"></param>
+		public void Fold(TreeNodeViewModel treeNodeViewModel)
+		{
+			List<int> allChildId = new List<int>();
+			this.GetAllChildrenId(treeNodeViewModel, allChildId);
+
+			foreach (int childId in allChildId)
+			{
+				TreeNodeViewModel child = this.Get(childId);
+				this.treeNodes.Remove(child);
+			}
+
+			treeNodeViewModel.IsFold = true;
+
+			var treeLayout = new TreeLayout(this);
+			treeLayout.ExcuteLayout();
+		}
+
+		/// <summary>
+		/// 展开节点,一级一级展开,一次只展开下层子节点,比如下层节点是折叠的,那下下层节点不展开
+		/// </summary>
+		/// <param name="treeNodeViewModel"></param>
+		public void UnFold(TreeNodeViewModel treeNodeViewModel)
+		{
+			treeNodeViewModel.IsFold = false;
+
+			List<int> allChildId = new List<int>();
+			this.GetAllChildrenId(treeNodeViewModel, allChildId);
+
+			foreach (int childId in allChildId)
+			{
+				TreeNodeViewModel child = this.Get(childId);
+				this.treeNodes.Add(child);
+			}
+
+			var treeLayout = new TreeLayout(this);
+			treeLayout.ExcuteLayout();
+		}
+
+		public void MoveLeft(TreeNodeViewModel treeNodeViewModel)
+		{
+			if (treeNodeViewModel.IsRoot)
+			{
+				return;
+			}
+			var parent = treeNodeViewModel.Parent;
+			int index = parent.Children.IndexOf(treeNodeViewModel.Id);
+			if (index == 0)
+			{
+				return;
+			}
+			parent.Children.Remove(treeNodeViewModel.Id);
+			parent.Children.Insert(index - 1, treeNodeViewModel.Id);
+
+			var treeLayout = new TreeLayout(this);
+			treeLayout.ExcuteLayout();
+		}
+
+		public void MoveRight(TreeNodeViewModel treeNodeViewModel)
+		{
+			if (treeNodeViewModel.IsRoot)
+			{
+				return;
+			}
+			var parent = treeNodeViewModel.Parent;
+			int index = parent.Children.IndexOf(treeNodeViewModel.Id);
+			if (index == parent.Children.Count - 1)
+			{
+				return;
+			}
+			parent.Children.Remove(treeNodeViewModel.Id);
+			parent.Children.Insert(index + 1, treeNodeViewModel.Id);
+
+			var treeLayout = new TreeLayout(this);
+			treeLayout.ExcuteLayout();
+		}
+	}
 }

+ 11 - 11
CSharp/Game/Controller/BehaviorTreeNode/Not.cs

@@ -2,16 +2,16 @@
 
 namespace Controller
 {
-    [Node(NodeType.Not)]
-    public class Not: Node
-    {
-        public Not(NodeConfig config): base(config)
-        {
-        }
+	[Node(NodeType.Not)]
+	public class Not: Node
+	{
+		public Not(NodeConfig config): base(config)
+		{
+		}
 
-        public override bool Run(BlackBoard blackBoard)
-        {
-            return !this.children[0].Run(blackBoard);
-        }
-    }
+		public override bool Run(BlackBoard blackBoard)
+		{
+			return !this.children[0].Run(blackBoard);
+		}
+	}
 }

+ 18 - 18
CSharp/Game/Controller/BehaviorTreeNode/Selector.cs

@@ -2,23 +2,23 @@
 
 namespace Controller
 {
-    [Node(NodeType.Selector)]
-    public class Selector: Node
-    {
-        public Selector(NodeConfig config): base(config)
-        {
-        }
+	[Node(NodeType.Selector)]
+	public class Selector: Node
+	{
+		public Selector(NodeConfig config): base(config)
+		{
+		}
 
-        public override bool Run(BlackBoard blackBoard)
-        {
-            foreach (var child in this.children)
-            {
-                if (child.Run(blackBoard))
-                {
-                    return true;
-                }
-            }
-            return false;
-        }
-    }
+		public override bool Run(BlackBoard blackBoard)
+		{
+			foreach (var child in this.children)
+			{
+				if (child.Run(blackBoard))
+				{
+					return true;
+				}
+			}
+			return false;
+		}
+	}
 }

+ 18 - 18
CSharp/Game/Controller/BehaviorTreeNode/Sequence.cs

@@ -2,23 +2,23 @@
 
 namespace Controller
 {
-    [Node(NodeType.Sequence)]
-    internal class Sequence: Node
-    {
-        public Sequence(NodeConfig config): base(config)
-        {
-        }
+	[Node(NodeType.Sequence)]
+	internal class Sequence: Node
+	{
+		public Sequence(NodeConfig config): base(config)
+		{
+		}
 
-        public override bool Run(BlackBoard blackBoard)
-        {
-            foreach (var child in this.children)
-            {
-                if (!child.Run(blackBoard))
-                {
-                    return false;
-                }
-            }
-            return true;
-        }
-    }
+		public override bool Run(BlackBoard blackBoard)
+		{
+			foreach (var child in this.children)
+			{
+				if (!child.Run(blackBoard))
+				{
+					return false;
+				}
+			}
+			return true;
+		}
+	}
 }

+ 14 - 14
CSharp/Game/Controller/Callback/BuffTimeoutCallback.cs

@@ -4,17 +4,17 @@ using MongoDB.Bson;
 
 namespace Controller
 {
-    [Callback(CallbackType.BuffTimeoutCallback)]
-    public class BuffTimeoutCallback: IEvent
-    {
-        public void Run(Env env)
-        {
-            Unit owner = World.Instance.GetComponent<UnitComponent>().Get(env.Get<ObjectId>(EnvKey.OwnerId));
-            if (owner == null)
-            {
-                return;
-            }
-            owner.GetComponent<BuffComponent>().RemoveById(env.Get<ObjectId>(EnvKey.BuffId));
-        }
-    }
-}
+	[Callback(CallbackType.BuffTimeoutCallback)]
+	public class BuffTimeoutCallback: IEvent
+	{
+		public void Run(Env env)
+		{
+			Unit owner = World.Instance.GetComponent<UnitComponent>().Get(env.Get<ObjectId>(EnvKey.OwnerId));
+			if (owner == null)
+			{
+				return;
+			}
+			owner.GetComponent<BuffComponent>().RemoveById(env.Get<ObjectId>(EnvKey.BuffId));
+		}
+	}
+}

+ 5 - 5
CSharp/Game/Controller/ConfigCategory/BuffCategory.cs

@@ -3,8 +3,8 @@ using Model;
 
 namespace Controller
 {
-    [Config]
-    public class BuffCategory : ACategory<BuffConfig>
-    {
-    }
-}
+	[Config]
+	public class BuffCategory: ACategory<BuffConfig>
+	{
+	}
+}

+ 5 - 5
CSharp/Game/Controller/ConfigCategory/GlobalCategory.cs

@@ -3,8 +3,8 @@ using Model;
 
 namespace Controller
 {
-    [Config]
-    public class GlobalCategory : ACategory<GlobalConfig>
-    {
-    }
-}
+	[Config]
+	public class GlobalCategory: ACategory<GlobalConfig>
+	{
+	}
+}

+ 5 - 5
CSharp/Game/Controller/ConfigCategory/NodeCategory.cs

@@ -3,8 +3,8 @@ using Model;
 
 namespace Controller
 {
-    [Config]
-    public class NodeCategory : ACategory<NodeConfig>
-    {
-    }
-}
+	[Config]
+	public class NodeCategory: ACategory<NodeConfig>
+	{
+	}
+}

+ 5 - 5
CSharp/Game/Controller/ConfigCategory/UnitCategory.cs

@@ -3,8 +3,8 @@ using Model;
 
 namespace Controller
 {
-    [Config]
-    public class UnitCategory : ACategory<UnitConfig>
-    {
-    }
-}
+	[Config]
+	public class UnitCategory: ACategory<UnitConfig>
+	{
+	}
+}

+ 8 - 9
CSharp/Game/Controller/Event/AfterAddBuff.cs

@@ -3,12 +3,11 @@ using Model;
 
 namespace Controller
 {
-    [Event(EventType.AfterAddBuff)]
-    public class AddBuffToTimer: IEvent
-    {
-        public void Run(Env env)
-        {
-
-        }
-    }
-}
+	[Event(EventType.AfterAddBuff)]
+	public class AddBuffToTimer: IEvent
+	{
+		public void Run(Env env)
+		{
+		}
+	}
+}

+ 14 - 14
CSharp/Game/Controller/Factory/UnitFactory.cs

@@ -2,17 +2,17 @@
 
 namespace Controller
 {
-    [Factory(typeof (Unit), UnitType.Player)]
-    public class UnitPlayerFactory: IFactory<Unit>
-    {
-        public Unit Create(int configId)
-        {
-            Unit player = new Unit(configId);
-            player.AddComponent<BuffComponent>();
-            Buff buff = new Buff(1, player.Id);
-            player.GetComponent<BuffComponent>().Add(buff);
-            World.Instance.GetComponent<UnitComponent>().Add(player);
-            return player;
-        }
-    }
-}
+	[Factory(typeof (Unit), UnitType.Player)]
+	public class UnitPlayerFactory: IFactory<Unit>
+	{
+		public Unit Create(int configId)
+		{
+			Unit player = new Unit(configId);
+			player.AddComponent<BuffComponent>();
+			Buff buff = new Buff(1, player.Id);
+			player.GetComponent<BuffComponent>().Add(buff);
+			World.Instance.GetComponent<UnitComponent>().Add(player);
+			return player;
+		}
+	}
+}

+ 6 - 6
CSharp/Game/Controller/NodeType.cs

@@ -1,9 +1,9 @@
 namespace Controller
 {
-    public static class NodeType
-    {
-        public const int Selector = 1;
-        public const int Sequence = 2;
-        public const int Not = 10;
-    }
+	public static class NodeType
+	{
+		public const int Selector = 1;
+		public const int Sequence = 2;
+		public const int Not = 10;
+	}
 }

+ 7 - 7
CSharp/Game/Controller/UnitType.cs

@@ -1,9 +1,9 @@
 namespace Controller
 {
-    public static class UnitType
-    {
-        public const int Player = 1;
-        public const int Npc = 2;
-        public const int Dog = 3;
-    }
-}
+	public static class UnitType
+	{
+		public const int Player = 1;
+		public const int Npc = 2;
+		public const int Dog = 3;
+	}
+}

+ 12 - 12
CSharp/Game/Model/BehaviorTree/BehaviorTree.cs

@@ -1,17 +1,17 @@
 namespace Model
 {
-    public class BehaviorTree
-    {
-        private readonly Node node;
+	public class BehaviorTree
+	{
+		private readonly Node node;
 
-        public BehaviorTree(Node node)
-        {
-            this.node = node;
-        }
+		public BehaviorTree(Node node)
+		{
+			this.node = node;
+		}
 
-        public bool Run(BlackBoard blackBoard)
-        {
-            return this.node.Run(blackBoard);
-        }
-    }
+		public bool Run(BlackBoard blackBoard)
+		{
+			return this.node.Run(blackBoard);
+		}
+	}
 }

+ 59 - 60
CSharp/Game/Model/BehaviorTree/BehaviorTreeFactory.cs

@@ -4,74 +4,73 @@ using System.Reflection;
 
 namespace Model
 {
-    public class BehaviorTreeFactory
-    {
-        private static readonly BehaviorTreeFactory instance = new BehaviorTreeFactory();
+	public class BehaviorTreeFactory
+	{
+		private static readonly BehaviorTreeFactory instance = new BehaviorTreeFactory();
 
-        public static BehaviorTreeFactory Instance
-        {
-            get
-            {
-                return instance;
-            }
-        }
+		public static BehaviorTreeFactory Instance
+		{
+			get
+			{
+				return instance;
+			}
+		}
 
-        private Dictionary<int, Func<NodeConfig, Node>> dictionary;
+		private Dictionary<int, Func<NodeConfig, Node>> dictionary;
 
-        private BehaviorTreeFactory()
-        {
-        }
+		private BehaviorTreeFactory()
+		{
+		}
 
-        public void Load(Assembly assembly)
-        {
-            this.dictionary = new Dictionary<int, Func<NodeConfig, Node>>();
+		public void Load(Assembly assembly)
+		{
+			this.dictionary = new Dictionary<int, Func<NodeConfig, Node>>();
 
-            Type[] types = assembly.GetTypes();
-            foreach (var type in types)
-            {
-                object[] attrs = type.GetCustomAttributes(typeof(NodeAttribute), false);
-                if (attrs.Length == 0)
-                {
-                    continue;
-                }
-                NodeAttribute attribute = (NodeAttribute)attrs[0];
+			Type[] types = assembly.GetTypes();
+			foreach (var type in types)
+			{
+				object[] attrs = type.GetCustomAttributes(typeof (NodeAttribute), false);
+				if (attrs.Length == 0)
+				{
+					continue;
+				}
+				NodeAttribute attribute = (NodeAttribute) attrs[0];
 
-                Type classType = type;
-                this.dictionary.Add(attribute.NodeType,
-                        config => (Node)Activator.CreateInstance(classType, new object[] { config }));
-            } 
-        }
+				Type classType = type;
+				this.dictionary.Add(attribute.NodeType,
+						config => (Node) Activator.CreateInstance(classType, new object[] { config }));
+			}
+		}
 
-        private Node CreateNode(NodeConfig config)
-        {
-            if (!this.dictionary.ContainsKey(config.Id))
-            {
-                throw new KeyNotFoundException(string.Format("CreateNode cannot found: {0}",
-                        config.Id));
-            }
-            return this.dictionary[config.Id](config);
-        }
+		private Node CreateNode(NodeConfig config)
+		{
+			if (!this.dictionary.ContainsKey(config.Id))
+			{
+				throw new KeyNotFoundException(string.Format("CreateNode cannot found: {0}", config.Id));
+			}
+			return this.dictionary[config.Id](config);
+		}
 
-        private Node CreateTreeNode(NodeConfig config)
-        {
-            var node = this.CreateNode(config);
-            if (config.SubConfigs == null)
-            {
-                return node;
-            }
+		private Node CreateTreeNode(NodeConfig config)
+		{
+			var node = this.CreateNode(config);
+			if (config.SubConfigs == null)
+			{
+				return node;
+			}
 
-            foreach (var subConfig in config.SubConfigs)
-            {
-                var subNode = this.CreateTreeNode(subConfig);
-                node.AddChild(subNode);
-            }
-            return node;
-        }
+			foreach (var subConfig in config.SubConfigs)
+			{
+				var subNode = this.CreateTreeNode(subConfig);
+				node.AddChild(subNode);
+			}
+			return node;
+		}
 
-        public BehaviorTree CreateTree(NodeConfig config)
-        {
-            var node = this.CreateTreeNode(config);
-            return new BehaviorTree(node);
-        }
-    }
+		public BehaviorTree CreateTree(NodeConfig config)
+		{
+			var node = this.CreateTreeNode(config);
+			return new BehaviorTree(node);
+		}
+	}
 }

+ 3 - 3
CSharp/Game/Model/BehaviorTree/BlackBoard.cs

@@ -2,7 +2,7 @@
 
 namespace Model
 {
-    public class BlackBoard: Object
-    {
-    }
+	public class BlackBoard: Object
+	{
+	}
 }

+ 14 - 14
CSharp/Game/Model/BehaviorTree/Node.cs

@@ -2,22 +2,22 @@
 
 namespace Model
 {
-    public abstract class Node
-    {
-        public NodeConfig Config { get; private set; }
+	public abstract class Node
+	{
+		public NodeConfig Config { get; private set; }
 
-        protected readonly List<Node> children = new List<Node>();
+		protected readonly List<Node> children = new List<Node>();
 
-        protected Node(NodeConfig config)
-        {
-            this.Config = config;
-        }
+		protected Node(NodeConfig config)
+		{
+			this.Config = config;
+		}
 
-        public void AddChild(Node child)
-        {
-            this.children.Add(child);
-        }
+		public void AddChild(Node child)
+		{
+			this.children.Add(child);
+		}
 
-        public abstract bool Run(BlackBoard blackBoard);
-    }
+		public abstract bool Run(BlackBoard blackBoard);
+	}
 }

+ 9 - 9
CSharp/Game/Model/BehaviorTree/NodeAttribute.cs

@@ -2,14 +2,14 @@
 
 namespace Model
 {
-    [AttributeUsage(AttributeTargets.Class)]
-    public class NodeAttribute: Attribute
-    {
-        public int NodeType { get; private set; }
+	[AttributeUsage(AttributeTargets.Class)]
+	public class NodeAttribute: Attribute
+	{
+		public int NodeType { get; private set; }
 
-        public NodeAttribute(int nodeType)
-        {
-            this.NodeType = nodeType;
-        }
-    }
+		public NodeAttribute(int nodeType)
+		{
+			this.NodeType = nodeType;
+		}
+	}
 }

+ 55 - 59
CSharp/Game/Model/Buff.cs

@@ -1,60 +1,60 @@
-using Common.Base;
+using System;
+using Common.Base;
 using Common.Event;
 using Common.Helper;
 using MongoDB.Bson;
 using MongoDB.Bson.Serialization.Attributes;
-using System;
 
 namespace Model
 {
-    public class Buff: Entity<Buff>, IDisposable
+	public class Buff: Entity<Buff>, IDisposable
 	{
-        [BsonElement]
-        private int configId { get; set; }
+		[BsonElement]
+		private int configId { get; set; }
 
 		[BsonElement]
 		private ObjectId ownerId;
 
-        [BsonElement]
-        private long expiration;
-
-        [BsonIgnore]
-        private ObjectId timerId;
-
-        [BsonIgnore]
-        public long Expiration 
-        {
-            get
-            {
-                return this.expiration;
-            }
-            set
-            {
-                this.expiration = value;
-            }
-        }
-
-        [BsonIgnore]
-        public ObjectId TimerId 
-        {
-            get
-            {
-                return this.timerId;
-            }
-            set
-            {
-                this.timerId = value;
-            }
-        }
-
-        public Buff(int configId, ObjectId ownerId)
-        {
-            this.configId = configId;
+		[BsonElement]
+		private long expiration;
+
+		[BsonIgnore]
+		private ObjectId timerId;
+
+		[BsonIgnore]
+		public long Expiration
+		{
+			get
+			{
+				return this.expiration;
+			}
+			set
+			{
+				this.expiration = value;
+			}
+		}
+
+		[BsonIgnore]
+		public ObjectId TimerId
+		{
+			get
+			{
+				return this.timerId;
+			}
+			set
+			{
+				this.timerId = value;
+			}
+		}
+
+		public Buff(int configId, ObjectId ownerId)
+		{
+			this.configId = configId;
 			this.ownerId = ownerId;
-            if (this.Config.Duration != 0)
-            {
-                this.Expiration = TimeHelper.Now() + this.Config.Duration;
-            }
+			if (this.Config.Duration != 0)
+			{
+				this.Expiration = TimeHelper.Now() + this.Config.Duration;
+			}
 
 			if (this.Expiration != 0)
 			{
@@ -65,7 +65,7 @@ namespace Model
 				this.TimerId = World.Instance.GetComponent<TimerComponent>()
 						.Add(this.Expiration, CallbackType.BuffTimeoutCallback, env);
 			}
-        }
+		}
 
 		protected void Dispose(bool disposing)
 		{
@@ -74,8 +74,9 @@ namespace Model
 				return;
 			}
 
-			// Buff在垃圾回收或者主动Dispose,都需要释放Timer回调
+			// Buff在垃圾回收或者主动Dispose,都需要释放Timer回调.非托管资源
 			World.Instance.GetComponent<TimerComponent>().Remove(this.TimerId);
+
 			this.expiration = 0;
 		}
 
@@ -89,11 +90,6 @@ namespace Model
 			this.Dispose(true);
 		}
 
-		public override void BeginInit()
-		{
-			base.BeginInit();
-		}
-
 		public override void EndInit()
 		{
 			base.EndInit();
@@ -110,20 +106,20 @@ namespace Model
 		}
 
 		[BsonIgnore]
-        public BuffConfig Config
-        {
-            get
-            {
-                return World.Instance.GetComponent<ConfigComponent>().Get<BuffConfig>(this.configId);
-            }
-        }
+		public BuffConfig Config
+		{
+			get
+			{
+				return World.Instance.GetComponent<ConfigComponent>().Get<BuffConfig>(this.configId);
+			}
+		}
 
 		[BsonIgnore]
 		public ObjectId OwnerId
 		{
 			get
 			{
-				return ownerId;
+				return this.ownerId;
 			}
 
 			set

+ 6 - 6
CSharp/Game/Model/BuffType.cs

@@ -1,8 +1,8 @@
 namespace Model
 {
-    public enum BuffType
-    {
-        // 眩晕
-        Dizziness = 0,
-    }
-}
+	public enum BuffType
+	{
+		// 眩晕
+		Dizziness = 0,
+	}
+}

+ 16 - 16
CSharp/Game/Model/Component/BehaviorTreeComponent.cs

@@ -4,21 +4,21 @@ using Common.Base;
 
 namespace Model
 {
-    public class BehaviorTreeComponent : Component<World>, IAssemblyLoader
-    {
-        private Dictionary<int, BehaviorTree> trees = new Dictionary<int, BehaviorTree>();
+	public class BehaviorTreeComponent: Component<World>, IAssemblyLoader
+	{
+		private Dictionary<int, BehaviorTree> trees = new Dictionary<int, BehaviorTree>();
 
-        public void Load(Assembly assembly)
-        {
-            BehaviorTreeFactory behaviorTreeFactory = BehaviorTreeFactory.Instance;
-            behaviorTreeFactory.Load(assembly);
+		public void Load(Assembly assembly)
+		{
+			BehaviorTreeFactory behaviorTreeFactory = BehaviorTreeFactory.Instance;
+			behaviorTreeFactory.Load(assembly);
 
-            NodeConfig[] nodeConfigs = World.Instance.GetComponent<ConfigComponent>().GetAll<NodeConfig>();
-            foreach (NodeConfig nodeConfig in nodeConfigs)
-            {
-                BehaviorTree behaviorTree = behaviorTreeFactory.CreateTree(nodeConfig);
-                this.trees[nodeConfig.Id] = behaviorTree;
-            }
-        }
-    }
-}
+			NodeConfig[] nodeConfigs = World.Instance.GetComponent<ConfigComponent>().GetAll<NodeConfig>();
+			foreach (NodeConfig nodeConfig in nodeConfigs)
+			{
+				BehaviorTree behaviorTree = behaviorTreeFactory.CreateTree(nodeConfig);
+				this.trees[nodeConfig.Id] = behaviorTree;
+			}
+		}
+	}
+}

+ 116 - 115
CSharp/Game/Model/Component/BuffComponent.cs

@@ -7,124 +7,125 @@ using MongoDB.Bson.Serialization.Attributes;
 
 namespace Model
 {
-    public class BuffComponent : Component<Unit>
-    {
-        [BsonElement]
-        private HashSet<Buff> buffs;
-
-        [BsonIgnore]
-        private Dictionary<ObjectId, Buff> idBuff;
-
-        [BsonIgnore]
-        private MultiMap<BuffType, Buff> typeBuff;
-
-        public BuffComponent()
-        {
-            this.buffs = new HashSet<Buff>();
-            this.idBuff = new Dictionary<ObjectId, Buff>();
-            this.typeBuff = new MultiMap<BuffType, Buff>();
-        }
-
-        public override void BeginInit()
-        {
-            base.BeginInit();
-
-            this.buffs = new HashSet<Buff>();
-            this.idBuff = new Dictionary<ObjectId, Buff>();
-            this.typeBuff = new MultiMap<BuffType, Buff>();
-        }
-
-        public override void EndInit()
-        {
-            base.EndInit();
-
-            foreach (var buff in this.buffs)
-            {
-                this.idBuff.Add(buff.Id, buff);
-                this.typeBuff.Add(buff.Config.Type, buff);
-            }
-        }
-
-        public void Add(Buff buff)
-        {
-            if (this.buffs.Contains(buff))
-            {
-                throw new ArgumentException(string.Format("already exist same buff, Id: {0} ConfigId: {1}", buff.Id, buff.Config.Id));
-            }
-
-            if (this.idBuff.ContainsKey(buff.Id))
-            {
-                throw new ArgumentException(string.Format("already exist same buff, Id: {0} ConfigId: {1}", buff.Id, buff.Config.Id));
-            }
-
-            Env env = new Env();
-            env[EnvKey.Owner] = this.Owner;
-            env[EnvKey.Buff] = buff;
-
-            World.Instance.GetComponent<EventComponent<EventAttribute>>().Run(EventType.BeforeAddBuff, env);
-
-            this.buffs.Add(buff);
-            this.idBuff.Add(buff.Id, buff);
-            this.typeBuff.Add(buff.Config.Type, buff);
-
-            World.Instance.GetComponent<EventComponent<EventAttribute>>().Run(EventType.AfterAddBuff, env);
-        }
-
-        public Buff GetById(ObjectId id)
-        {
-            if (!this.idBuff.ContainsKey(id))
-            {
-                return null;
-            }
-
-            return this.idBuff[id];
-        }
-
-        public Buff GetOneByType(BuffType type)
-        {
-            return this.typeBuff.GetOne(type);
-        }
-
-        public Buff[] GetByType(BuffType type)
-        {
-            return this.typeBuff.GetAll(type);
-        }
-
-        private void Remove(Buff buff)
-        {
-            if (buff == null)
-            {
-                return;
-            }
-
-            Env env = new Env();
-            env[EnvKey.Owner] = this.Owner;
-            env[EnvKey.Buff] = buff;
-
-            World.Instance.GetComponent<EventComponent<EventAttribute>>().Run(EventType.BeforeRemoveBuff, env);
-
-            this.buffs.Remove(buff);
-            this.idBuff.Remove(buff.Id);
-            this.typeBuff.Remove(buff.Config.Type, buff);
-
-            World.Instance.GetComponent<EventComponent<EventAttribute>>().Run(EventType.AfterRemoveBuff, env);
-
-			buff.Dispose();
+	public class BuffComponent: Component<Unit>
+	{
+		[BsonElement]
+		private HashSet<Buff> buffs;
+
+		[BsonIgnore]
+		private Dictionary<ObjectId, Buff> idBuff;
+
+		[BsonIgnore]
+		private MultiMap<BuffType, Buff> typeBuff;
+
+		public BuffComponent()
+		{
+			this.buffs = new HashSet<Buff>();
+			this.idBuff = new Dictionary<ObjectId, Buff>();
+			this.typeBuff = new MultiMap<BuffType, Buff>();
 		}
 
-        public void RemoveById(ObjectId id)
-        {
-            Buff buff = this.GetById(id);
-            this.Remove(buff);
+		public override void BeginInit()
+		{
+			base.BeginInit();
+
+			this.buffs = new HashSet<Buff>();
+			this.idBuff = new Dictionary<ObjectId, Buff>();
+			this.typeBuff = new MultiMap<BuffType, Buff>();
+		}
+
+		public override void EndInit()
+		{
+			base.EndInit();
+
+			foreach (var buff in this.buffs)
+			{
+				this.idBuff.Add(buff.Id, buff);
+				this.typeBuff.Add(buff.Config.Type, buff);
+			}
+		}
+
+		public void Add(Buff buff)
+		{
+			if (this.buffs.Contains(buff))
+			{
+				throw new ArgumentException(string.Format("already exist same buff, Id: {0} ConfigId: {1}",
+						buff.Id, buff.Config.Id));
+			}
+
+			if (this.idBuff.ContainsKey(buff.Id))
+			{
+				throw new ArgumentException(string.Format("already exist same buff, Id: {0} ConfigId: {1}",
+						buff.Id, buff.Config.Id));
+			}
+
+			Env env = new Env();
+			env[EnvKey.Owner] = this.Owner;
+			env[EnvKey.Buff] = buff;
+
+			World.Instance.GetComponent<EventComponent<EventAttribute>>().Run(EventType.BeforeAddBuff, env);
+
+			this.buffs.Add(buff);
+			this.idBuff.Add(buff.Id, buff);
+			this.typeBuff.Add(buff.Config.Type, buff);
+
+			World.Instance.GetComponent<EventComponent<EventAttribute>>().Run(EventType.AfterAddBuff, env);
+		}
+
+		public Buff GetById(ObjectId id)
+		{
+			if (!this.idBuff.ContainsKey(id))
+			{
+				return null;
+			}
+
+			return this.idBuff[id];
+		}
+
+		public Buff GetOneByType(BuffType type)
+		{
+			return this.typeBuff.GetOne(type);
+		}
+
+		public Buff[] GetByType(BuffType type)
+		{
+			return this.typeBuff.GetAll(type);
+		}
+
+		private void Remove(Buff buff)
+		{
+			if (buff == null)
+			{
+				return;
+			}
+
+			Env env = new Env();
+			env[EnvKey.Owner] = this.Owner;
+			env[EnvKey.Buff] = buff;
+
+			World.Instance.GetComponent<EventComponent<EventAttribute>>()
+					.Run(EventType.BeforeRemoveBuff, env);
+
+			this.buffs.Remove(buff);
+			this.idBuff.Remove(buff.Id);
+			this.typeBuff.Remove(buff.Config.Type, buff);
+
+			World.Instance.GetComponent<EventComponent<EventAttribute>>().Run(EventType.AfterRemoveBuff, env);
+		}
+
+		public void RemoveById(ObjectId id)
+		{
+			Buff buff = this.GetById(id);
+			this.Remove(buff);
 		}
 
-        public void RemoveByType(BuffType type)
-        {
-            Buff[] allbuffs = this.GetByType(type);
-            foreach (Buff buff in allbuffs)
-            {
-                this.Remove(buff);
+		public void RemoveByType(BuffType type)
+		{
+			Buff[] allbuffs = this.GetByType(type);
+			foreach (Buff buff in allbuffs)
+			{
+				this.Remove(buff);
 			}
-        }
-    }
+		}
+	}
 }

+ 54 - 55
CSharp/Game/Model/Component/ConfigComponent.cs

@@ -6,66 +6,65 @@ using Common.Config;
 
 namespace Model
 {
-    public class ConfigComponent : Component<World>, IAssemblyLoader
-    {
-        public Dictionary<Type, ICategory> allConfig;
+	public class ConfigComponent: Component<World>, IAssemblyLoader
+	{
+		public Dictionary<Type, ICategory> allConfig;
 
-        public void Load(Assembly assembly)
-        {
-            allConfig = new Dictionary<Type, ICategory>();
-            Type[] types = assembly.GetTypes();
-            foreach (Type type in types)
-            {
-                object[] attrs = type.GetCustomAttributes(typeof(ConfigAttribute), false);
-                if (attrs.Length == 0)
-                {
-                    continue;
-                }
+		public void Load(Assembly assembly)
+		{
+			this.allConfig = new Dictionary<Type, ICategory>();
+			Type[] types = assembly.GetTypes();
+			foreach (Type type in types)
+			{
+				object[] attrs = type.GetCustomAttributes(typeof (ConfigAttribute), false);
+				if (attrs.Length == 0)
+				{
+					continue;
+				}
 
-                object obj = (Activator.CreateInstance(type));
+				object obj = (Activator.CreateInstance(type));
 
-                ICategory iCategory = obj as ICategory;
-                if (iCategory == null)
-                {
-                    throw new Exception(
-                        string.Format("class: {0} not inherit from ACategory", type.Name));
-                }
-                iCategory.BeginInit();
-                iCategory.EndInit();
+				ICategory iCategory = obj as ICategory;
+				if (iCategory == null)
+				{
+					throw new Exception(string.Format("class: {0} not inherit from ACategory", type.Name));
+				}
+				iCategory.BeginInit();
+				iCategory.EndInit();
 
-                allConfig[iCategory.ConfigType] = iCategory;
-            }
-        }
+				this.allConfig[iCategory.ConfigType] = iCategory;
+			}
+		}
 
-        public T Get<T>(int id) where T : AConfig
-        {
-            Type type = typeof (T);
-            ICategory configCategory;
-            if (!this.allConfig.TryGetValue(type, out configCategory))
-            {
-                throw new KeyNotFoundException(string.Format("ConfigComponent not found key: {0}", type.FullName));
-            }
-            return ((ACategory<T>) configCategory)[id];
-        }
+		public T Get<T>(int id) where T : AConfig
+		{
+			Type type = typeof (T);
+			ICategory configCategory;
+			if (!this.allConfig.TryGetValue(type, out configCategory))
+			{
+				throw new KeyNotFoundException(string.Format("ConfigComponent not found key: {0}", type.FullName));
+			}
+			return ((ACategory<T>) configCategory)[id];
+		}
 
-        public T[] GetAll<T>() where T : AConfig
-        {
-            Type type = typeof(T);
-            ICategory configCategory;
-            if (!this.allConfig.TryGetValue(type, out configCategory))
-            {
-                throw new KeyNotFoundException(string.Format("ConfigComponent not found key: {0}", type.FullName));
-            }
-            return ((ACategory<T>)configCategory).GetAll();
-        }
+		public T[] GetAll<T>() where T : AConfig
+		{
+			Type type = typeof (T);
+			ICategory configCategory;
+			if (!this.allConfig.TryGetValue(type, out configCategory))
+			{
+				throw new KeyNotFoundException(string.Format("ConfigComponent not found key: {0}", type.FullName));
+			}
+			return ((ACategory<T>) configCategory).GetAll();
+		}
 
-        public T GetCategory<T>() where T : class, ICategory, new()
-        {
-            T t = new T();
-            Type type = t.ConfigType;
-            ICategory category;
-            bool ret = this.allConfig.TryGetValue(type, out category);
-            return ret? (T) category : null;
-        }
-    }
+		public T GetCategory<T>() where T : class, ICategory, new()
+		{
+			T t = new T();
+			Type type = t.ConfigType;
+			ICategory category;
+			bool ret = this.allConfig.TryGetValue(type, out category);
+			return ret? (T) category : null;
+		}
+	}
 }

+ 43 - 43
CSharp/Game/Model/Component/EventComponent.cs

@@ -6,53 +6,53 @@ using Common.Event;
 
 namespace Model
 {
-    public class EventComponent<AttributeType> : Component<World>, IAssemblyLoader
-        where AttributeType : AEventAttribute
-    {
-        private Dictionary<int, List<IEvent>> events;
+	public class EventComponent<AttributeType>: Component<World>, IAssemblyLoader
+			where AttributeType : AEventAttribute
+	{
+		private Dictionary<int, List<IEvent>> events;
 
-        public void Load(Assembly assembly)
-        {
-            this.events = new Dictionary<int, List<IEvent>>();
+		public void Load(Assembly assembly)
+		{
+			this.events = new Dictionary<int, List<IEvent>>();
 
-            var types = assembly.GetTypes();
-            foreach (var t in types)
-            {
-                object[] attrs = t.GetCustomAttributes(typeof (AttributeType), false);
-                if (attrs.Length == 0)
-                { 
-                    continue;
-                }
-                object obj = Activator.CreateInstance(t);
-                IEvent iEvent = obj as IEvent;
-                if (iEvent == null)
-                {
-                    throw new Exception(string.Format("event not inherit IEvent interface: {0}",
-                            obj.GetType().FullName));
-                }
+			var types = assembly.GetTypes();
+			foreach (var t in types)
+			{
+				object[] attrs = t.GetCustomAttributes(typeof (AttributeType), false);
+				if (attrs.Length == 0)
+				{
+					continue;
+				}
+				object obj = Activator.CreateInstance(t);
+				IEvent iEvent = obj as IEvent;
+				if (iEvent == null)
+				{
+					throw new Exception(string.Format("event not inherit IEvent interface: {0}",
+							obj.GetType().FullName));
+				}
 
-                AEventAttribute iEventAttribute = (AEventAttribute) attrs[0];
+				AEventAttribute iEventAttribute = (AEventAttribute) attrs[0];
 
-                if (!this.events.ContainsKey(iEventAttribute.Type))
-                {
-                    this.events.Add(iEventAttribute.Type, new List<IEvent>());
-                }
-                this.events[iEventAttribute.Type].Add(iEvent);
-            }
-        }
+				if (!this.events.ContainsKey(iEventAttribute.Type))
+				{
+					this.events.Add(iEventAttribute.Type, new List<IEvent>());
+				}
+				this.events[iEventAttribute.Type].Add(iEvent);
+			}
+		}
 
-        public void Run(int type, Env env)
-        {
-            List<IEvent> iEventDict = null;
-            if (!this.events.TryGetValue(type, out iEventDict))
-            {
-                return;
-            }
+		public void Run(int type, Env env)
+		{
+			List<IEvent> iEventDict = null;
+			if (!this.events.TryGetValue(type, out iEventDict))
+			{
+				return;
+			}
 
-            foreach (var iEvent in iEventDict)
-            {
-                iEvent.Run(env);
-            }
-        }
-    }
+			foreach (var iEvent in iEventDict)
+			{
+				iEvent.Run(env);
+			}
+		}
+	}
 }

+ 35 - 36
CSharp/Game/Model/Component/FactoryComponent.cs

@@ -5,45 +5,44 @@ using Common.Base;
 
 namespace Model
 {
-    public class FactoryComponent<T> : Component<World>, IAssemblyLoader where T : Entity<T>
-    {
-        private Dictionary<int, IFactory<T>> allConfig;
+	public class FactoryComponent<T>: Component<World>, IAssemblyLoader where T : Entity<T>
+	{
+		private Dictionary<int, IFactory<T>> allConfig;
 
-        public void Load(Assembly assembly)
-        {
-            allConfig = new Dictionary<int, IFactory<T>>();
-            Type[] types = assembly.GetTypes();
-            foreach (Type type in types)
-            {
-                object[] attrs = type.GetCustomAttributes(typeof(FactoryAttribute), false);
-                if (attrs.Length == 0)
-                {
-                    continue;
-                }
+		public void Load(Assembly assembly)
+		{
+			this.allConfig = new Dictionary<int, IFactory<T>>();
+			Type[] types = assembly.GetTypes();
+			foreach (Type type in types)
+			{
+				object[] attrs = type.GetCustomAttributes(typeof (FactoryAttribute), false);
+				if (attrs.Length == 0)
+				{
+					continue;
+				}
 
-                FactoryAttribute attribute = (FactoryAttribute)attrs[0];
-                if (attribute.ClassType != typeof (T))
-                {
-                    continue;
-                }
+				FactoryAttribute attribute = (FactoryAttribute) attrs[0];
+				if (attribute.ClassType != typeof (T))
+				{
+					continue;
+				}
 
-                object obj = (Activator.CreateInstance(type));
+				object obj = (Activator.CreateInstance(type));
 
-                IFactory<T> iFactory = obj as IFactory<T>;
-                if (iFactory == null)
-                {
-                    throw new Exception(
-                        string.Format("class: {0} not inherit from IFactory", type.Name));
-                }
+				IFactory<T> iFactory = obj as IFactory<T>;
+				if (iFactory == null)
+				{
+					throw new Exception(string.Format("class: {0} not inherit from IFactory", type.Name));
+				}
 
-                allConfig[attribute.Type] = iFactory;
-            }
-        }
+				this.allConfig[attribute.Type] = iFactory;
+			}
+		}
 
-        public T Create(int configId)
-        {
-            int type = World.Instance.GetComponent<ConfigComponent>().Get<UnitConfig>(configId).Type;
-            return this.allConfig[type].Create(configId);
-        }
-    }
-}
+		public T Create(int configId)
+		{
+			int type = World.Instance.GetComponent<ConfigComponent>().Get<UnitConfig>(configId).Type;
+			return this.allConfig[type].Create(configId);
+		}
+	}
+}

+ 7 - 12
CSharp/Game/Model/Component/MessageComponent.cs

@@ -1,14 +1,9 @@
-using System.Collections.Generic;
-using Common.Base;
-using MongoDB.Bson;
-using MongoDB.Bson.Serialization.Attributes;
-
-namespace Model
+namespace Model
 {
-    public class MessageComponent
-    {
-        public MessageComponent()
-        {
-        }
-    }
+	public class MessageComponent
+	{
+		public MessageComponent()
+		{
+		}
+	}
 }

+ 66 - 65
CSharp/Game/Model/Component/TimerComponent.cs

@@ -6,74 +6,75 @@ using MongoDB.Bson;
 
 namespace Model
 {
-    public class TimerComponent: Component<World>
-    {
-        private class Timer
-        {
-            public ObjectId Id { get; set; }
-            public long Time { get; set; }
-            public int CallbackId { get; set; }
-            public Env Env { get; set; }
-        }
+	public class TimerComponent: Component<World>
+	{
+		private class Timer
+		{
+			public ObjectId Id { get; set; }
+			public long Time { get; set; }
+			public int CallbackId { get; set; }
+			public Env Env { get; set; }
+		}
 
-        private readonly Dictionary<ObjectId, Timer> timers = new Dictionary<ObjectId, Timer>();
+		private readonly Dictionary<ObjectId, Timer> timers = new Dictionary<ObjectId, Timer>();
 
-        /// <summary>
-        /// key: time, value: timer id
-        /// </summary>
-        private readonly MultiMap<long, ObjectId> timeId = new MultiMap<long, ObjectId>();
+		/// <summary>
+		/// key: time, value: timer id
+		/// </summary>
+		private readonly MultiMap<long, ObjectId> timeId = new MultiMap<long, ObjectId>();
 
-        public ObjectId Add(long time, int callbackId, Env env)
-        {
-            Timer timer = new Timer
-            {
-                Id = ObjectId.GenerateNewId(), 
-                Time = time, 
-                CallbackId = callbackId,
-                Env = env
-            };
-            this.timers[timer.Id] = timer;
-            this.timeId.Add(timer.Time, timer.Id);
-            return timer.Id;
-        }
+		public ObjectId Add(long time, int callbackId, Env env)
+		{
+			Timer timer = new Timer
+			{
+				Id = ObjectId.GenerateNewId(),
+				Time = time,
+				CallbackId = callbackId,
+				Env = env
+			};
+			this.timers[timer.Id] = timer;
+			this.timeId.Add(timer.Time, timer.Id);
+			return timer.Id;
+		}
 
-        public void Remove(ObjectId id)
-        {
-            Timer timer;
-            if (!this.timers.TryGetValue(id, out timer))
-            {
-                return;
-            }
-            this.timeId.Remove(timer.Time, timer.Id);
-        }
+		public void Remove(ObjectId id)
+		{
+			Timer timer;
+			if (!this.timers.TryGetValue(id, out timer))
+			{
+				return;
+			}
+			this.timeId.Remove(timer.Time, timer.Id);
+		}
 
-        public void Update()
-        {
-            long timeNow = TimeHelper.Now();
-            List<long> timeoutTimer = new List<long>();
-            foreach (long time in this.timeId.Keys)
-            {
-                if (time > timeNow)
-                {
-                    break;
-                }
-                timeoutTimer.Add(time);
-            }
+		public void Update()
+		{
+			long timeNow = TimeHelper.Now();
+			List<long> timeoutTimer = new List<long>();
+			foreach (long time in this.timeId.Keys)
+			{
+				if (time > timeNow)
+				{
+					break;
+				}
+				timeoutTimer.Add(time);
+			}
 
-            foreach (long key in timeoutTimer)
-            {
-                List<ObjectId> timeOutId = this.timeId[key];
-                foreach (ObjectId id in timeOutId)
-                {
-                    Timer timer;
-                    if (!this.timers.TryGetValue(id, out timer))
-                    {
-                        continue;
-                    }
-                    this.Remove(id);
-                    World.Instance.GetComponent<EventComponent<CallbackAttribute>>().Run(timer.CallbackId, timer.Env);
-                }
-            }
-        }
-    }
-}
+			foreach (long key in timeoutTimer)
+			{
+				List<ObjectId> timeOutId = this.timeId[key];
+				foreach (ObjectId id in timeOutId)
+				{
+					Timer timer;
+					if (!this.timers.TryGetValue(id, out timer))
+					{
+						continue;
+					}
+					this.Remove(id);
+					World.Instance.GetComponent<EventComponent<CallbackAttribute>>()
+							.Run(timer.CallbackId, timer.Env);
+				}
+			}
+		}
+	}
+}

+ 55 - 56
CSharp/Game/Model/Component/UnitComponent.cs

@@ -6,66 +6,65 @@ using MongoDB.Bson;
 
 namespace Model
 {
-    public class UnitComponent : Component<World>
-    {
-        private readonly Dictionary<ObjectId, Unit> units =
-                new Dictionary<ObjectId, Unit>();
+	public class UnitComponent: Component<World>
+	{
+		private readonly Dictionary<ObjectId, Unit> units = new Dictionary<ObjectId, Unit>();
 
-        private readonly Dictionary<int, Dictionary<ObjectId, Unit>> typeUnits =
-                new Dictionary<int, Dictionary<ObjectId, Unit>>();
+		private readonly Dictionary<int, Dictionary<ObjectId, Unit>> typeUnits =
+				new Dictionary<int, Dictionary<ObjectId, Unit>>();
 
-        public void Add(Unit unit)
-        {
-            this.units.Add(unit.Id, unit);
-            if (!this.typeUnits.ContainsKey(unit.Config.Type))
-            {
-                this.typeUnits.Add(unit.Config.Type, new Dictionary<ObjectId, Unit>());
-            }
-            this.typeUnits[unit.Config.Type].Add(unit.Id, unit);
-        }
+		public void Add(Unit unit)
+		{
+			this.units.Add(unit.Id, unit);
+			if (!this.typeUnits.ContainsKey(unit.Config.Type))
+			{
+				this.typeUnits.Add(unit.Config.Type, new Dictionary<ObjectId, Unit>());
+			}
+			this.typeUnits[unit.Config.Type].Add(unit.Id, unit);
+		}
 
-        public Unit Get(ObjectId id)
-        {
-            Unit unit = null;
-            this.units.TryGetValue(id, out unit);
-            return unit;
-        }
+		public Unit Get(ObjectId id)
+		{
+			Unit unit = null;
+			this.units.TryGetValue(id, out unit);
+			return unit;
+		}
 
-        public Unit[] GetOneType(int type)
-        {
-            Dictionary<ObjectId, Unit> oneTypeUnits = null;
-            if (!this.typeUnits.TryGetValue(type, out oneTypeUnits))
-            {
-                return new Unit[0];
-            }
-            return oneTypeUnits.Values.ToArray();
-        }
+		public Unit[] GetOneType(int type)
+		{
+			Dictionary<ObjectId, Unit> oneTypeUnits = null;
+			if (!this.typeUnits.TryGetValue(type, out oneTypeUnits))
+			{
+				return new Unit[0];
+			}
+			return oneTypeUnits.Values.ToArray();
+		}
 
-        public bool Remove(Unit unit)
-        {
-            if (unit == null)
-            {
-                throw new ArgumentNullException("unit");
-            }
-            if (!this.units.Remove(unit.Id))
-            {
-                return false;
-            }
-            if (!this.typeUnits[unit.Config.Type].Remove(unit.Id))
-            {
-                return false;
-            }
-            return true;
-        }
+		public bool Remove(Unit unit)
+		{
+			if (unit == null)
+			{
+				throw new ArgumentNullException("unit");
+			}
+			if (!this.units.Remove(unit.Id))
+			{
+				return false;
+			}
+			if (!this.typeUnits[unit.Config.Type].Remove(unit.Id))
+			{
+				return false;
+			}
+			return true;
+		}
 
-        public bool Remove(ObjectId id)
-        {
-            Unit unit = this.Get(id);
-            if (unit == null)
-            {
-                return false;
-            }
-            return this.Remove(unit);
-        }
-    }
+		public bool Remove(ObjectId id)
+		{
+			Unit unit = this.Get(id);
+			if (unit == null)
+			{
+				return false;
+			}
+			return this.Remove(unit);
+		}
+	}
 }

+ 14 - 14
CSharp/Game/Model/Config/BuffConfig.cs

@@ -1,19 +1,19 @@
- using System.Collections.Generic;
+using System.Collections.Generic;
 using Common.Config;
 
 namespace Model
 {
-    public class BuffConfig: AConfig
-    {
-        public BuffType Type { get; set; }
-        public string Name { get; set; }
-        public long Duration { get; set; }
-        public int MaxStack { get; set; }
-        public List<int> Effects { get; set; }
+	public class BuffConfig: AConfig
+	{
+		public BuffType Type { get; set; }
+		public string Name { get; set; }
+		public long Duration { get; set; }
+		public int MaxStack { get; set; }
+		public List<int> Effects { get; set; }
 
-        public BuffConfig()
-        {
-            this.Effects = new List<int>();
-        }
-    }
-}
+		public BuffConfig()
+		{
+			this.Effects = new List<int>();
+		}
+	}
+}

+ 4 - 4
CSharp/Game/Model/Config/GlobalConfig.cs

@@ -2,8 +2,8 @@
 
 namespace Model
 {
-    public class GlobalConfig: AConfig
-    {
-        public int Type { get; set; }
-    }
+	public class GlobalConfig: AConfig
+	{
+		public int Type { get; set; }
+	}
 }

+ 5 - 5
CSharp/Game/Model/Config/NodeConfig.cs

@@ -3,9 +3,9 @@ using Common.Config;
 
 namespace Model
 {
-    public class NodeConfig: AConfig
-    {
-        public List<string> Args { get; set; }
-        public List<NodeConfig> SubConfigs { get; set; }
-    }
+	public class NodeConfig: AConfig
+	{
+		public List<string> Args { get; set; }
+		public List<NodeConfig> SubConfigs { get; set; }
+	}
 }

+ 5 - 5
CSharp/Game/Model/Config/UnitConfig.cs

@@ -2,8 +2,8 @@
 
 namespace Model
 {
-    public class UnitConfig: AConfig
-    {
-        public int Type { get; set; }
-    }
-}
+	public class UnitConfig: AConfig
+	{
+		public int Type { get; set; }
+	}
+}

+ 8 - 8
CSharp/Game/Model/EnvKey.cs

@@ -1,10 +1,10 @@
 namespace Model
 {
-    public static class EnvKey
-    {
-        public const string Owner = "Owner";
-        public const string OwnerId = "OwnerId";
-        public const string Buff = "Buff";
-        public const string BuffId = "BuffId";
-    }
-}
+	public static class EnvKey
+	{
+		public const string Owner = "Owner";
+		public const string OwnerId = "OwnerId";
+		public const string Buff = "Buff";
+		public const string BuffId = "BuffId";
+	}
+}

+ 13 - 13
CSharp/Game/Model/EventAttribute.cs

@@ -2,17 +2,17 @@
 
 namespace Model
 {
-    public class EventAttribute: AEventAttribute
-    {
-        public EventAttribute(int type): base(type)
-        {
-        }
-    }
+	public class EventAttribute: AEventAttribute
+	{
+		public EventAttribute(int type): base(type)
+		{
+		}
+	}
 
-    public class CallbackAttribute : AEventAttribute
-    {
-        public CallbackAttribute(int type): base(type)
-        {
-        }
-    }
-}
+	public class CallbackAttribute: AEventAttribute
+	{
+		public CallbackAttribute(int type): base(type)
+		{
+		}
+	}
+}

+ 12 - 12
CSharp/Game/Model/EventType.cs

@@ -1,15 +1,15 @@
 namespace Model
 {
-    public static class EventType
-    {
-        public const int BeforeAddBuff = 0;
-        public const int AfterAddBuff = 1;
-        public const int BeforeRemoveBuff = 2;
-        public const int AfterRemoveBuff = 3;
-    }
+	public static class EventType
+	{
+		public const int BeforeAddBuff = 0;
+		public const int AfterAddBuff = 1;
+		public const int BeforeRemoveBuff = 2;
+		public const int AfterRemoveBuff = 3;
+	}
 
-    public static class CallbackType
-    {
-        public const int BuffTimeoutCallback = 0;
-    }
-}
+	public static class CallbackType
+	{
+		public const int BuffTimeoutCallback = 0;
+	}
+}

+ 11 - 11
CSharp/Game/Model/FactoryAttribute.cs

@@ -2,16 +2,16 @@
 
 namespace Model
 {
-    [AttributeUsage(AttributeTargets.Class)]
-    public class FactoryAttribute : Attribute
-    {
-        public Type ClassType { get; private set; }
-        public int Type { get; private set; }
+	[AttributeUsage(AttributeTargets.Class)]
+	public class FactoryAttribute: Attribute
+	{
+		public Type ClassType { get; private set; }
+		public int Type { get; private set; }
 
-        public FactoryAttribute(Type classType, int type)
-        {
-            this.ClassType = classType;
-            this.Type = type;
-        }
-    }
+		public FactoryAttribute(Type classType, int type)
+		{
+			this.ClassType = classType;
+			this.Type = type;
+		}
+	}
 }

+ 6 - 5
CSharp/Game/Model/IAssemblyLoader.cs

@@ -1,8 +1,9 @@
 using System.Reflection;
+
 namespace Model
 {
-    public interface IAssemblyLoader
-    {
-        void Load(Assembly assembly);
-    }
-}
+	public interface IAssemblyLoader
+	{
+		void Load(Assembly assembly);
+	}
+}

+ 4 - 4
CSharp/Game/Model/IFactory.cs

@@ -2,8 +2,8 @@
 
 namespace Model
 {
-    public interface IFactory<out T> where T : Entity<T>
-    {
-        T Create(int configId);
-    }
+	public interface IFactory<out T> where T : Entity<T>
+	{
+		T Create(int configId);
+	}
 }

+ 10 - 10
CSharp/Game/Model/MessageAttribute.cs

@@ -2,13 +2,13 @@
 
 namespace Model
 {
-    /// <summary>
-    /// 搭配EventComponent用来分发消息
-    /// </summary>
-    public class MessageAttribute: AEventAttribute
-    {
-        public MessageAttribute(int type): base(type)
-        {
-        }
-    }
-}
+	/// <summary>
+	/// 搭配EventComponent用来分发消息
+	/// </summary>
+	public class MessageAttribute: AEventAttribute
+	{
+		public MessageAttribute(int type): base(type)
+		{
+		}
+	}
+}

+ 17 - 17
CSharp/Game/Model/Unit.cs

@@ -3,23 +3,23 @@ using MongoDB.Bson.Serialization.Attributes;
 
 namespace Model
 {
-    public class Unit : Entity<Unit>
-    {
-        [BsonElement]
-        private int configId { get; set; }
+	public class Unit: Entity<Unit>
+	{
+		[BsonElement]
+		private int configId { get; set; }
 
-        [BsonIgnore]
-        public UnitConfig Config
-        {
-            get
-            {
-                return World.Instance.GetComponent<ConfigComponent>().Get<UnitConfig>(this.configId);
-            }
-        }
+		[BsonIgnore]
+		public UnitConfig Config
+		{
+			get
+			{
+				return World.Instance.GetComponent<ConfigComponent>().Get<UnitConfig>(this.configId);
+			}
+		}
 
-        public Unit(int configId)
-        {
-            this.configId = configId;
-        }
-    }
+		public Unit(int configId)
+		{
+			this.configId = configId;
+		}
+	}
 }

+ 28 - 28
CSharp/Game/Model/World.cs

@@ -4,37 +4,37 @@ using Common.Base;
 
 namespace Model
 {
-    public class World : Entity<World>
-    {
-        private static readonly World instance = new World();
+	public class World: Entity<World>
+	{
+		private static readonly World instance = new World();
 
-        public Assembly Assembly { get; set; }
+		public Assembly Assembly { get; set; }
 
-        public static World Instance
-        {
-            get
-            {
-                return instance;
-            }
-        }
+		public static World Instance
+		{
+			get
+			{
+				return instance;
+			}
+		}
 
-        private World()
-        {
-        }
+		private World()
+		{
+		}
 
-        public void Load()
-        {
-            this.Assembly = Assembly.Load(File.ReadAllBytes(@"./Controller.dll"));
+		public void Load()
+		{
+			this.Assembly = Assembly.Load(File.ReadAllBytes(@"./Controller.dll"));
 
-            foreach (Component<World> component in this.GetComponents())
-            {
-                IAssemblyLoader assemblyLoader = component as IAssemblyLoader;
-                if (assemblyLoader == null)
-                {
-                    continue;
-                }
-                assemblyLoader.Load(this.Assembly);
-            }
-        }
-    }
+			foreach (Component<World> component in this.GetComponents())
+			{
+				IAssemblyLoader assemblyLoader = component as IAssemblyLoader;
+				if (assemblyLoader == null)
+				{
+					continue;
+				}
+				assemblyLoader.Load(this.Assembly);
+			}
+		}
+	}
 }

+ 46 - 48
CSharp/Game/MongoDBTest/MongoDBTest.cs

@@ -7,51 +7,49 @@ using MongoDB.Driver.Builders;
 
 namespace MongoDBTest
 {
-    [TestClass]
-    public class MongoDBTest
-    {
-        [TestMethod]
-        public void TestMongoDB()
-        {
-            const string connectionString = "mongodb://localhost";
-            var client = new MongoClient(connectionString);
-            var server = client.GetServer();
-            var database = server.GetDatabase("test");
-            var collection = database.GetCollection<Unit>("Unit");
-
-
-            World world = World.Instance;
-
-            // 加载配置
-            world.AddComponent<ConfigComponent>();
-            world.AddComponent<EventComponent<CallbackAttribute>>();
-            world.AddComponent<EventComponent<EventAttribute>>();
-            world.AddComponent<TimerComponent>();
-            world.AddComponent<UnitComponent>();
-            world.AddComponent<FactoryComponent<Unit>>();
-            world.AddComponent<BehaviorTreeComponent>();
-            world.Load();
-
-
-            Unit player1 = world.GetComponent<FactoryComponent<Unit>>().Create(1);
-            player1["hp"] = 10;
-            
-            collection.Insert(player1);
-
-            var query = Query<Unit>.EQ(e => e.Id, player1.Id);
-            Unit player2 = collection.FindOne(query);
-            
-            Console.WriteLine(MongoHelper.ToJson(player2));
-            Assert.AreEqual(MongoHelper.ToJson(player1), MongoHelper.ToJson(player2));
-
-            Unit player3 = player1.Clone();
-
-            Assert.AreEqual(MongoHelper.ToJson(player1), MongoHelper.ToJson(player3));
-
-            //Thread.Sleep(20 * 1000);
-            //world.Load();
-            //
-            //Assert.AreEqual(MongoHelper.ToJson(player1), MongoHelper.ToJson(player2));
-        }
-    }
-}
+	[TestClass]
+	public class MongoDBTest
+	{
+		[TestMethod]
+		public void TestMongoDB()
+		{
+			const string connectionString = "mongodb://localhost";
+			var client = new MongoClient(connectionString);
+			var server = client.GetServer();
+			var database = server.GetDatabase("test");
+			var collection = database.GetCollection<Unit>("Unit");
+
+			World world = World.Instance;
+
+			// 加载配置
+			world.AddComponent<ConfigComponent>();
+			world.AddComponent<EventComponent<CallbackAttribute>>();
+			world.AddComponent<EventComponent<EventAttribute>>();
+			world.AddComponent<TimerComponent>();
+			world.AddComponent<UnitComponent>();
+			world.AddComponent<FactoryComponent<Unit>>();
+			world.AddComponent<BehaviorTreeComponent>();
+			world.Load();
+
+			Unit player1 = world.GetComponent<FactoryComponent<Unit>>().Create(1);
+			player1["hp"] = 10;
+
+			collection.Insert(player1);
+
+			var query = Query<Unit>.EQ(e => e.Id, player1.Id);
+			Unit player2 = collection.FindOne(query);
+
+			Console.WriteLine(MongoHelper.ToJson(player2));
+			Assert.AreEqual(MongoHelper.ToJson(player1), MongoHelper.ToJson(player2));
+
+			Unit player3 = player1.Clone();
+
+			Assert.AreEqual(MongoHelper.ToJson(player1), MongoHelper.ToJson(player3));
+
+			//Thread.Sleep(20 * 1000);
+			//world.Load();
+			//
+			//Assert.AreEqual(MongoHelper.ToJson(player1), MongoHelper.ToJson(player2));
+		}
+	}
+}

+ 28 - 28
CSharp/Platform/Common/Base/Component.cs

@@ -3,34 +3,34 @@ using MongoDB.Bson.Serialization.Attributes;
 
 namespace Common.Base
 {
-    /// <summary>
-    /// Component的Id与Owner Entity Id一样
-    /// </summary>
-    public abstract class Component<T>: Object where T: Entity<T>
-    {
-        private T owner;
+	/// <summary>
+	/// Component的Id与Owner Entity Id一样
+	/// </summary>
+	public abstract class Component<T>: Object where T : Entity<T>
+	{
+		private T owner;
 
-        [BsonIgnore]
-        public T Owner
-        {
-            get
-            {
-                return owner;
-            }
-            set
-            {
-                this.owner = value;
-                this.Id = this.owner.Id;
-            }
-        }
+		[BsonIgnore]
+		public T Owner
+		{
+			get
+			{
+				return this.owner;
+			}
+			set
+			{
+				this.owner = value;
+				this.Id = this.owner.Id;
+			}
+		}
 
-        /// <summary>
-        /// 用于父类的Component需要重写此方法
-        /// </summary>
-        /// <returns></returns>
-        public virtual Type GetComponentType()
-        {
-            return this.GetType();
-        }
-    }
+		/// <summary>
+		/// 用于父类的Component需要重写此方法
+		/// </summary>
+		/// <returns></returns>
+		public virtual Type GetComponentType()
+		{
+			return this.GetType();
+		}
+	}
 }

+ 106 - 107
CSharp/Platform/Common/Base/Entity.cs

@@ -6,111 +6,110 @@ using MongoDB.Bson.Serialization.Attributes;
 
 namespace Common.Base
 {
-    public abstract class Entity<T> : Object where T : Entity<T>
-    {
-        [BsonElement] 
-        [BsonIgnoreIfNull]
-        private HashSet<Component<T>> components;
-
-        private Dictionary<Type, Component<T>> componentDict = new Dictionary<Type, Component<T>>();
-
-        public T Clone()
-        {
-            return MongoHelper.FromBson<T>(MongoHelper.ToBson(this));
-        }
-
-        public K AddComponent<K>() where K : Component<T>, new()
-        {
-            K component = new K { Owner = (T) this };
-
-            if (this.componentDict.ContainsKey(component.GetComponentType()))
-            {
-                throw new Exception(
-                    string.Format("AddComponent, component already exist, id: {0}, component: {1}",
-                    this.Id, typeof(K).Name));
-            }
-
-            if (this.components == null)
-            {
-                this.components = new HashSet<Component<T>>();
-            }
-
-            this.components.Add(component);
-            this.componentDict.Add(component.GetComponentType(), component);
-            return component;
-        }
-
-        public void AddComponent(Component<T> component)
-        {
-            if (this.componentDict.ContainsKey(component.GetComponentType()))
-            {
-                throw new Exception(
-                    string.Format("AddComponent, component already exist, id: {0}, component: {1}",
-                    this.Id, component.GetComponentType().Name));
-            }
-
-            if (this.components == null)
-            {
-                this.components = new HashSet<Component<T>>();
-            }
-            this.components.Add(component);
-            this.componentDict.Add(component.GetComponentType(), component);
-        }
-
-        public void RemoveComponent<K>() where K : Component<T>
-        {
-            Component<T> component;
-            if (!this.componentDict.TryGetValue(typeof (K), out component))
-            {
-                throw new Exception(
-                    string.Format("RemoveComponent, component not exist, id: {0}, component: {1}",
-                    this.Id, typeof(K).Name));
-            }
-            
-            this.components.Remove(component);
-            this.componentDict.Remove(typeof(K));
-
-            if (this.components.Count == 0)
-            {
-                this.components = null;
-            }
-        }
-
-        public K GetComponent<K>() where K : Component<T>
-        {
-            Component<T> component;
-            if (!this.componentDict.TryGetValue(typeof (K), out component))
-            {
-                return default (K);
-            }
-            return (K) component;
-        }
-
-        public Component<T>[] GetComponents()
-        {
-            return this.components.ToArray();
-        }
-
-        public override void BeginInit()
-        {
-            base.BeginInit();
-            this.components = new HashSet<Component<T>>();
-            this.componentDict = new Dictionary<Type, Component<T>>();
-        }
-
-        public override void EndInit()
-        {
-            base.EndInit();
-            if (this.components.Count == 0)
-            {
-                this.components = null;
-                return;
-            }
-            foreach (var component in this.components)
-            {
-                component.Owner = (T) this;
-                this.componentDict.Add(component.GetComponentType(), component);
-            }
-        }
-    }
+	public abstract class Entity<T>: Object where T : Entity<T>
+	{
+		[BsonElement, BsonIgnoreIfNull]
+		private HashSet<Component<T>> components;
+
+		private Dictionary<Type, Component<T>> componentDict = new Dictionary<Type, Component<T>>();
+
+		public T Clone()
+		{
+			return MongoHelper.FromBson<T>(MongoHelper.ToBson(this));
+		}
+
+		public K AddComponent<K>() where K : Component<T>, new()
+		{
+			K component = new K { Owner = (T) this };
+
+			if (this.componentDict.ContainsKey(component.GetComponentType()))
+			{
+				throw new Exception(
+						string.Format("AddComponent, component already exist, id: {0}, component: {1}", this.Id,
+								typeof (K).Name));
+			}
+
+			if (this.components == null)
+			{
+				this.components = new HashSet<Component<T>>();
+			}
+
+			this.components.Add(component);
+			this.componentDict.Add(component.GetComponentType(), component);
+			return component;
+		}
+
+		public void AddComponent(Component<T> component)
+		{
+			if (this.componentDict.ContainsKey(component.GetComponentType()))
+			{
+				throw new Exception(
+						string.Format("AddComponent, component already exist, id: {0}, component: {1}", this.Id,
+								component.GetComponentType().Name));
+			}
+
+			if (this.components == null)
+			{
+				this.components = new HashSet<Component<T>>();
+			}
+			this.components.Add(component);
+			this.componentDict.Add(component.GetComponentType(), component);
+		}
+
+		public void RemoveComponent<K>() where K : Component<T>
+		{
+			Component<T> component;
+			if (!this.componentDict.TryGetValue(typeof (K), out component))
+			{
+				throw new Exception(
+						string.Format("RemoveComponent, component not exist, id: {0}, component: {1}", this.Id,
+								typeof (K).Name));
+			}
+
+			this.components.Remove(component);
+			this.componentDict.Remove(typeof (K));
+
+			if (this.components.Count == 0)
+			{
+				this.components = null;
+			}
+		}
+
+		public K GetComponent<K>() where K : Component<T>
+		{
+			Component<T> component;
+			if (!this.componentDict.TryGetValue(typeof (K), out component))
+			{
+				return default (K);
+			}
+			return (K) component;
+		}
+
+		public Component<T>[] GetComponents()
+		{
+			return this.components.ToArray();
+		}
+
+		public override void BeginInit()
+		{
+			base.BeginInit();
+			this.components = new HashSet<Component<T>>();
+			this.componentDict = new Dictionary<Type, Component<T>>();
+		}
+
+		public override void EndInit()
+		{
+			base.EndInit();
+			if (this.components.Count == 0)
+			{
+				this.components = null;
+				return;
+			}
+			foreach (var component in this.components)
+			{
+				component.Owner = (T) this;
+				this.componentDict.Add(component.GetComponentType(), component);
+			}
+		}
+	}
 }

+ 98 - 99
CSharp/Platform/Common/Base/MultiMap.cs

@@ -2,111 +2,110 @@
 
 namespace Common.Base
 {
-    public class MultiMap<T, K>
-    {
-        private readonly SortedDictionary<T, List<K>> dictionary =
-                new SortedDictionary<T, List<K>>();
+	public class MultiMap<T, K>
+	{
+		private readonly SortedDictionary<T, List<K>> dictionary = new SortedDictionary<T, List<K>>();
 
-        public SortedDictionary<T, List<K>>.KeyCollection Keys
-        {
-            get
-            {
-                return this.dictionary.Keys;
-            }
-        }
+		public SortedDictionary<T, List<K>>.KeyCollection Keys
+		{
+			get
+			{
+				return this.dictionary.Keys;
+			}
+		}
 
-        public void Add(T t, K k)
-        {
-            List<K> list;
-            this.dictionary.TryGetValue(t, out list);
-            if (list == null)
-            {
-                list = new List<K>();
-            }
-            list.Add(k);
-            this.dictionary[t] = list;
-        }
+		public void Add(T t, K k)
+		{
+			List<K> list;
+			this.dictionary.TryGetValue(t, out list);
+			if (list == null)
+			{
+				list = new List<K>();
+			}
+			list.Add(k);
+			this.dictionary[t] = list;
+		}
 
-        public bool Remove(T t, K k)
-        {
-            List<K> list;
-            this.dictionary.TryGetValue(t, out list);
-            if (list == null)
-            {
-                return false;
-            }
-            if (!list.Remove(k))
-            {
-                return false;
-            }
-            if (list.Count == 0)
-            {
-                this.dictionary.Remove(t);
-            }
-            return true;
-        }
+		public bool Remove(T t, K k)
+		{
+			List<K> list;
+			this.dictionary.TryGetValue(t, out list);
+			if (list == null)
+			{
+				return false;
+			}
+			if (!list.Remove(k))
+			{
+				return false;
+			}
+			if (list.Count == 0)
+			{
+				this.dictionary.Remove(t);
+			}
+			return true;
+		}
 
-        public bool Remove(T t)
-        {
-            return this.dictionary.Remove(t);
-        }
+		public bool Remove(T t)
+		{
+			return this.dictionary.Remove(t);
+		}
 
-        /// <summary>
-        /// 不返回内部的list,copy一份出来
-        /// </summary>
-        /// <param name="t"></param>
-        /// <returns></returns>
-        public K[] GetAll(T t)
-        {
-            List<K> list;
-            this.dictionary.TryGetValue(t, out list);
-            if (list == null)
-            {
-                return new K[0];
-            }
-            var newList = new List<K>();
-            foreach (K k in list)
-            {
-                newList.Add(k);
-            }
-            return newList.ToArray();
-        }
+		/// <summary>
+		/// 不返回内部的list,copy一份出来
+		/// </summary>
+		/// <param name="t"></param>
+		/// <returns></returns>
+		public K[] GetAll(T t)
+		{
+			List<K> list;
+			this.dictionary.TryGetValue(t, out list);
+			if (list == null)
+			{
+				return new K[0];
+			}
+			var newList = new List<K>();
+			foreach (K k in list)
+			{
+				newList.Add(k);
+			}
+			return newList.ToArray();
+		}
 
-        /// <summary>
-        /// 返回内部的list
-        /// </summary>
-        /// <param name="t"></param>
-        /// <returns></returns>
-        public List<K> this[T t]
-        {
-            get
-            {
-                List<K> list;
-                this.dictionary.TryGetValue(t, out list);
-                return list;
-            }
-        }
+		/// <summary>
+		/// 返回内部的list
+		/// </summary>
+		/// <param name="t"></param>
+		/// <returns></returns>
+		public List<K> this[T t]
+		{
+			get
+			{
+				List<K> list;
+				this.dictionary.TryGetValue(t, out list);
+				return list;
+			}
+		}
 
-        public K GetOne(T t)
-        {
-            List<K> list;
-            this.dictionary.TryGetValue(t, out list);
-            if ((list != null) && (list.Count > 0))
-            {
-                return list[0];
-            }
-            return default(K);
-        }
+		public K GetOne(T t)
+		{
+			List<K> list;
+			this.dictionary.TryGetValue(t, out list);
+			if ((list != null) && (list.Count > 0))
+			{
+				return list[0];
+			}
+			return default(K);
+		}
 
-        public bool Contains(T t, K k)
-        {
-            List<K> list;
-            this.dictionary.TryGetValue(t, out list);
-            if (list == null)
-            {
-                return false;
-            }
-            return list.Contains(k);
-        }
-    }
+		public bool Contains(T t, K k)
+		{
+			List<K> list;
+			this.dictionary.TryGetValue(t, out list);
+			if (list == null)
+			{
+				return false;
+			}
+			return list.Contains(k);
+		}
+	}
 }

+ 97 - 98
CSharp/Platform/Common/Base/Object.cs

@@ -6,116 +6,115 @@ using MongoDB.Bson.Serialization.Attributes;
 
 namespace Common.Base
 {
-    public abstract class Object: ISupportInitialize
-    {
-        [BsonId]
-        public ObjectId Id { get; protected set; }
+	public abstract class Object: ISupportInitialize
+	{
+		[BsonId]
+		public ObjectId Id { get; protected set; }
 
-        [BsonElement]
-        [BsonIgnoreIfNull]
-        private Dictionary<string, object> values;
+		[BsonElement, BsonIgnoreIfNull]
+		private Dictionary<string, object> values;
 
-        protected Object()
-        {
-            this.Id = ObjectId.GenerateNewId();
-        }
+		protected Object()
+		{
+			this.Id = ObjectId.GenerateNewId();
+		}
 
-        protected Object(ObjectId id)
-        {
-            this.Id = id;
-        }
+		protected Object(ObjectId id)
+		{
+			this.Id = id;
+		}
 
-        public virtual void BeginInit()
-        {
-            if (this.values == null)
-            {
-                this.values = new Dictionary<string, object>();
-            }
-        }
+		public virtual void BeginInit()
+		{
+			if (this.values == null)
+			{
+				this.values = new Dictionary<string, object>();
+			}
+		}
 
-        public virtual void EndInit()
-        {
-            if (this.values.Count == 0)
-            {
-                this.values = null;
-            }
-        }
+		public virtual void EndInit()
+		{
+			if (this.values.Count == 0)
+			{
+				this.values = null;
+			}
+		}
 
-        public object this[string key]
-        {
-            get
-            {
-                return this.values[key];
-            }
-            set
-            {
-                if (this.values == null)
-                {
-                    this.values = new Dictionary<string, object>();
-                }
-                this.values[key] = value;
-            }
-        }
+		public object this[string key]
+		{
+			get
+			{
+				return this.values[key];
+			}
+			set
+			{
+				if (this.values == null)
+				{
+					this.values = new Dictionary<string, object>();
+				}
+				this.values[key] = value;
+			}
+		}
 
-        public T Get<T>(string key)
-        {
-            if (!this.values.ContainsKey(key))
-            {
-                return default(T);
-            }
-            return (T) this.values[key];
-        }
+		public T Get<T>(string key)
+		{
+			if (!this.values.ContainsKey(key))
+			{
+				return default(T);
+			}
+			return (T) this.values[key];
+		}
 
-        public T Get<T>()
-        {
-            return this.Get<T>(typeof (T).Name);
-        }
+		public T Get<T>()
+		{
+			return this.Get<T>(typeof (T).Name);
+		}
 
-        public void Set(string key, object obj)
-        {
-            if (this.values == null)
-            {
-                this.values = new Dictionary<string, object>();
-            }
-            this.values[key] = obj;
-        }
+		public void Set(string key, object obj)
+		{
+			if (this.values == null)
+			{
+				this.values = new Dictionary<string, object>();
+			}
+			this.values[key] = obj;
+		}
 
-        public void Set<T>(T obj)
-        {
-            if (this.values == null)
-            {
-                this.values = new Dictionary<string, object>();
-            }
-            this.values[typeof (T).Name] = obj;
-        }
+		public void Set<T>(T obj)
+		{
+			if (this.values == null)
+			{
+				this.values = new Dictionary<string, object>();
+			}
+			this.values[typeof (T).Name] = obj;
+		}
 
-        public bool ContainKey(string key)
-        {
-            return this.values.ContainsKey(key);
-        }
+		public bool ContainKey(string key)
+		{
+			return this.values.ContainsKey(key);
+		}
 
-        public bool Remove(string key)
-        {
-            bool ret = this.values.Remove(key);
-            if (this.values.Count == 0)
-            {
-                this.values = null;
-            }
-            return ret;
-        }
+		public bool Remove(string key)
+		{
+			bool ret = this.values.Remove(key);
+			if (this.values.Count == 0)
+			{
+				this.values = null;
+			}
+			return ret;
+		}
 
-        public void Add(string key, object value)
-        {
-            if (this.values == null)
-            {
-                this.values = new Dictionary<string, object>();
-            }
-            this.values.Add(key, value);
-        }
+		public void Add(string key, object value)
+		{
+			if (this.values == null)
+			{
+				this.values = new Dictionary<string, object>();
+			}
+			this.values.Add(key, value);
+		}
 
-        public IEnumerator GetEnumerator()
-        {
-            return this.values.GetEnumerator();
-        }
-    }
+		public IEnumerator GetEnumerator()
+		{
+			return this.values.GetEnumerator();
+		}
+	}
 }

+ 47 - 47
CSharp/Platform/Common/Config/ACategory.cs

@@ -6,51 +6,51 @@ using Common.Helper;
 
 namespace Common.Config
 {
-    public abstract class ACategory<T>: ICategory where T : AConfig
-    {
-        protected Dictionary<int, T> dict;
-
-        public virtual void BeginInit()
-        {
-            dict = new Dictionary<int, T>();
-
-            string path = Path.Combine(@"../../Config/", typeof(T).Name);
-
-            if (!Directory.Exists(path))
-            {
-                throw new Exception(string.Format("not found config path: {0}", path));
-            }
-
-            foreach (var file in Directory.GetFiles(path))
-            {
-                var t = MongoHelper.FromJson<T>(File.ReadAllText(file));
-                this.dict.Add(t.Id, t);
-            }
-        }
-
-        public Type ConfigType
-        {
-            get
-            {
-                return typeof (T);
-            }
-        }
-
-        public virtual void EndInit()
-        {
-        }
-
-        public T this[int type]
-        {
-            get
-            {
-                return this.dict[type];
-            }
-        }
-
-        public T[] GetAll()
-        {
-            return this.dict.Values.ToArray();
-        }
-    }
+	public abstract class ACategory<T>: ICategory where T : AConfig
+	{
+		protected Dictionary<int, T> dict;
+
+		public virtual void BeginInit()
+		{
+			this.dict = new Dictionary<int, T>();
+
+			string path = Path.Combine(@"../../Config/", typeof (T).Name);
+
+			if (!Directory.Exists(path))
+			{
+				throw new Exception(string.Format("not found config path: {0}", path));
+			}
+
+			foreach (var file in Directory.GetFiles(path))
+			{
+				var t = MongoHelper.FromJson<T>(File.ReadAllText(file));
+				this.dict.Add(t.Id, t);
+			}
+		}
+
+		public Type ConfigType
+		{
+			get
+			{
+				return typeof (T);
+			}
+		}
+
+		public virtual void EndInit()
+		{
+		}
+
+		public T this[int type]
+		{
+			get
+			{
+				return this.dict[type];
+			}
+		}
+
+		public T[] GetAll()
+		{
+			return this.dict.Values.ToArray();
+		}
+	}
 }

+ 11 - 11
CSharp/Platform/Common/Config/AConfig.cs

@@ -3,17 +3,17 @@ using MongoDB.Bson.Serialization.Attributes;
 
 namespace Common.Config
 {
-    public abstract class AConfig : ISupportInitialize
-    {
-        [BsonId]
-        public int Id { get; set; }
+	public abstract class AConfig: ISupportInitialize
+	{
+		[BsonId]
+		public int Id { get; set; }
 
-        public virtual void BeginInit()
-        {
-        }
+		public virtual void BeginInit()
+		{
+		}
 
-        public virtual void EndInit()
-        {
-        }
-    }
+		public virtual void EndInit()
+		{
+		}
+	}
 }

+ 4 - 4
CSharp/Platform/Common/Config/ConfigAttribute.cs

@@ -2,8 +2,8 @@
 
 namespace Common.Config
 {
-    [AttributeUsage(AttributeTargets.Class)]
-    public class ConfigAttribute: Attribute
-    {
-    }
+	[AttributeUsage(AttributeTargets.Class)]
+	public class ConfigAttribute: Attribute
+	{
+	}
 }

+ 4 - 4
CSharp/Platform/Common/Config/ICategory.cs

@@ -3,8 +3,8 @@ using System.ComponentModel;
 
 namespace Common.Config
 {
-    public interface ICategory: ISupportInitialize
-    {
-        Type ConfigType { get; }
-    }
+	public interface ICategory: ISupportInitialize
+	{
+		Type ConfigType { get; }
+	}
 }

+ 9 - 9
CSharp/Platform/Common/Event/AEventAttribute.cs

@@ -2,14 +2,14 @@
 
 namespace Common.Event
 {
-    [AttributeUsage(AttributeTargets.Class)]
-    public abstract class AEventAttribute : Attribute
-    {
-        public int Type { get; private set; }
+	[AttributeUsage(AttributeTargets.Class)]
+	public abstract class AEventAttribute: Attribute
+	{
+		public int Type { get; private set; }
 
-        protected AEventAttribute(int type)
-        {
-            this.Type = type;
-        }
-    }
+		protected AEventAttribute(int type)
+		{
+			this.Type = type;
+		}
+	}
 }

+ 3 - 3
CSharp/Platform/Common/Event/Env.cs

@@ -2,7 +2,7 @@
 
 namespace Common.Event
 {
-    public class Env: Object
-    {
-    }
+	public class Env: Object
+	{
+	}
 }

+ 4 - 4
CSharp/Platform/Common/Event/IEvent.cs

@@ -1,7 +1,7 @@
 namespace Common.Event
 {
-    public interface IEvent
-    {
-        void Run(Env env);
-    }
+	public interface IEvent
+	{
+		void Run(Env env);
+	}
 }

+ 67 - 67
CSharp/Platform/Common/Helper/BigIntegerHelper.cs

@@ -3,78 +3,78 @@ using System.Numerics;
 
 namespace Common.Helper
 {
-    public static class BigIntegerHelper
-    {
-        public static BigInteger RandBigInteger(int byteNum)
-        {
-            var bigIntegerBytes = new byte[byteNum];
-            var random = new Random();
-            random.NextBytes(bigIntegerBytes);
-            var bigInteger = new BigInteger(bigIntegerBytes);
-            return bigInteger;
-        }
+	public static class BigIntegerHelper
+	{
+		public static BigInteger RandBigInteger(int byteNum)
+		{
+			var bigIntegerBytes = new byte[byteNum];
+			var random = new Random();
+			random.NextBytes(bigIntegerBytes);
+			var bigInteger = new BigInteger(bigIntegerBytes);
+			return bigInteger;
+		}
 
-        public static BigInteger RandUnsignedBigInteger(int byteNum)
-        {
-            var bigIntegerBytes = new byte[byteNum];
-            var random = new Random();
-            random.NextBytes(bigIntegerBytes);
-            //bigIntegerBytes = "C6DFEDA1EAAC7417A191EE5EC6062CE9546614".HexToBytes().Reverse();
+		public static BigInteger RandUnsignedBigInteger(int byteNum)
+		{
+			var bigIntegerBytes = new byte[byteNum];
+			var random = new Random();
+			random.NextBytes(bigIntegerBytes);
+			//bigIntegerBytes = "C6DFEDA1EAAC7417A191EE5EC6062CE9546614".HexToBytes().Reverse();
 
-            return bigIntegerBytes.ToUBigInteger();
-        }
+			return bigIntegerBytes.ToUBigInteger();
+		}
 
-        public static BigInteger ToBigInteger(this byte[] bytes)
-        {
-            return new BigInteger(bytes);
-        }
+		public static BigInteger ToBigInteger(this byte[] bytes)
+		{
+			return new BigInteger(bytes);
+		}
 
-        public static BigInteger ToUBigInteger(this byte[] bytes)
-        {
-            var dst = new byte[bytes.Length + 1];
-            Array.Copy(bytes, dst, bytes.Length);
-            return new BigInteger(dst);
-        }
+		public static BigInteger ToUBigInteger(this byte[] bytes)
+		{
+			var dst = new byte[bytes.Length + 1];
+			Array.Copy(bytes, dst, bytes.Length);
+			return new BigInteger(dst);
+		}
 
-        public static byte[] ToUBigIntegerArray(this BigInteger bigInteger)
-        {
-            var result = bigInteger.ToByteArray();
-            if (result[result.Length - 1] == 0 && (result.Length % 0x10) != 0)
-            {
-                Array.Resize(ref result, result.Length - 1);
-            }
-            return result;
-        }
+		public static byte[] ToUBigIntegerArray(this BigInteger bigInteger)
+		{
+			var result = bigInteger.ToByteArray();
+			if (result[result.Length - 1] == 0 && (result.Length % 0x10) != 0)
+			{
+				Array.Resize(ref result, result.Length - 1);
+			}
+			return result;
+		}
 
-        public static byte[] ToUBigIntegerArray(this BigInteger bigInteger, int length)
-        {
-            var result = bigInteger.ToByteArray();
-            if (result[result.Length - 1] == 0 && (result.Length % 0x10) != 0)
-            {
-                Array.Resize(ref result, result.Length - 1);
-            }
-            if (length > result.Length)
-            {
-                Array.Resize(ref result, length);
-            }
-            return result;
-        }
+		public static byte[] ToUBigIntegerArray(this BigInteger bigInteger, int length)
+		{
+			var result = bigInteger.ToByteArray();
+			if (result[result.Length - 1] == 0 && (result.Length % 0x10) != 0)
+			{
+				Array.Resize(ref result, result.Length - 1);
+			}
+			if (length > result.Length)
+			{
+				Array.Resize(ref result, length);
+			}
+			return result;
+		}
 
-        /// <summary>
-        /// 返回非负值
-        /// </summary>
-        /// <param name="value"></param>
-        /// <param name="exponent"></param>
-        /// <param name="modulus"></param>
-        /// <returns></returns>
-        public static BigInteger UModPow(BigInteger value, BigInteger exponent, BigInteger modulus)
-        {
-            BigInteger result = BigInteger.ModPow(value, exponent, modulus);
-            if (result < 0)
-            {
-                result += modulus;
-            }
-            return result;
-        }
-    }
+		/// <summary>
+		/// 返回非负值
+		/// </summary>
+		/// <param name="value"></param>
+		/// <param name="exponent"></param>
+		/// <param name="modulus"></param>
+		/// <returns></returns>
+		public static BigInteger UModPow(BigInteger value, BigInteger exponent, BigInteger modulus)
+		{
+			BigInteger result = BigInteger.ModPow(value, exponent, modulus);
+			if (result < 0)
+			{
+				result += modulus;
+			}
+			return result;
+		}
+	}
 }

+ 25 - 25
CSharp/Platform/Common/Helper/ByteHelper.cs

@@ -4,32 +4,32 @@ using System.Text;
 
 namespace Common.Helper
 {
-    public static class ByteHelper
-    {
-        public static string ToHex(this byte b)
-        {
-            return b.ToString("X2");
-        }
+	public static class ByteHelper
+	{
+		public static string ToHex(this byte b)
+		{
+			return b.ToString("X2");
+		}
 
-        public static string ToHex(this IEnumerable<byte> bytes)
-        {
-            var stringBuilder = new StringBuilder();
-            foreach (byte b in bytes)
-            {
-                stringBuilder.Append(b.ToString("X2"));
-            }
-            return stringBuilder.ToString();
-        }
+		public static string ToHex(this IEnumerable<byte> bytes)
+		{
+			var stringBuilder = new StringBuilder();
+			foreach (byte b in bytes)
+			{
+				stringBuilder.Append(b.ToString("X2"));
+			}
+			return stringBuilder.ToString();
+		}
 
-        public static string ToStr(this byte[] bytes)
-        {
-            return Encoding.Default.GetString(bytes);
-        }
+		public static string ToStr(this byte[] bytes)
+		{
+			return Encoding.Default.GetString(bytes);
+		}
 
-        public static byte[] Reverse(this byte[] bytes)
-        {
-            Array.Reverse(bytes);
-            return bytes;
-        }
-    }
+		public static byte[] Reverse(this byte[] bytes)
+		{
+			Array.Reverse(bytes);
+			return bytes;
+		}
+	}
 }

+ 17 - 17
CSharp/Platform/Common/Helper/EnumHelper.cs

@@ -2,21 +2,21 @@
 
 namespace Common.Helper
 {
-    public static class EnumHelper
-    {
-        public static int EnumIndex<T>(int value)
-        {
-            int i = 0;
-            foreach (var v in Enum.GetValues(typeof (T)))
-            {
-                if ((int) v != value)
-                {
-                    ++i;
-                    continue;
-                }
-                return i;
-            }
-            return -1;
-        }
-    }
+	public static class EnumHelper
+	{
+		public static int EnumIndex<T>(int value)
+		{
+			int i = 0;
+			foreach (var v in Enum.GetValues(typeof (T)))
+			{
+				if ((int) v != value)
+				{
+					++i;
+					continue;
+				}
+				return i;
+			}
+			return -1;
+		}
+	}
 }

+ 13 - 13
CSharp/Platform/Common/Helper/LoaderHelper.cs

@@ -4,17 +4,17 @@ using System.Reflection;
 
 namespace Common.Helper
 {
-    public static class LoaderHelper
-    {
-        public static Assembly Load(string path)
-        {
-            if (!File.Exists(path))
-            {
-                throw new Exception(string.Format("not found path, path: {0}", path));
-            }
-            byte[] buffer = File.ReadAllBytes(path);
-            var assembly = Assembly.Load(buffer);
-            return assembly;
-        }
-    }
+	public static class LoaderHelper
+	{
+		public static Assembly Load(string path)
+		{
+			if (!File.Exists(path))
+			{
+				throw new Exception(string.Format("not found path, path: {0}", path));
+			}
+			byte[] buffer = File.ReadAllBytes(path);
+			var assembly = Assembly.Load(buffer);
+			return assembly;
+		}
+	}
 }

+ 27 - 27
CSharp/Platform/Common/Helper/MongoHelper.cs

@@ -5,36 +5,36 @@ using MongoDB.Bson.Serialization;
 
 namespace Common.Helper
 {
-    public static class MongoHelper
-    {
-        public static string ToJson(object obj)
-        {
-            return obj.ToJson();
-        }
+	public static class MongoHelper
+	{
+		public static string ToJson(object obj)
+		{
+			return obj.ToJson();
+		}
 
-        public static string ToJson(object obj, JsonWriterSettings settings)
-        {
-            return obj.ToJson(settings);
-        }
+		public static string ToJson(object obj, JsonWriterSettings settings)
+		{
+			return obj.ToJson(settings);
+		}
 
-        public static T FromJson<T>(string str)
-        {
-            return BsonSerializer.Deserialize<T>(str);
-        }
+		public static T FromJson<T>(string str)
+		{
+			return BsonSerializer.Deserialize<T>(str);
+		}
 
-        public static byte[] ToBson(object obj)
-        {
-            return obj.ToBson();
-        }
+		public static byte[] ToBson(object obj)
+		{
+			return obj.ToBson();
+		}
 
-        public static T FromBson<T>(byte[] bytes)
-        {
-            return BsonSerializer.Deserialize<T>(bytes);
-        }
+		public static T FromBson<T>(byte[] bytes)
+		{
+			return BsonSerializer.Deserialize<T>(bytes);
+		}
 
-        public static object FromBson(byte[] bytes, Type type)
-        {
-            return BsonSerializer.Deserialize(bytes, type);
-        }
-    }
+		public static object FromBson(byte[] bytes, Type type)
+		{
+			return BsonSerializer.Deserialize(bytes, type);
+		}
+	}
 }

+ 33 - 33
CSharp/Platform/Common/Helper/ProtobufHelper.cs

@@ -4,39 +4,39 @@ using ProtoBuf;
 
 namespace Common.Helper
 {
-    public static class ProtobufHelper
-    {
-        public static byte[] ToBytes<T>(T message)
-        {
-            var ms = new MemoryStream();
-            Serializer.Serialize(ms, message);
-            return ms.ToArray();
-        }
+	public static class ProtobufHelper
+	{
+		public static byte[] ToBytes<T>(T message)
+		{
+			var ms = new MemoryStream();
+			Serializer.Serialize(ms, message);
+			return ms.ToArray();
+		}
 
-        public static T FromBytes<T>(byte[] bytes)
-        {
-            var ms = new MemoryStream(bytes, 0, bytes.Length);
-            T t = Serializer.Deserialize<T>(ms);
-            var iSupportInitialize = t as ISupportInitialize;
-            if (iSupportInitialize == null)
-            {
-                return t;
-            }
-            iSupportInitialize.EndInit();
-            return t;
-        }
+		public static T FromBytes<T>(byte[] bytes)
+		{
+			var ms = new MemoryStream(bytes, 0, bytes.Length);
+			T t = Serializer.Deserialize<T>(ms);
+			var iSupportInitialize = t as ISupportInitialize;
+			if (iSupportInitialize == null)
+			{
+				return t;
+			}
+			iSupportInitialize.EndInit();
+			return t;
+		}
 
-        public static T FromBytes<T>(byte[] bytes, int index, int length)
-        {
-            var ms = new MemoryStream(bytes, index, length);
-            T t = Serializer.Deserialize<T>(ms);
-            var iSupportInitialize = t as ISupportInitialize;
-            if (iSupportInitialize == null)
-            {
-                return t;
-            }
-            iSupportInitialize.EndInit();
-            return t;
-        }
-    }
+		public static T FromBytes<T>(byte[] bytes, int index, int length)
+		{
+			var ms = new MemoryStream(bytes, index, length);
+			T t = Serializer.Deserialize<T>(ms);
+			var iSupportInitialize = t as ISupportInitialize;
+			if (iSupportInitialize == null)
+			{
+				return t;
+			}
+			iSupportInitialize.EndInit();
+			return t;
+		}
+	}
 }

+ 10 - 10
CSharp/Platform/Common/Helper/RandomHelper.cs

@@ -2,14 +2,14 @@
 
 namespace Common.Helper
 {
-    public static class RandomHelper
-    {
-        public static UInt64 RandUInt64()
-        {
-            var bytes = new byte[8];
-            var random = new Random();
-            random.NextBytes(bytes);
-            return BitConverter.ToUInt64(bytes, 0);
-        }
-    }
+	public static class RandomHelper
+	{
+		public static UInt64 RandUInt64()
+		{
+			var bytes = new byte[8];
+			var random = new Random();
+			random.NextBytes(bytes);
+			return BitConverter.ToUInt64(bytes, 0);
+		}
+	}
 }

+ 30 - 31
CSharp/Platform/Common/Helper/StringHelper.cs

@@ -5,38 +5,37 @@ using System.Text;
 
 namespace Common.Helper
 {
-    public static class StringHelper
-    {
-        public static IEnumerable<byte> ToBytes(this string str)
-        {
-            byte[] byteArray = Encoding.Default.GetBytes(str);
-            return byteArray;
-        }
+	public static class StringHelper
+	{
+		public static IEnumerable<byte> ToBytes(this string str)
+		{
+			byte[] byteArray = Encoding.Default.GetBytes(str);
+			return byteArray;
+		}
 
-        public static byte[] ToByteArray(this string str)
-        {
-            byte[] byteArray = Encoding.Default.GetBytes(str);
-            return byteArray;
-        }
+		public static byte[] ToByteArray(this string str)
+		{
+			byte[] byteArray = Encoding.Default.GetBytes(str);
+			return byteArray;
+		}
 
-        public static byte[] HexToBytes(this string hexString)
-        {
-            if (hexString.Length % 2 != 0)
-            {
-                throw new ArgumentException(String.Format(CultureInfo.InvariantCulture,
-                        "The binary key cannot have an odd number of digits: {0}", hexString));
-            }
+		public static byte[] HexToBytes(this string hexString)
+		{
+			if (hexString.Length % 2 != 0)
+			{
+				throw new ArgumentException(String.Format(CultureInfo.InvariantCulture,
+						"The binary key cannot have an odd number of digits: {0}", hexString));
+			}
 
-            var hexAsBytes = new byte[hexString.Length / 2];
-            for (int index = 0; index < hexAsBytes.Length; index++)
-            {
-                string byteValue = "";
-                byteValue += hexString[index * 2];
-                byteValue += hexString[index * 2 + 1];
-                hexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber,
-                        CultureInfo.InvariantCulture);
-            }
-            return hexAsBytes;
-        }
-    }
+			var hexAsBytes = new byte[hexString.Length / 2];
+			for (int index = 0; index < hexAsBytes.Length; index++)
+			{
+				string byteValue = "";
+				byteValue += hexString[index * 2];
+				byteValue += hexString[index * 2 + 1];
+				hexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
+			}
+			return hexAsBytes;
+		}
+	}
 }

+ 8 - 8
CSharp/Platform/Common/Helper/TimeHelper.cs

@@ -2,12 +2,12 @@
 
 namespace Common.Helper
 {
-    public static class TimeHelper
-    {
-        public static long Now()
-        {
-            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
-            return Convert.ToInt64((DateTime.UtcNow - epoch).TotalMilliseconds);
-        }
-    }
+	public static class TimeHelper
+	{
+		public static long Now()
+		{
+			var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
+			return Convert.ToInt64((DateTime.UtcNow - epoch).TotalMilliseconds);
+		}
+	}
 }

+ 32 - 32
CSharp/Platform/Common/Helper/XmlHelper.cs

@@ -6,37 +6,37 @@ using System.Xml.Serialization;
 
 namespace Common.Helper
 {
-    public static class XmlHelper
-    {
-        /// <summary>
-        /// 对象序列化成 XML String
-        /// </summary>
-        public static string XmlSerialize<T>(T obj)
-        {
-            string xmlString = string.Empty;
-            var xmlSerializer = new XmlSerializer(typeof (T));
-            using (var ms = new MemoryStream())
-            {
-                xmlSerializer.Serialize(ms, obj);
-                xmlString = Encoding.UTF8.GetString(ms.ToArray());
-            }
-            return xmlString;
-        }
+	public static class XmlHelper
+	{
+		/// <summary>
+		/// 对象序列化成 XML String
+		/// </summary>
+		public static string XmlSerialize<T>(T obj)
+		{
+			string xmlString = string.Empty;
+			var xmlSerializer = new XmlSerializer(typeof (T));
+			using (var ms = new MemoryStream())
+			{
+				xmlSerializer.Serialize(ms, obj);
+				xmlString = Encoding.UTF8.GetString(ms.ToArray());
+			}
+			return xmlString;
+		}
 
-        /// <summary>
-        /// XML String 反序列化成对象
-        /// </summary>
-        public static T XmlDeserialize<T>(string xmlString)
-        {
-            T t = default(T);
-            var xmlSerializer = new XmlSerializer(typeof (T));
-            Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString));
-            using (var xmlReader = XmlReader.Create(xmlStream))
-            {
-                Object obj = xmlSerializer.Deserialize(xmlReader);
-                t = (T) obj;
-            }
-            return t;
-        }
-    }
+		/// <summary>
+		/// XML String 反序列化成对象
+		/// </summary>
+		public static T XmlDeserialize<T>(string xmlString)
+		{
+			T t = default(T);
+			var xmlSerializer = new XmlSerializer(typeof (T));
+			Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString));
+			using (var xmlReader = XmlReader.Create(xmlStream))
+			{
+				Object obj = xmlSerializer.Deserialize(xmlReader);
+				t = (T) obj;
+			}
+			return t;
+		}
+	}
 }

+ 13 - 13
CSharp/Platform/Common/Hooks/Native.cs

@@ -3,20 +3,20 @@ using System.Runtime.InteropServices;
 
 namespace Common.Hooks
 {
-    [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode,
-            SetLastError = true)]
-    public delegate int DRecv(IntPtr handle, IntPtr buf, int count, int flag);
+	[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true
+			)]
+	public delegate int DRecv(IntPtr handle, IntPtr buf, int count, int flag);
 
-    [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode,
-            SetLastError = true)]
-    public delegate int DSend(IntPtr handle, IntPtr buf, int count, int flag);
+	[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true
+			)]
+	public delegate int DSend(IntPtr handle, IntPtr buf, int count, int flag);
 
-    public static class Native
-    {
-        [DllImport("Ws2_32.dll", EntryPoint = "recv")]
-        public static extern int Recv(IntPtr handle, IntPtr buf, int count, int flag);
+	public static class Native
+	{
+		[DllImport("Ws2_32.dll", EntryPoint = "recv")]
+		public static extern int Recv(IntPtr handle, IntPtr buf, int count, int flag);
 
-        [DllImport("Ws2_32.dll", EntryPoint = "send")]
-        public static extern int Send(IntPtr handle, IntPtr buf, int count, int flag);
-    }
+		[DllImport("Ws2_32.dll", EntryPoint = "send")]
+		public static extern int Send(IntPtr handle, IntPtr buf, int count, int flag);
+	}
 }

+ 34 - 34
CSharp/Platform/Common/Logger/ALogDecorater.cs

@@ -1,40 +1,40 @@
 namespace Common.Logger
 {
-    public abstract class ALogDecorater
-    {
-        protected const string SEP = " ";
-        private int level;
-        protected readonly ALogDecorater decorater;
+	public abstract class ALogDecorater
+	{
+		protected const string SEP = " ";
+		private int level;
+		protected readonly ALogDecorater decorater;
 
-        protected ALogDecorater(ALogDecorater decorater = null)
-        {
-            this.decorater = decorater;
-            this.Level = 0;
-        }
+		protected ALogDecorater(ALogDecorater decorater = null)
+		{
+			this.decorater = decorater;
+			this.Level = 0;
+		}
 
-        protected int Level
-        {
-            get
-            {
-                return this.level;
-            }
-            set
-            {
-                this.level = value;
-                if (this.decorater != null)
-                {
-                    this.decorater.Level = value + 1;
-                }
-            }
-        }
+		protected int Level
+		{
+			get
+			{
+				return this.level;
+			}
+			set
+			{
+				this.level = value;
+				if (this.decorater != null)
+				{
+					this.decorater.Level = value + 1;
+				}
+			}
+		}
 
-        public virtual string Decorate(string message)
-        {
-            if (this.decorater == null)
-            {
-                return message;
-            }
-            return this.decorater.Decorate(message);
-        }
-    }
+		public virtual string Decorate(string message)
+		{
+			if (this.decorater == null)
+			{
+				return message;
+			}
+			return this.decorater.Decorate(message);
+		}
+	}
 }

+ 5 - 5
CSharp/Platform/Common/Logger/ILog.cs

@@ -1,8 +1,8 @@
 namespace Common.Logger
 {
-    public interface ILog
-    {
-        void Trace(string message);
-        void Debug(string message);
-    }
+	public interface ILog
+	{
+		void Trace(string message);
+		void Debug(string message);
+	}
 }

+ 27 - 27
CSharp/Platform/Common/Logger/Log.cs

@@ -1,35 +1,35 @@
 namespace Common.Logger
 {
-    public static class Log
-    {
-        private static readonly ILog globalLog = new NLogAdapter(new StackInfoDecorater());
+	public static class Log
+	{
+		private static readonly ILog globalLog = new NLogAdapter(new StackInfoDecorater());
 
-        public static ILog GlobalLog
-        {
-            get
-            {
-                return globalLog;
-            }
-        }
+		public static ILog GlobalLog
+		{
+			get
+			{
+				return globalLog;
+			}
+		}
 
-        public static void Trace(string message)
-        {
-            GlobalLog.Trace(message);
-        }
+		public static void Trace(string message)
+		{
+			GlobalLog.Trace(message);
+		}
 
-        public static void Trace(string format, params object[] args)
-        {
-            GlobalLog.Trace(string.Format(format, args));
-        }
+		public static void Trace(string format, params object[] args)
+		{
+			GlobalLog.Trace(string.Format(format, args));
+		}
 
-        public static void Debug(string format)
-        {
-            GlobalLog.Debug(format);
-        }
+		public static void Debug(string format)
+		{
+			GlobalLog.Debug(format);
+		}
 
-        public static void Debug(string format, params object[] args)
-        {
-            GlobalLog.Debug(string.Format(format, args));
-        }
-    }
+		public static void Debug(string format, params object[] args)
+		{
+			GlobalLog.Debug(string.Format(format, args));
+		}
+	}
 }

+ 15 - 15
CSharp/Platform/Common/Logger/NLogAdapter.cs

@@ -2,22 +2,22 @@
 
 namespace Common.Logger
 {
-    public class NLogAdapter: ALogDecorater, ILog
-    {
-        private readonly NLog.Logger logger = LogManager.GetCurrentClassLogger();
+	public class NLogAdapter: ALogDecorater, ILog
+	{
+		private readonly NLog.Logger logger = LogManager.GetCurrentClassLogger();
 
-        public NLogAdapter(ALogDecorater decorater = null): base(decorater)
-        {
-        }
+		public NLogAdapter(ALogDecorater decorater = null): base(decorater)
+		{
+		}
 
-        public void Trace(string message)
-        {
-            this.logger.Trace(this.Decorate(SEP + message));
-        }
+		public void Trace(string message)
+		{
+			this.logger.Trace(this.Decorate(SEP + message));
+		}
 
-        public void Debug(string message)
-        {
-            this.logger.Debug(this.Decorate(SEP + message));
-        }
-    }
+		public void Debug(string message)
+		{
+			this.logger.Debug(this.Decorate(SEP + message));
+		}
+	}
 }

+ 35 - 35
CSharp/Platform/Common/Logger/StackInfoDecorater.cs

@@ -3,45 +3,45 @@ using System.IO;
 
 namespace Common.Logger
 {
-    internal class StackInfoDecorater: ALogDecorater
-    {
-        public StackInfoDecorater(ALogDecorater decorater = null): base(decorater)
-        {
-            this.FileName = true;
-            this.FileLineNumber = true;
-        }
+	internal class StackInfoDecorater: ALogDecorater
+	{
+		public StackInfoDecorater(ALogDecorater decorater = null): base(decorater)
+		{
+			this.FileName = true;
+			this.FileLineNumber = true;
+		}
 
-        public bool FileName { get; set; }
+		public bool FileName { get; set; }
 
-        public bool FileLineNumber { get; set; }
+		public bool FileLineNumber { get; set; }
 
-        public override string Decorate(string message)
-        {
-            if (this.decorater != null)
-            {
-                message = this.decorater.Decorate(message);
-            }
+		public override string Decorate(string message)
+		{
+			if (this.decorater != null)
+			{
+				message = this.decorater.Decorate(message);
+			}
 
-            if (!this.FileLineNumber && !this.FileName)
-            {
-                return message;
-            }
+			if (!this.FileLineNumber && !this.FileName)
+			{
+				return message;
+			}
 
-            string extraInfo = "";
-            var stackTrace = new StackTrace(true);
-            var frame = stackTrace.GetFrame(this.Level + 3);
+			string extraInfo = "";
+			var stackTrace = new StackTrace(true);
+			var frame = stackTrace.GetFrame(this.Level + 3);
 
-            if (this.FileName)
-            {
-                var fileName = Path.GetFileName(frame.GetFileName());
-                extraInfo += fileName + " ";
-            }
-            if (this.FileLineNumber)
-            {
-                var fileLineNumber = frame.GetFileLineNumber();
-                extraInfo += fileLineNumber + " ";
-            }
-            return extraInfo + message;
-        }
-    }
+			if (this.FileName)
+			{
+				var fileName = Path.GetFileName(frame.GetFileName());
+				extraInfo += fileName + " ";
+			}
+			if (this.FileLineNumber)
+			{
+				var fileLineNumber = frame.GetFileLineNumber();
+				extraInfo += fileLineNumber + " ";
+			}
+			return extraInfo + message;
+		}
+	}
 }

+ 52 - 52
CSharp/Platform/ENet/Address.cs

@@ -3,60 +3,60 @@ using System.Net;
 
 namespace ENet
 {
-    public struct Address
-    {
-        private uint ip;
-        private ushort port;
+	public struct Address
+	{
+		private uint ip;
+		private ushort port;
 
-        public uint Ip
-        {
-            get
-            {
-                return this.ip;
-            }
-            set
-            {
-                this.ip = value;
-            }
-        }
+		public uint Ip
+		{
+			get
+			{
+				return this.ip;
+			}
+			set
+			{
+				this.ip = value;
+			}
+		}
 
-        public ushort Port
-        {
-            get
-            {
-                return this.port;
-            }
-            set
-            {
-                this.port = value;
-            }
-        }
+		public ushort Port
+		{
+			get
+			{
+				return this.port;
+			}
+			set
+			{
+				this.port = value;
+			}
+		}
 
-        public string HostName
-        {
-            get
-            {
-                var hostInfo = Dns.GetHostEntry(new IPAddress(this.ip));
-                return hostInfo.HostName;
-            }
-            set
-            {
-                IPAddress[] addresslist = Dns.GetHostAddresses(value);
-                foreach (IPAddress address in addresslist)
-                {
-                    this.ip = BitConverter.ToUInt32(address.GetAddressBytes(), 0);
-                    return;
-                }
-            }
-        }
+		public string HostName
+		{
+			get
+			{
+				var hostInfo = Dns.GetHostEntry(new IPAddress(this.ip));
+				return hostInfo.HostName;
+			}
+			set
+			{
+				IPAddress[] addresslist = Dns.GetHostAddresses(value);
+				foreach (IPAddress address in addresslist)
+				{
+					this.ip = BitConverter.ToUInt32(address.GetAddressBytes(), 0);
+					return;
+				}
+			}
+		}
 
-        public ENetAddress Struct
-        {
-            get
-            {
-                var address = new ENetAddress { Host = this.ip, Port = this.port };
-                return address;
-            }
-        }
-    }
+		public ENetAddress Struct
+		{
+			get
+			{
+				var address = new ENetAddress { Host = this.ip, Port = this.port };
+				return address;
+			}
+		}
+	}
 }

+ 53 - 53
CSharp/Platform/ENet/EEvent.cs

@@ -2,64 +2,64 @@
 
 namespace ENet
 {
-    public enum EventState
-    {
-        CONNECTED = 0,
-        DISCONNECTED = 1,
-    }
+	public enum EventState
+	{
+		CONNECTED = 0,
+		DISCONNECTED = 1,
+	}
 
-    public class EEvent
-    {
-        private readonly ENetEvent ev;
-        private EventState peerState = EventState.CONNECTED;
+	public class EEvent
+	{
+		private readonly ENetEvent ev;
+		private EventState peerState = EventState.CONNECTED;
 
-        public EEvent(ENetEvent ev)
-        {
-            this.ev = ev;
-        }
+		public EEvent(ENetEvent ev)
+		{
+			this.ev = ev;
+		}
 
-        public EventState EventState
-        {
-            get
-            {
-                return this.peerState;
-            }
-            set
-            {
-                this.peerState = value;
-            }
-        }
+		public EventState EventState
+		{
+			get
+			{
+				return this.peerState;
+			}
+			set
+			{
+				this.peerState = value;
+			}
+		}
 
-        public ENetEvent Ev
-        {
-            get
-            {
-                return this.ev;
-            }
-        }
+		public ENetEvent Ev
+		{
+			get
+			{
+				return this.ev;
+			}
+		}
 
-        public IntPtr PacketPtr
-        {
-            get
-            {
-                return this.Ev.Packet;
-            }
-        }
+		public IntPtr PacketPtr
+		{
+			get
+			{
+				return this.Ev.Packet;
+			}
+		}
 
-        public IntPtr PeerPtr
-        {
-            get
-            {
-                return this.Ev.Peer;
-            }
-        }
+		public IntPtr PeerPtr
+		{
+			get
+			{
+				return this.Ev.Peer;
+			}
+		}
 
-        public EventType Type
-        {
-            get
-            {
-                return this.Ev.Type;
-            }
-        }
-    }
+		public EventType Type
+		{
+			get
+			{
+				return this.Ev.Type;
+			}
+		}
+	}
 }

+ 16 - 16
CSharp/Platform/ENet/EException.cs

@@ -3,23 +3,23 @@ using System.Runtime.Serialization;
 
 namespace ENet
 {
-    [Serializable]
-    public class EException: Exception
-    {
-        public EException()
-        {
-        }
+	[Serializable]
+	public class EException: Exception
+	{
+		public EException()
+		{
+		}
 
-        public EException(string message): base(message)
-        {
-        }
+		public EException(string message): base(message)
+		{
+		}
 
-        public EException(string message, Exception inner): base(message, inner)
-        {
-        }
+		public EException(string message, Exception inner): base(message, inner)
+		{
+		}
 
-        protected EException(SerializationInfo info, StreamingContext context)
-        {
-        }
-    }
+		protected EException(SerializationInfo info, StreamingContext context)
+		{
+		}
+	}
 }

+ 81 - 81
CSharp/Platform/ENet/EPacket.cs

@@ -3,95 +3,95 @@ using System.Runtime.InteropServices;
 
 namespace ENet
 {
-    internal sealed class EPacket: IDisposable
-    {
-        private IntPtr packet;
+	internal sealed class EPacket: IDisposable
+	{
+		private IntPtr packet;
 
-        public EPacket(IntPtr packet)
-        {
-            this.packet = packet;
-        }
+		public EPacket(IntPtr packet)
+		{
+			this.packet = packet;
+		}
 
-        public EPacket(byte[] data, PacketFlags flags = PacketFlags.None)
-        {
-            if (data == null)
-            {
-                throw new ArgumentNullException("data");
-            }
-            this.packet = NativeMethods.EnetPacketCreate(data, (uint) data.Length, flags);
-            if (this.packet == IntPtr.Zero)
-            {
-                throw new EException("Packet creation call failed");
-            }
-        }
+		public EPacket(byte[] data, PacketFlags flags = PacketFlags.None)
+		{
+			if (data == null)
+			{
+				throw new ArgumentNullException("data");
+			}
+			this.packet = NativeMethods.EnetPacketCreate(data, (uint) data.Length, flags);
+			if (this.packet == IntPtr.Zero)
+			{
+				throw new EException("Packet creation call failed");
+			}
+		}
 
-        ~EPacket()
-        {
-            this.Dispose(false);
-        }
+		~EPacket()
+		{
+			this.Dispose(false);
+		}
 
-        public void Dispose()
-        {
-            this.Dispose(true);
-            GC.SuppressFinalize(this);
-        }
+		public void Dispose()
+		{
+			this.Dispose(true);
+			GC.SuppressFinalize(this);
+		}
 
-        private void Dispose(bool disposing)
-        {
-            if (this.packet == IntPtr.Zero)
-            {
-                return;
-            }
+		private void Dispose(bool disposing)
+		{
+			if (this.packet == IntPtr.Zero)
+			{
+				return;
+			}
 
-            NativeMethods.EnetPacketDestroy(this.packet);
-            this.packet = IntPtr.Zero;
-        }
+			NativeMethods.EnetPacketDestroy(this.packet);
+			this.packet = IntPtr.Zero;
+		}
 
-        private ENetPacket Struct
-        {
-            get
-            {
-                return (ENetPacket) Marshal.PtrToStructure(this.packet, typeof (ENetPacket));
-            }
-            set
-            {
-                Marshal.StructureToPtr(value, this.packet, false);
-            }
-        }
+		private ENetPacket Struct
+		{
+			get
+			{
+				return (ENetPacket) Marshal.PtrToStructure(this.packet, typeof (ENetPacket));
+			}
+			set
+			{
+				Marshal.StructureToPtr(value, this.packet, false);
+			}
+		}
 
-        public IntPtr PacketPtr
-        {
-            get
-            {
-                return this.packet;
-            }
-            set
-            {
-                this.packet = value;
-            }
-        }
+		public IntPtr PacketPtr
+		{
+			get
+			{
+				return this.packet;
+			}
+			set
+			{
+				this.packet = value;
+			}
+		}
 
-        public uint Length
-        {
-            get
-            {
-                if (this.packet == IntPtr.Zero)
-                {
-                    return 0;
-                }
-                return this.Struct.DataLength;
-            }
-        }
+		public uint Length
+		{
+			get
+			{
+				if (this.packet == IntPtr.Zero)
+				{
+					return 0;
+				}
+				return this.Struct.DataLength;
+			}
+		}
 
-        public byte[] Bytes
-        {
-            get
-            {
-                var enetPacket = this.Struct;
-                var bytes = new byte[enetPacket.DataLength];
-                Marshal.Copy(enetPacket.Data, bytes, 0, (int) enetPacket.DataLength);
-                return bytes;
-            }
-        }
-    }
+		public byte[] Bytes
+		{
+			get
+			{
+				var enetPacket = this.Struct;
+				var bytes = new byte[enetPacket.DataLength];
+				Marshal.Copy(enetPacket.Data, bytes, 0, (int) enetPacket.DataLength);
+				return bytes;
+			}
+		}
+	}
 }

+ 304 - 308
CSharp/Platform/ENet/EService.cs

@@ -3,312 +3,308 @@ using System.Collections.Generic;
 
 namespace ENet
 {
-    public sealed class EService: IDisposable
-    {
-        static EService()
-        {
-            Library.Initialize();
-        }
-
-        private readonly PeersManager peersManager = new PeersManager();
-        private readonly LinkedList<EEvent> connEEvents = new LinkedList<EEvent>();
-
-        internal PeersManager PeersManager
-        {
-            get
-            {
-                return this.peersManager;
-            }
-        }
-
-        internal LinkedList<EEvent> ConnEEvents
-        {
-            get
-            {
-                return this.connEEvents;
-            }
-        }
-
-        private IntPtr host;
-        private bool isRunning = true;
-        private readonly object eventsLock = new object();
-        private Action events;
-
-        public EService(
-                string hostName, ushort port,
-                uint peerLimit = NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID, uint channelLimit = 0,
-                uint incomingBandwidth = 0, uint outgoingBandwidth = 0)
-        {
-            if (peerLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID)
-            {
-                throw new ArgumentOutOfRangeException(string.Format("peerLimit: {0}", peerLimit));
-            }
-
-            if (channelLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
-            {
-                throw new ArgumentOutOfRangeException(string.Format("channelLimit: {0}",
-                        channelLimit));
-            }
-
-            var address = new Address { HostName = hostName, Port = port };
-            ENetAddress nativeAddress = address.Struct;
-            this.host = NativeMethods.EnetHostCreate(ref nativeAddress, peerLimit, channelLimit,
-                    incomingBandwidth, outgoingBandwidth);
-
-            if (this.host == IntPtr.Zero)
-            {
-                throw new EException("Host creation call failed.");
-            }
-        }
-
-        public EService(
-                uint peerLimit = NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID, uint channelLimit = 0,
-                uint incomingBandwidth = 0, uint outgoingBandwidth = 0)
-        {
-            if (peerLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID)
-            {
-                throw new ArgumentOutOfRangeException(string.Format("peerLimit: {0}", peerLimit));
-            }
-
-            if (channelLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
-            {
-                throw new ArgumentOutOfRangeException(string.Format("channelLimit: {0}",
-                        channelLimit));
-            }
-
-            this.host = NativeMethods.EnetHostCreate(IntPtr.Zero, peerLimit, channelLimit,
-                    incomingBandwidth, outgoingBandwidth);
-
-            if (this.host == IntPtr.Zero)
-            {
-                throw new EException("Host creation call failed.");
-            }
-        }
-
-        ~EService()
-        {
-            this.Dispose(false);
-        }
-
-        public void Dispose()
-        {
-            this.Dispose(true);
-            GC.SuppressFinalize(this);
-        }
-
-        private void Dispose(bool disposing)
-        {
-            if (this.host == IntPtr.Zero)
-            {
-                return;
-            }
-
-            NativeMethods.EnetHostDestroy(this.host);
-
-            this.host = IntPtr.Zero;
-        }
-
-        public IntPtr HostPtr
-        {
-            get
-            {
-                return this.host;
-            }
-        }
-
-        public void EnableCrc()
-        {
-            NativeMethods.EnetEnableCrc(this.host);
-        }
-
-        private EEvent GetEvent()
-        {
-            var enetEv = new ENetEvent();
-            int ret = NativeMethods.EnetHostCheckEvents(this.host, enetEv);
-            if (ret <= 0)
-            {
-                return null;
-            }
-            var e = new EEvent(enetEv);
-            return e;
-        }
-
-        public void CompressWithRangeCoder()
-        {
-            NativeMethods.EnetHostCompressWithRangeCoder(this.host);
-        }
-
-        public void DoNotCompress()
-        {
-            NativeMethods.EnetHostCompress(this.host, IntPtr.Zero);
-        }
-
-        public void Flush()
-        {
-            NativeMethods.EnetHostFlush(this.host);
-        }
-
-        public void SetBandwidthLimit(uint incomingBandwidth, uint outgoingBandwidth)
-        {
-            NativeMethods.EnetHostBandwidthLimit(this.host, incomingBandwidth, outgoingBandwidth);
-        }
-
-        public void SetChannelLimit(uint channelLimit)
-        {
-            if (channelLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
-            {
-                throw new ArgumentOutOfRangeException(string.Format("channelLimit: {0}",
-                        channelLimit));
-            }
-            NativeMethods.EnetHostChannelLimit(this.host, channelLimit);
-        }
-
-        public event Action Events
-        {
-            add
-            {
-                lock (this.eventsLock)
-                {
-                    this.events += value;
-                }
-            }
-            remove
-            {
-                lock (this.eventsLock)
-                {
-                    this.events -= value;
-                }
-            }
-        }
-
-        public void OnEvents()
-        {
-            Action local = null;
-            lock (this.eventsLock)
-            {
-                if (this.events == null)
-                {
-                    return;
-                }
-                local = this.events;
-                this.events = null;
-            }
-            local();
-        }
-
-        public void Stop()
-        {
-            this.isRunning = false;
-        }
-
-        private int Service(int timeout)
-        {
-            if (timeout < 0)
-            {
-                throw new ArgumentOutOfRangeException(string.Format("timeout: {0}", timeout));
-            }
-            return NativeMethods.EnetHostService(this.host, null, (uint) timeout);
-        }
-
-        public void RunOnce(int timeout = 0)
-        {
-            if (timeout < 0)
-            {
-                throw new ArgumentOutOfRangeException(string.Format("timeout: {0}", timeout));
-            }
-
-            this.OnEvents();
-
-            if (this.Service(timeout) < 0)
-            {
-                return;
-            }
-
-            while (true)
-            {
-                EEvent eEvent = this.GetEvent();
-                if (eEvent == null)
-                {
-                    return;
-                }
-
-                switch (eEvent.Type)
-                {
-                    case EventType.Connect:
-                    {
-                        // 这是一个connect peer
-                        if (this.PeersManager.ContainsKey(eEvent.PeerPtr))
-                        {
-                            ESocket eSocket = this.PeersManager[eEvent.PeerPtr];
-                            eSocket.OnConnected(eEvent);
-                        }
-                                // accept peer
-                        else
-                        {
-                            // 如果server端没有acceptasync,则请求放入队列
-                            if (!this.PeersManager.ContainsKey(IntPtr.Zero))
-                            {
-                                this.connEEvents.AddLast(eEvent);
-                            }
-                            else
-                            {
-                                ESocket eSocket = this.PeersManager[IntPtr.Zero];
-                                eSocket.OnConnected(eEvent);
-                            }
-                        }
-                        break;
-                    }
-                    case EventType.Receive:
-                    {
-                        ESocket eSocket = this.PeersManager[eEvent.PeerPtr];
-                        eSocket.OnReceived(eEvent);
-                        break;
-                    }
-                    case EventType.Disconnect:
-                    {
-                        // 如果链接还在缓存中,则删除
-                        foreach (EEvent connEEvent in this.connEEvents)
-                        {
-                            if (connEEvent.PeerPtr != eEvent.PeerPtr)
-                            {
-                                continue;
-                            }
-                            this.connEEvents.Remove(connEEvent);
-                            return;
-                        }
-
-                        // 链接已经被应用层接收
-                        eEvent.EventState = EventState.DISCONNECTED;
-                        ESocket eSocket = this.PeersManager[eEvent.PeerPtr];
-                        this.PeersManager.Remove(eEvent.PeerPtr);
-
-                        // 等待的task将抛出异常
-                        if (eSocket.Connected != null)
-                        {
-                            eSocket.OnConnected(eEvent);
-                        }
-                        else if (eSocket.Received != null)
-                        {
-                            eSocket.OnReceived(eEvent);
-                        }
-                        else if (eSocket.Disconnect != null)
-                        {
-                            eSocket.OnDisconnect(eEvent);
-                        }
-
-                        eSocket.OnError(ErrorCode.ClientDisconnect);
-                        break;
-                    }
-                }
-            }
-        }
-
-        public void Start(int timeout = 0)
-        {
-            while (this.isRunning)
-            {
-                this.RunOnce(timeout);
-            }
-        }
-    }
+	public sealed class EService: IDisposable
+	{
+		static EService()
+		{
+			Library.Initialize();
+		}
+
+		private readonly PeersManager peersManager = new PeersManager();
+		private readonly LinkedList<EEvent> connEEvents = new LinkedList<EEvent>();
+
+		internal PeersManager PeersManager
+		{
+			get
+			{
+				return this.peersManager;
+			}
+		}
+
+		internal LinkedList<EEvent> ConnEEvents
+		{
+			get
+			{
+				return this.connEEvents;
+			}
+		}
+
+		private IntPtr host;
+		private bool isRunning = true;
+		private readonly object eventsLock = new object();
+		private Action events;
+
+		public EService(
+				string hostName, ushort port, uint peerLimit = NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID,
+				uint channelLimit = 0, uint incomingBandwidth = 0, uint outgoingBandwidth = 0)
+		{
+			if (peerLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID)
+			{
+				throw new ArgumentOutOfRangeException(string.Format("peerLimit: {0}", peerLimit));
+			}
+
+			if (channelLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
+			{
+				throw new ArgumentOutOfRangeException(string.Format("channelLimit: {0}", channelLimit));
+			}
+
+			var address = new Address { HostName = hostName, Port = port };
+			ENetAddress nativeAddress = address.Struct;
+			this.host = NativeMethods.EnetHostCreate(ref nativeAddress, peerLimit, channelLimit,
+					incomingBandwidth, outgoingBandwidth);
+
+			if (this.host == IntPtr.Zero)
+			{
+				throw new EException("Host creation call failed.");
+			}
+		}
+
+		public EService(
+				uint peerLimit = NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID, uint channelLimit = 0,
+				uint incomingBandwidth = 0, uint outgoingBandwidth = 0)
+		{
+			if (peerLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_PEER_ID)
+			{
+				throw new ArgumentOutOfRangeException(string.Format("peerLimit: {0}", peerLimit));
+			}
+
+			if (channelLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
+			{
+				throw new ArgumentOutOfRangeException(string.Format("channelLimit: {0}", channelLimit));
+			}
+
+			this.host = NativeMethods.EnetHostCreate(IntPtr.Zero, peerLimit, channelLimit, incomingBandwidth,
+					outgoingBandwidth);
+
+			if (this.host == IntPtr.Zero)
+			{
+				throw new EException("Host creation call failed.");
+			}
+		}
+
+		~EService()
+		{
+			this.Dispose(false);
+		}
+
+		public void Dispose()
+		{
+			this.Dispose(true);
+			GC.SuppressFinalize(this);
+		}
+
+		private void Dispose(bool disposing)
+		{
+			if (this.host == IntPtr.Zero)
+			{
+				return;
+			}
+
+			NativeMethods.EnetHostDestroy(this.host);
+
+			this.host = IntPtr.Zero;
+		}
+
+		public IntPtr HostPtr
+		{
+			get
+			{
+				return this.host;
+			}
+		}
+
+		public void EnableCrc()
+		{
+			NativeMethods.EnetEnableCrc(this.host);
+		}
+
+		private EEvent GetEvent()
+		{
+			var enetEv = new ENetEvent();
+			int ret = NativeMethods.EnetHostCheckEvents(this.host, enetEv);
+			if (ret <= 0)
+			{
+				return null;
+			}
+			var e = new EEvent(enetEv);
+			return e;
+		}
+
+		public void CompressWithRangeCoder()
+		{
+			NativeMethods.EnetHostCompressWithRangeCoder(this.host);
+		}
+
+		public void DoNotCompress()
+		{
+			NativeMethods.EnetHostCompress(this.host, IntPtr.Zero);
+		}
+
+		public void Flush()
+		{
+			NativeMethods.EnetHostFlush(this.host);
+		}
+
+		public void SetBandwidthLimit(uint incomingBandwidth, uint outgoingBandwidth)
+		{
+			NativeMethods.EnetHostBandwidthLimit(this.host, incomingBandwidth, outgoingBandwidth);
+		}
+
+		public void SetChannelLimit(uint channelLimit)
+		{
+			if (channelLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
+			{
+				throw new ArgumentOutOfRangeException(string.Format("channelLimit: {0}", channelLimit));
+			}
+			NativeMethods.EnetHostChannelLimit(this.host, channelLimit);
+		}
+
+		public event Action Events
+		{
+			add
+			{
+				lock (this.eventsLock)
+				{
+					this.events += value;
+				}
+			}
+			remove
+			{
+				lock (this.eventsLock)
+				{
+					this.events -= value;
+				}
+			}
+		}
+
+		public void OnEvents()
+		{
+			Action local = null;
+			lock (this.eventsLock)
+			{
+				if (this.events == null)
+				{
+					return;
+				}
+				local = this.events;
+				this.events = null;
+			}
+			local();
+		}
+
+		public void Stop()
+		{
+			this.isRunning = false;
+		}
+
+		private int Service(int timeout)
+		{
+			if (timeout < 0)
+			{
+				throw new ArgumentOutOfRangeException(string.Format("timeout: {0}", timeout));
+			}
+			return NativeMethods.EnetHostService(this.host, null, (uint) timeout);
+		}
+
+		public void RunOnce(int timeout = 0)
+		{
+			if (timeout < 0)
+			{
+				throw new ArgumentOutOfRangeException(string.Format("timeout: {0}", timeout));
+			}
+
+			this.OnEvents();
+
+			if (this.Service(timeout) < 0)
+			{
+				return;
+			}
+
+			while (true)
+			{
+				EEvent eEvent = this.GetEvent();
+				if (eEvent == null)
+				{
+					return;
+				}
+
+				switch (eEvent.Type)
+				{
+					case EventType.Connect:
+					{
+						// 这是一个connect peer
+						if (this.PeersManager.ContainsKey(eEvent.PeerPtr))
+						{
+							ESocket eSocket = this.PeersManager[eEvent.PeerPtr];
+							eSocket.OnConnected(eEvent);
+						}
+								// accept peer
+						else
+						{
+							// 如果server端没有acceptasync,则请求放入队列
+							if (!this.PeersManager.ContainsKey(IntPtr.Zero))
+							{
+								this.connEEvents.AddLast(eEvent);
+							}
+							else
+							{
+								ESocket eSocket = this.PeersManager[IntPtr.Zero];
+								eSocket.OnConnected(eEvent);
+							}
+						}
+						break;
+					}
+					case EventType.Receive:
+					{
+						ESocket eSocket = this.PeersManager[eEvent.PeerPtr];
+						eSocket.OnReceived(eEvent);
+						break;
+					}
+					case EventType.Disconnect:
+					{
+						// 如果链接还在缓存中,则删除
+						foreach (EEvent connEEvent in this.connEEvents)
+						{
+							if (connEEvent.PeerPtr != eEvent.PeerPtr)
+							{
+								continue;
+							}
+							this.connEEvents.Remove(connEEvent);
+							return;
+						}
+
+						// 链接已经被应用层接收
+						eEvent.EventState = EventState.DISCONNECTED;
+						ESocket eSocket = this.PeersManager[eEvent.PeerPtr];
+						this.PeersManager.Remove(eEvent.PeerPtr);
+
+						// 等待的task将抛出异常
+						if (eSocket.Connected != null)
+						{
+							eSocket.OnConnected(eEvent);
+						}
+						else if (eSocket.Received != null)
+						{
+							eSocket.OnReceived(eEvent);
+						}
+						else if (eSocket.Disconnect != null)
+						{
+							eSocket.OnDisconnect(eEvent);
+						}
+
+						eSocket.OnError(ErrorCode.ClientDisconnect);
+						break;
+					}
+				}
+			}
+		}
+
+		public void Start(int timeout = 0)
+		{
+			while (this.isRunning)
+			{
+				this.RunOnce(timeout);
+			}
+		}
+	}
 }

+ 269 - 272
CSharp/Platform/ENet/ESocket.cs

@@ -5,306 +5,303 @@ using System.Threading.Tasks;
 
 namespace ENet
 {
-    public sealed class ESocket: IDisposable
-    {
-        private IntPtr peerPtr = IntPtr.Zero;
-        private readonly EService service;
-        private readonly LinkedList<byte[]> recvBuffer = new LinkedList<byte[]>();
+	public sealed class ESocket: IDisposable
+	{
+		private IntPtr peerPtr = IntPtr.Zero;
+		private readonly EService service;
+		private readonly LinkedList<byte[]> recvBuffer = new LinkedList<byte[]>();
 
-        public Action<EEvent> Connected { get; set; }
-        public Action<EEvent> Received { get; set; }
-        public Action<EEvent> Disconnect { get; set; }
-        public Action<int> Error { get; set; }
+		public Action<EEvent> Connected { get; set; }
+		public Action<EEvent> Received { get; set; }
+		public Action<EEvent> Disconnect { get; set; }
+		public Action<int> Error { get; set; }
 
-        public ESocket(EService service)
-        {
-            this.service = service;
-        }
+		public ESocket(EService service)
+		{
+			this.service = service;
+		}
 
-        public void Dispose()
-        {
-            if (this.peerPtr == IntPtr.Zero)
-            {
-                return;
-            }
-            NativeMethods.EnetPeerReset(this.peerPtr);
-            this.peerPtr = IntPtr.Zero;
-        }
+		public void Dispose()
+		{
+			if (this.peerPtr == IntPtr.Zero)
+			{
+				return;
+			}
+			NativeMethods.EnetPeerReset(this.peerPtr);
+			this.peerPtr = IntPtr.Zero;
+		}
 
-        public IntPtr PeerPtr
-        {
-            get
-            {
-                return this.peerPtr;
-            }
-            set
-            {
-                this.peerPtr = value;
-            }
-        }
+		public IntPtr PeerPtr
+		{
+			get
+			{
+				return this.peerPtr;
+			}
+			set
+			{
+				this.peerPtr = value;
+			}
+		}
 
-        private ENetPeer Struct
-        {
-            get
-            {
-                if (this.peerPtr == IntPtr.Zero)
-                {
-                    return new ENetPeer();
-                }
-                return (ENetPeer) Marshal.PtrToStructure(this.peerPtr, typeof (ENetPeer));
-            }
-            set
-            {
-                Marshal.StructureToPtr(value, this.peerPtr, false);
-            }
-        }
+		private ENetPeer Struct
+		{
+			get
+			{
+				if (this.peerPtr == IntPtr.Zero)
+				{
+					return new ENetPeer();
+				}
+				return (ENetPeer) Marshal.PtrToStructure(this.peerPtr, typeof (ENetPeer));
+			}
+			set
+			{
+				Marshal.StructureToPtr(value, this.peerPtr, false);
+			}
+		}
 
-        public PeerState State
-        {
-            get
-            {
-                if (this.peerPtr == IntPtr.Zero)
-                {
-                    return PeerState.Uninitialized;
-                }
-                return this.Struct.State;
-            }
-        }
+		public PeerState State
+		{
+			get
+			{
+				if (this.peerPtr == IntPtr.Zero)
+				{
+					return PeerState.Uninitialized;
+				}
+				return this.Struct.State;
+			}
+		}
 
-        public void Ping()
-        {
-            NativeMethods.EnetPeerPing(this.peerPtr);
-        }
+		public void Ping()
+		{
+			NativeMethods.EnetPeerPing(this.peerPtr);
+		}
 
-        public void ConfigureThrottle(uint interval, uint acceleration, uint deceleration)
-        {
-            NativeMethods.EnetPeerThrottleConfigure(this.peerPtr, interval, acceleration,
-                    deceleration);
-        }
+		public void ConfigureThrottle(uint interval, uint acceleration, uint deceleration)
+		{
+			NativeMethods.EnetPeerThrottleConfigure(this.peerPtr, interval, acceleration, deceleration);
+		}
 
-        public Task<bool> ConnectAsync(
-                string hostName, ushort port,
-                uint channelLimit = NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT, uint data = 0)
-        {
-            if (channelLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
-            {
-                throw new ArgumentOutOfRangeException("channelLimit");
-            }
+		public Task<bool> ConnectAsync(
+				string hostName, ushort port,
+				uint channelLimit = NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT, uint data = 0)
+		{
+			if (channelLimit > NativeMethods.ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
+			{
+				throw new ArgumentOutOfRangeException("channelLimit");
+			}
 
-            var tcs = new TaskCompletionSource<bool>();
-            var address = new Address { HostName = hostName, Port = port };
-            ENetAddress nativeAddress = address.Struct;
-            this.peerPtr = NativeMethods.EnetHostConnect(this.service.HostPtr, ref nativeAddress,
-                    channelLimit, data);
-            if (this.peerPtr == IntPtr.Zero)
-            {
-                throw new EException("host connect call failed.");
-            }
-            this.service.PeersManager.Add(this.peerPtr, this);
-            this.Connected = eEvent =>
-            {
-                if (eEvent.EventState == EventState.DISCONNECTED)
-                {
-                    tcs.TrySetException(new EException("socket disconnected in connect"));
-                }
-                tcs.TrySetResult(true);
-            };
-            return tcs.Task;
-        }
+			var tcs = new TaskCompletionSource<bool>();
+			var address = new Address { HostName = hostName, Port = port };
+			ENetAddress nativeAddress = address.Struct;
+			this.peerPtr = NativeMethods.EnetHostConnect(this.service.HostPtr, ref nativeAddress,
+					channelLimit, data);
+			if (this.peerPtr == IntPtr.Zero)
+			{
+				throw new EException("host connect call failed.");
+			}
+			this.service.PeersManager.Add(this.peerPtr, this);
+			this.Connected = eEvent =>
+			{
+				if (eEvent.EventState == EventState.DISCONNECTED)
+				{
+					tcs.TrySetException(new EException("socket disconnected in connect"));
+				}
+				tcs.TrySetResult(true);
+			};
+			return tcs.Task;
+		}
 
-        public Task<bool> AcceptAsync()
-        {
-            if (this.service.PeersManager.ContainsKey(IntPtr.Zero))
-            {
-                throw new EException("do not accept twice!");
-            }
+		public Task<bool> AcceptAsync()
+		{
+			if (this.service.PeersManager.ContainsKey(IntPtr.Zero))
+			{
+				throw new EException("do not accept twice!");
+			}
 
-            var tcs = new TaskCompletionSource<bool>();
+			var tcs = new TaskCompletionSource<bool>();
 
-            // 如果有请求连接缓存的包,从缓存中取
-            if (this.service.ConnEEvents.Count > 0)
-            {
-                EEvent eEvent = this.service.ConnEEvents.First.Value;
-                this.service.ConnEEvents.RemoveFirst();
+			// 如果有请求连接缓存的包,从缓存中取
+			if (this.service.ConnEEvents.Count > 0)
+			{
+				EEvent eEvent = this.service.ConnEEvents.First.Value;
+				this.service.ConnEEvents.RemoveFirst();
 
-                this.PeerPtr = eEvent.PeerPtr;
-                this.service.PeersManager.Add(this.PeerPtr, this);
-                tcs.TrySetResult(true);
-            }
-            else
-            {
-                this.service.PeersManager.Add(this.PeerPtr, this);
-                this.Connected = eEvent =>
-                {
-                    if (eEvent.EventState == EventState.DISCONNECTED)
-                    {
-                        tcs.TrySetException(new EException("socket disconnected in accpet"));
-                    }
+				this.PeerPtr = eEvent.PeerPtr;
+				this.service.PeersManager.Add(this.PeerPtr, this);
+				tcs.TrySetResult(true);
+			}
+			else
+			{
+				this.service.PeersManager.Add(this.PeerPtr, this);
+				this.Connected = eEvent =>
+				{
+					if (eEvent.EventState == EventState.DISCONNECTED)
+					{
+						tcs.TrySetException(new EException("socket disconnected in accpet"));
+					}
 
-                    this.service.PeersManager.Remove(IntPtr.Zero);
+					this.service.PeersManager.Remove(IntPtr.Zero);
 
-                    this.PeerPtr = eEvent.PeerPtr;
-                    this.service.PeersManager.Add(this.PeerPtr, this);
-                    tcs.TrySetResult(true);
-                };
-            }
-            return tcs.Task;
-        }
+					this.PeerPtr = eEvent.PeerPtr;
+					this.service.PeersManager.Add(this.PeerPtr, this);
+					tcs.TrySetResult(true);
+				};
+			}
+			return tcs.Task;
+		}
 
-        public void WriteAsync(
-                byte[] data, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
-        {
-            var packet = new EPacket(data, flags);
-            NativeMethods.EnetPeerSend(this.peerPtr, channelID, packet.PacketPtr);
-            // enet_peer_send函数会自动删除packet,设置为0,防止Dispose或者析构函数再次删除
-            packet.PacketPtr = IntPtr.Zero;
-        }
+		public void WriteAsync(byte[] data, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
+		{
+			var packet = new EPacket(data, flags);
+			NativeMethods.EnetPeerSend(this.peerPtr, channelID, packet.PacketPtr);
+			// enet_peer_send函数会自动删除packet,设置为0,防止Dispose或者析构函数再次删除
+			packet.PacketPtr = IntPtr.Zero;
+		}
 
-        public Task<byte[]> ReadAsync()
-        {
-            var tcs = new TaskCompletionSource<byte[]>();
+		public Task<byte[]> ReadAsync()
+		{
+			var tcs = new TaskCompletionSource<byte[]>();
 
-            // 如果有缓存的包,从缓存中取
-            if (this.recvBuffer.Count > 0)
-            {
-                var bytes = this.recvBuffer.First.Value;
-                this.recvBuffer.RemoveFirst();
-                tcs.TrySetResult(bytes);
-            }
-                    // 没有缓存封包,设置回调等待
-            else
-            {
-                this.Received = eEvent =>
-                {
-                    if (eEvent.EventState == EventState.DISCONNECTED)
-                    {
-                        tcs.TrySetException(new EException("socket disconnected in receive"));
-                    }
+			// 如果有缓存的包,从缓存中取
+			if (this.recvBuffer.Count > 0)
+			{
+				var bytes = this.recvBuffer.First.Value;
+				this.recvBuffer.RemoveFirst();
+				tcs.TrySetResult(bytes);
+			}
+					// 没有缓存封包,设置回调等待
+			else
+			{
+				this.Received = eEvent =>
+				{
+					if (eEvent.EventState == EventState.DISCONNECTED)
+					{
+						tcs.TrySetException(new EException("socket disconnected in receive"));
+					}
 
-                    using (var packet = new EPacket(eEvent.PacketPtr))
-                    {
-                        var bytes = packet.Bytes;
-                        tcs.TrySetResult(bytes);
-                    }
-                };
-            }
-            return tcs.Task;
-        }
+					using (var packet = new EPacket(eEvent.PacketPtr))
+					{
+						var bytes = packet.Bytes;
+						tcs.TrySetResult(bytes);
+					}
+				};
+			}
+			return tcs.Task;
+		}
 
-        public void WriteAsync(
-                Action<int> action, byte[] data, byte channelID = 0,
-                PacketFlags flags = PacketFlags.Reliable)
-        {
-            var packet = new EPacket(data, flags);
-            int ret = NativeMethods.EnetPeerSend(this.peerPtr, channelID, packet.PacketPtr);
-            // enet_peer_send函数会自动删除packet,设置为0,防止Dispose或者析构函数再次删除
-            packet.PacketPtr = IntPtr.Zero;
-            action(ret);
-        }
+		public void WriteAsync(
+				Action<int> action, byte[] data, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
+		{
+			var packet = new EPacket(data, flags);
+			int ret = NativeMethods.EnetPeerSend(this.peerPtr, channelID, packet.PacketPtr);
+			// enet_peer_send函数会自动删除packet,设置为0,防止Dispose或者析构函数再次删除
+			packet.PacketPtr = IntPtr.Zero;
+			action(ret);
+		}
 
-        public void ReadAsync(Action<byte[], int> action)
-        {
-            // 如果有缓存的包,从缓存中取
-            if (this.recvBuffer.Count > 0)
-            {
-                var bytes = this.recvBuffer.First.Value;
-                this.recvBuffer.RemoveFirst();
-                action(bytes, 0);
-            }
-                    // 没有缓存封包,设置回调等待
-            else
-            {
-                this.Received = eEvent =>
-                {
-                    if (eEvent.EventState == EventState.DISCONNECTED)
-                    {
-                        action(new byte[0], -1);
-                    }
+		public void ReadAsync(Action<byte[], int> action)
+		{
+			// 如果有缓存的包,从缓存中取
+			if (this.recvBuffer.Count > 0)
+			{
+				var bytes = this.recvBuffer.First.Value;
+				this.recvBuffer.RemoveFirst();
+				action(bytes, 0);
+			}
+					// 没有缓存封包,设置回调等待
+			else
+			{
+				this.Received = eEvent =>
+				{
+					if (eEvent.EventState == EventState.DISCONNECTED)
+					{
+						action(new byte[0], -1);
+					}
 
-                    using (var packet = new EPacket(eEvent.PacketPtr))
-                    {
-                        var bytes = packet.Bytes;
-                        action(bytes, 0);
-                    }
-                };
-            }
-        }
+					using (var packet = new EPacket(eEvent.PacketPtr))
+					{
+						var bytes = packet.Bytes;
+						action(bytes, 0);
+					}
+				};
+			}
+		}
 
-        public Task<bool> DisconnectAsync(uint data = 0)
-        {
-            NativeMethods.EnetPeerDisconnect(this.peerPtr, data);
-            // EnetPeerDisconnect会reset Peer,这里设置为0,防止再次Dispose
-            this.PeerPtr = IntPtr.Zero;
-            var tcs = new TaskCompletionSource<bool>();
-            this.Disconnect = eEvent => tcs.TrySetResult(true);
-            return tcs.Task;
-        }
+		public Task<bool> DisconnectAsync(uint data = 0)
+		{
+			NativeMethods.EnetPeerDisconnect(this.peerPtr, data);
+			// EnetPeerDisconnect会reset Peer,这里设置为0,防止再次Dispose
+			this.PeerPtr = IntPtr.Zero;
+			var tcs = new TaskCompletionSource<bool>();
+			this.Disconnect = eEvent => tcs.TrySetResult(true);
+			return tcs.Task;
+		}
 
-        public Task<bool> DisconnectLaterAsync(uint data = 0)
-        {
-            NativeMethods.EnetPeerDisconnectLater(this.peerPtr, data);
-            // EnetPeerDisconnect会reset Peer,这里设置为0,防止再次Dispose
-            this.PeerPtr = IntPtr.Zero;
-            var tcs = new TaskCompletionSource<bool>();
-            this.Disconnect = eEvent => tcs.TrySetResult(true);
-            return tcs.Task;
-        }
+		public Task<bool> DisconnectLaterAsync(uint data = 0)
+		{
+			NativeMethods.EnetPeerDisconnectLater(this.peerPtr, data);
+			// EnetPeerDisconnect会reset Peer,这里设置为0,防止再次Dispose
+			this.PeerPtr = IntPtr.Zero;
+			var tcs = new TaskCompletionSource<bool>();
+			this.Disconnect = eEvent => tcs.TrySetResult(true);
+			return tcs.Task;
+		}
 
-        public void DisconnectNow(uint data)
-        {
-            NativeMethods.EnetPeerDisconnectNow(this.peerPtr, data);
-            // EnetPeerDisconnect会reset Peer,这里设置为0,防止再次Dispose
-            this.PeerPtr = IntPtr.Zero;
-        }
+		public void DisconnectNow(uint data)
+		{
+			NativeMethods.EnetPeerDisconnectNow(this.peerPtr, data);
+			// EnetPeerDisconnect会reset Peer,这里设置为0,防止再次Dispose
+			this.PeerPtr = IntPtr.Zero;
+		}
 
-        internal void OnConnected(EEvent eEvent)
-        {
-            if (this.Connected == null)
-            {
-                return;
-            }
-            Action<EEvent> localConnected = this.Connected;
-            this.Connected = null;
-            // 此调用将让await ConnectAsync返回,所以null必须在此之前设置
-            localConnected(eEvent);
-        }
+		internal void OnConnected(EEvent eEvent)
+		{
+			if (this.Connected == null)
+			{
+				return;
+			}
+			Action<EEvent> localConnected = this.Connected;
+			this.Connected = null;
+			// 此调用将让await ConnectAsync返回,所以null必须在此之前设置
+			localConnected(eEvent);
+		}
 
-        internal void OnReceived(EEvent eEvent)
-        {
-            // 如果应用层还未调用readasync则将包放到缓存队列
-            if (this.Received == null)
-            {
-                using (var packet = new EPacket(eEvent.PacketPtr))
-                {
-                    var bytes = packet.Bytes;
-                    this.recvBuffer.AddLast(bytes);
-                }
-            }
-            else
-            {
-                Action<EEvent> localReceived = this.Received;
-                this.Received = null;
-                // 此调用将让await ReadAsync返回,所以null必须在此之前设置
-                localReceived(eEvent);
-            }
-        }
+		internal void OnReceived(EEvent eEvent)
+		{
+			// 如果应用层还未调用readasync则将包放到缓存队列
+			if (this.Received == null)
+			{
+				using (var packet = new EPacket(eEvent.PacketPtr))
+				{
+					var bytes = packet.Bytes;
+					this.recvBuffer.AddLast(bytes);
+				}
+			}
+			else
+			{
+				Action<EEvent> localReceived = this.Received;
+				this.Received = null;
+				// 此调用将让await ReadAsync返回,所以null必须在此之前设置
+				localReceived(eEvent);
+			}
+		}
 
-        internal void OnDisconnect(EEvent eEvent)
-        {
-            if (this.Disconnect == null)
-            {
-                return;
-            }
-            this.Disconnect(eEvent);
-        }
+		internal void OnDisconnect(EEvent eEvent)
+		{
+			if (this.Disconnect == null)
+			{
+				return;
+			}
+			this.Disconnect(eEvent);
+		}
 
-        internal void OnError(int errorCode)
-        {
-            if (this.Error == null)
-            {
-                return;
-            }
-            this.Error(errorCode);
-        }
-    }
+		internal void OnError(int errorCode)
+		{
+			if (this.Error == null)
+			{
+				return;
+			}
+			this.Error(errorCode);
+		}
+	}
 }

+ 4 - 4
CSharp/Platform/ENet/ErrorCode.cs

@@ -1,7 +1,7 @@
 namespace ENet
 {
-    public static class ErrorCode
-    {
-        public const int ClientDisconnect = 1;
-    }
+	public static class ErrorCode
+	{
+		public const int ClientDisconnect = 1;
+	}
 }

+ 27 - 28
CSharp/Platform/ENet/Library.cs

@@ -1,33 +1,32 @@
 namespace ENet
 {
-    internal static class Library
-    {
-        public static void Initialize()
-        {
-            var inits = new ENetCallbacks();
-            int ret = NativeMethods.EnetInitializeWithCallbacks(NativeMethods.ENET_VERSION,
-                    ref inits);
-            if (ret < 0)
-            {
-                throw new EException(string.Format("Initialization failed, ret: {0}", ret));
-            }
-        }
+	internal static class Library
+	{
+		public static void Initialize()
+		{
+			var inits = new ENetCallbacks();
+			int ret = NativeMethods.EnetInitializeWithCallbacks(NativeMethods.ENET_VERSION, ref inits);
+			if (ret < 0)
+			{
+				throw new EException(string.Format("Initialization failed, ret: {0}", ret));
+			}
+		}
 
-        public static void Deinitialize()
-        {
-            NativeMethods.EnetDeinitialize();
-        }
+		public static void Deinitialize()
+		{
+			NativeMethods.EnetDeinitialize();
+		}
 
-        public static uint Time
-        {
-            get
-            {
-                return NativeMethods.EnetTimeGet();
-            }
-            set
-            {
-                NativeMethods.EnetTimeSet(value);
-            }
-        }
-    }
+		public static uint Time
+		{
+			get
+			{
+				return NativeMethods.EnetTimeGet();
+			}
+			set
+			{
+				NativeMethods.EnetTimeSet(value);
+			}
+		}
+	}
 }

+ 131 - 150
CSharp/Platform/ENet/NativeMethods.cs

@@ -4,154 +4,135 @@ using System.Text;
 
 namespace ENet
 {
-    public static class NativeMethods
-    {
-        private const string LIB = "ENetCpp.dll";
-
-        public const int ENET_PEER_PACKET_THROTTLE_SCALE = 32;
-        public const int ENET_PEER_PACKET_THROTTLE_ACCELERATION = 2;
-        public const int ENET_PEER_PACKET_THROTTLE_DECELERATION = 2;
-        public const int ENET_PEER_PACKET_THROTTLE_INTERVAL = 5000;
-        public const int ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT = 1;
-        public const int ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT = 255;
-        public const int ENET_PROTOCOL_MAXIMUM_PEER_ID = 0xfff;
-        public const uint ENET_VERSION = (1 << 16) | (3 << 8) | (10);
-        public const uint ENET_HOST_ANY = 0;
-        public const uint ENET_HOST_BROADCAST = 0xffffffff;
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_address_set_host")]
-        internal static extern int EnetAddressSetHost(ref ENetAddress address, string hostName);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_address_get_host")]
-        internal static extern int EnetAddressGetHost(
-                ref ENetAddress address, StringBuilder hostName, uint nameLength);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_address_get_host_ip")]
-        internal static extern int EnetAddressGetHostIp(
-                ref ENetAddress address, StringBuilder hostIp, uint ipLength);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_deinitialize")]
-        internal static extern void EnetDeinitialize();
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_initialize")
-        ]
-        internal static extern int EnetInitialize();
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_initialize_with_callbacks")]
-        internal static extern int EnetInitializeWithCallbacks(
-                uint version, ref ENetCallbacks inits);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_enable_crc")
-        ]
-        internal static extern void EnetEnableCrc(IntPtr host);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_host_create"
-                )]
-        internal static extern IntPtr EnetHostCreate(
-                ref ENetAddress address, uint peerLimit, uint channelLimit, uint incomingBandwidth,
-                uint outgoingBandwidth);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_host_create"
-                )]
-        internal static extern IntPtr EnetHostCreate(
-                IntPtr address, uint peerLimit, uint channelLimit, uint incomingBandwidth,
-                uint outgoingBandwidth);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_host_destroy")]
-        internal static extern void EnetHostDestroy(IntPtr host);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_host_connect")]
-        internal static extern IntPtr EnetHostConnect(
-                IntPtr host, ref ENetAddress address, uint channelCount, uint data);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_host_broadcast")]
-        internal static extern void EnetHostBroadcast(IntPtr host, byte channelID, IntPtr packet);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_host_compress")]
-        internal static extern void EnetHostCompress(IntPtr host, IntPtr compressor);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_host_compress_with_range_coder")]
-        internal static extern int EnetHostCompressWithRangeCoder(IntPtr host);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_host_channel_limit")]
-        internal static extern void EnetHostChannelLimit(IntPtr host, uint channelLimit);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_host_bandwidth_limit")]
-        internal static extern void EnetHostBandwidthLimit(
-                IntPtr host, uint incomingBandwidth, uint outgoingBandwidth);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_host_flush")
-        ]
-        internal static extern void EnetHostFlush(IntPtr host);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_host_check_events")]
-        internal static extern int EnetHostCheckEvents(IntPtr host, ENetEvent ev);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_host_service")]
-        internal static extern int EnetHostService(IntPtr host, ENetEvent ev, uint timeout);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_time_get")]
-        internal static extern uint EnetTimeGet();
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_time_set")]
-        internal static extern void EnetTimeSet(uint newTimeBase);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_packet_create")]
-        internal static extern IntPtr EnetPacketCreate(
-                byte[] data, uint dataLength, PacketFlags flags);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_packet_destroy")]
-        internal static extern void EnetPacketDestroy(IntPtr packet);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_packet_resize")]
-        internal static extern int EnetPacketResize(IntPtr packet, uint dataLength);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_peer_throttle_configure")]
-        internal static extern void EnetPeerThrottleConfigure(
-                IntPtr peer, uint interval, uint acceleration, uint deceleration);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_peer_send")]
-        internal static extern int EnetPeerSend(IntPtr peer, byte channelID, IntPtr packet);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_peer_receive")]
-        internal static extern IntPtr EnetPeerReceive(IntPtr peer, out byte channelID);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_peer_reset")
-        ]
-        internal static extern void EnetPeerReset(IntPtr peer);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_peer_ping")]
-        internal static extern void EnetPeerPing(IntPtr peer);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_peer_disconnect_now")]
-        internal static extern void EnetPeerDisconnectNow(IntPtr peer, uint data);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_peer_disconnect")]
-        internal static extern void EnetPeerDisconnect(IntPtr peer, uint data);
-
-        [DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
-                EntryPoint = "enet_peer_disconnect_later")]
-        internal static extern void EnetPeerDisconnectLater(IntPtr peer, uint data);
-    }
+	public static class NativeMethods
+	{
+		private const string LIB = "ENetCpp.dll";
+
+		public const int ENET_PEER_PACKET_THROTTLE_SCALE = 32;
+		public const int ENET_PEER_PACKET_THROTTLE_ACCELERATION = 2;
+		public const int ENET_PEER_PACKET_THROTTLE_DECELERATION = 2;
+		public const int ENET_PEER_PACKET_THROTTLE_INTERVAL = 5000;
+		public const int ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT = 1;
+		public const int ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT = 255;
+		public const int ENET_PROTOCOL_MAXIMUM_PEER_ID = 0xfff;
+		public const uint ENET_VERSION = (1 << 16) | (3 << 8) | (10);
+		public const uint ENET_HOST_ANY = 0;
+		public const uint ENET_HOST_BROADCAST = 0xffffffff;
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_address_set_host")
+		]
+		internal static extern int EnetAddressSetHost(ref ENetAddress address, string hostName);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_address_get_host")
+		]
+		internal static extern int EnetAddressGetHost(
+				ref ENetAddress address, StringBuilder hostName, uint nameLength);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
+				EntryPoint = "enet_address_get_host_ip")]
+		internal static extern int EnetAddressGetHostIp(
+				ref ENetAddress address, StringBuilder hostIp, uint ipLength);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_deinitialize")]
+		internal static extern void EnetDeinitialize();
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_initialize")]
+		internal static extern int EnetInitialize();
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
+				EntryPoint = "enet_initialize_with_callbacks")]
+		internal static extern int EnetInitializeWithCallbacks(uint version, ref ENetCallbacks inits);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_enable_crc")]
+		internal static extern void EnetEnableCrc(IntPtr host);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_host_create")]
+		internal static extern IntPtr EnetHostCreate(
+				ref ENetAddress address, uint peerLimit, uint channelLimit, uint incomingBandwidth,
+				uint outgoingBandwidth);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_host_create")]
+		internal static extern IntPtr EnetHostCreate(
+				IntPtr address, uint peerLimit, uint channelLimit, uint incomingBandwidth,
+				uint outgoingBandwidth);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_host_destroy")]
+		internal static extern void EnetHostDestroy(IntPtr host);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_host_connect")]
+		internal static extern IntPtr EnetHostConnect(
+				IntPtr host, ref ENetAddress address, uint channelCount, uint data);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_host_broadcast")]
+		internal static extern void EnetHostBroadcast(IntPtr host, byte channelID, IntPtr packet);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_host_compress")]
+		internal static extern void EnetHostCompress(IntPtr host, IntPtr compressor);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
+				EntryPoint = "enet_host_compress_with_range_coder")]
+		internal static extern int EnetHostCompressWithRangeCoder(IntPtr host);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
+				EntryPoint = "enet_host_channel_limit")]
+		internal static extern void EnetHostChannelLimit(IntPtr host, uint channelLimit);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
+				EntryPoint = "enet_host_bandwidth_limit")]
+		internal static extern void EnetHostBandwidthLimit(
+				IntPtr host, uint incomingBandwidth, uint outgoingBandwidth);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_host_flush")]
+		internal static extern void EnetHostFlush(IntPtr host);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_host_check_events"
+				)]
+		internal static extern int EnetHostCheckEvents(IntPtr host, ENetEvent ev);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_host_service")]
+		internal static extern int EnetHostService(IntPtr host, ENetEvent ev, uint timeout);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_time_get")]
+		internal static extern uint EnetTimeGet();
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_time_set")]
+		internal static extern void EnetTimeSet(uint newTimeBase);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_packet_create")]
+		internal static extern IntPtr EnetPacketCreate(byte[] data, uint dataLength, PacketFlags flags);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_packet_destroy")]
+		internal static extern void EnetPacketDestroy(IntPtr packet);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_packet_resize")]
+		internal static extern int EnetPacketResize(IntPtr packet, uint dataLength);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
+				EntryPoint = "enet_peer_throttle_configure")]
+		internal static extern void EnetPeerThrottleConfigure(
+				IntPtr peer, uint interval, uint acceleration, uint deceleration);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_peer_send")]
+		internal static extern int EnetPeerSend(IntPtr peer, byte channelID, IntPtr packet);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_peer_receive")]
+		internal static extern IntPtr EnetPeerReceive(IntPtr peer, out byte channelID);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_peer_reset")]
+		internal static extern void EnetPeerReset(IntPtr peer);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_peer_ping")]
+		internal static extern void EnetPeerPing(IntPtr peer);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
+				EntryPoint = "enet_peer_disconnect_now")]
+		internal static extern void EnetPeerDisconnectNow(IntPtr peer, uint data);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl, EntryPoint = "enet_peer_disconnect")]
+		internal static extern void EnetPeerDisconnect(IntPtr peer, uint data);
+
+		[DllImport(LIB, CallingConvention = CallingConvention.Cdecl,
+				EntryPoint = "enet_peer_disconnect_later")]
+		internal static extern void EnetPeerDisconnectLater(IntPtr peer, uint data);
+	}
 }

Unele fișiere nu au fost afișate deoarece prea multe fișiere au fost modificate în acest diff