text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
fileFormatVersion: 2 guid: 1f28ab385e1ddf6448d270d4fb1e4727 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts.meta/0
{ "file_path": "ET/Unity/Assets/Scripts.meta", "repo_id": "ET", "token_count": 70 }
99
fileFormatVersion: 2 guid: 50901d1f8551c05499583f1a5d362d06 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/Analyzer/EntitySystemOf.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Analyzer/EntitySystemOf.cs.meta", "repo_id": "ET", "token_count": 94 }
100
using System; namespace ET { public struct EntityRef<T> where T: Entity { private readonly long instanceId; private T entity; private EntityRef(T t) { if (t == null) { this.instanceId = 0; this.entity = null; return; } this.instanceId = t.InstanceId; this.entity = t; } private T UnWrap { get { if (this.entity == null) { return null; } if (this.entity.InstanceId != this.instanceId) { // 这里instanceId变化了,设置为null,解除引用,好让runtime去gc this.entity = null; } return this.entity; } } public static implicit operator EntityRef<T>(T t) { return new EntityRef<T>(t); } public static implicit operator T(EntityRef<T> v) { return v.UnWrap; } } public struct EntityWeakRef<T> where T: Entity { private long instanceId; // 使用WeakReference,这样不会导致entity dispose了却无法gc的问题 // 不过暂时没有测试WeakReference的性能 private readonly WeakReference<T> weakRef; private EntityWeakRef(T t) { if (t == null) { this.instanceId = 0; this.weakRef = null; return; } this.instanceId = t.InstanceId; this.weakRef = new WeakReference<T>(t); } private T UnWrap { get { if (this.instanceId == 0) { return null; } if (!this.weakRef.TryGetTarget(out T entity)) { this.instanceId = 0; return null; } if (entity.InstanceId != this.instanceId) { this.instanceId = 0; return null; } return entity; } } public static implicit operator EntityWeakRef<T>(T t) { return new EntityWeakRef<T>(t); } public static implicit operator T(EntityWeakRef<T> v) { return v.UnWrap; } } }
ET/Unity/Assets/Scripts/Core/Entity/EntityRef.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Entity/EntityRef.cs", "repo_id": "ET", "token_count": 1585 }
101
using System; namespace ET { public interface ILateUpdate { } public interface ILateUpdateSystem: ISystemType { void Run(Entity o); } [EntitySystem] public abstract class LateUpdateSystem<T> : SystemObject, ILateUpdateSystem where T: Entity, ILateUpdate { void ILateUpdateSystem.Run(Entity o) { this.LateUpdate((T)o); } Type ISystemType.Type() { return typeof(T); } Type ISystemType.SystemType() { return typeof(ILateUpdateSystem); } int ISystemType.GetInstanceQueueIndex() { return InstanceQueueIndex.LateUpdate; } protected abstract void LateUpdate(T self); } }
ET/Unity/Assets/Scripts/Core/Entity/ILateUpdateSystem.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Entity/ILateUpdateSystem.cs", "repo_id": "ET", "token_count": 238 }
102
using System.Diagnostics; using MongoDB.Bson.Serialization.Attributes; namespace ET { [EnableMethod] [ChildOf] public class Scene: Entity, IScene { [BsonIgnore] public Fiber Fiber { get; set; } public string Name { get; } public SceneType SceneType { get; set; } public Scene() { } public Scene(Fiber fiber, long id, long instanceId, SceneType sceneType, string name) { this.Id = id; this.Name = name; this.InstanceId = instanceId; this.SceneType = sceneType; this.IsCreated = true; this.IsNew = true; this.Fiber = fiber; this.IScene = this; this.IsRegister = true; Log.Info($"scene create: {this.SceneType} {this.Id} {this.InstanceId}"); } public override void Dispose() { base.Dispose(); Log.Info($"scene dispose: {this.SceneType} {this.Id} {this.InstanceId}"); } protected override string ViewName { get { return $"{this.GetType().Name} ({this.SceneType})"; } } } }
ET/Unity/Assets/Scripts/Core/Entity/Scene.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Entity/Scene.cs", "repo_id": "ET", "token_count": 691 }
103
fileFormatVersion: 2 guid: 43270a1ae7e8422458e49f6855475e8c folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/Fiber/Module/Actor.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Fiber/Module/Actor.meta", "repo_id": "ET", "token_count": 70 }
104
using System.Collections.Generic; namespace ET { [EntitySystemOf(typeof(CoroutineLockQueueType))] [FriendOf(typeof(CoroutineLockQueueType))] public static partial class CoroutineLockQueueTypeSystem { [EntitySystem] private static void Awake(this CoroutineLockQueueType self) { } public static CoroutineLockQueue Get(this CoroutineLockQueueType self, long key) { return self.GetChild<CoroutineLockQueue>(key); } public static CoroutineLockQueue New(this CoroutineLockQueueType self, long key) { CoroutineLockQueue queue = self.AddChildWithId<CoroutineLockQueue, int>(key, (int)self.Id, true); return queue; } public static void Remove(this CoroutineLockQueueType self, long key) { self.RemoveChild(key); } public static async ETTask<CoroutineLock> Wait(this CoroutineLockQueueType self, long key, int time) { CoroutineLockQueue queue = self.Get(key) ?? self.New(key); return await queue.Wait(time); } public static void Notify(this CoroutineLockQueueType self, long key, int level) { CoroutineLockQueue queue = self.Get(key); if (queue == null) { return; } if (!queue.Notify(level)) { self.Remove(key); } } } [ChildOf(typeof(CoroutineLockComponent))] public class CoroutineLockQueueType: Entity, IAwake { } }
ET/Unity/Assets/Scripts/Core/Fiber/Module/CoroutineLock/CoroutineLockQueueType.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Fiber/Module/CoroutineLock/CoroutineLockQueueType.cs", "repo_id": "ET", "token_count": 729 }
105
fileFormatVersion: 2 guid: c919506426bb2ee4bb9fc54ace00b98a MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/HashSetComponent.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/HashSetComponent.cs.meta", "repo_id": "ET", "token_count": 93 }
106
namespace ET { public static class ObjectHelper { public static void Swap<T>(ref T t1, ref T t2) { (t1, t2) = (t2, t1); } } }
ET/Unity/Assets/Scripts/Core/Helper/ObjectHelper.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Helper/ObjectHelper.cs", "repo_id": "ET", "token_count": 70 }
107
fileFormatVersion: 2 guid: 653a223bbff127d49baf78f578fd1e80 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/Method.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Method.meta", "repo_id": "ET", "token_count": 68 }
108
using System; using System.Collections.Generic; using System.IO; namespace ET { public class CircularBuffer: Stream { public int ChunkSize = 8192; private readonly Queue<byte[]> bufferQueue = new Queue<byte[]>(); private readonly Queue<byte[]> bufferCache = new Queue<byte[]>(); public int LastIndex { get; set; } public int FirstIndex { get; set; } private byte[] lastBuffer; public CircularBuffer() { this.AddLast(); } public override long Length { get { int c = 0; if (this.bufferQueue.Count == 0) { c = 0; } else { c = (this.bufferQueue.Count - 1) * ChunkSize + this.LastIndex - this.FirstIndex; } if (c < 0) { Log.Error("CircularBuffer count < 0: {0}, {1}, {2}".Fmt(this.bufferQueue.Count, this.LastIndex, this.FirstIndex)); } return c; } } public void AddLast() { byte[] buffer; if (this.bufferCache.Count > 0) { buffer = this.bufferCache.Dequeue(); } else { buffer = new byte[ChunkSize]; } this.bufferQueue.Enqueue(buffer); this.lastBuffer = buffer; } public void RemoveFirst() { this.bufferCache.Enqueue(bufferQueue.Dequeue()); } public byte[] First { get { if (this.bufferQueue.Count == 0) { this.AddLast(); } return this.bufferQueue.Peek(); } } public byte[] Last { get { if (this.bufferQueue.Count == 0) { this.AddLast(); } return this.lastBuffer; } } /// <summary> /// 从CircularBuffer读到stream中 /// </summary> /// <param name="stream"></param> /// <returns></returns> //public async ETTask ReadAsync(Stream stream) //{ // long buffLength = this.Length; // int sendSize = this.ChunkSize - this.FirstIndex; // if (sendSize > buffLength) // { // sendSize = (int)buffLength; // } // // await stream.WriteAsync(this.First, this.FirstIndex, sendSize); // // this.FirstIndex += sendSize; // if (this.FirstIndex == this.ChunkSize) // { // this.FirstIndex = 0; // this.RemoveFirst(); // } //} // 从CircularBuffer读到stream public void Read(Stream stream, int count) { if (count > this.Length) { throw new Exception($"bufferList length < count, {Length} {count}"); } int alreadyCopyCount = 0; while (alreadyCopyCount < count) { int n = count - alreadyCopyCount; if (ChunkSize - this.FirstIndex > n) { stream.Write(this.First, this.FirstIndex, n); this.FirstIndex += n; alreadyCopyCount += n; } else { stream.Write(this.First, this.FirstIndex, ChunkSize - this.FirstIndex); alreadyCopyCount += ChunkSize - this.FirstIndex; this.FirstIndex = 0; this.RemoveFirst(); } } } // 从stream写入CircularBuffer public void Write(Stream stream) { int count = (int)(stream.Length - stream.Position); int alreadyCopyCount = 0; while (alreadyCopyCount < count) { if (this.LastIndex == ChunkSize) { this.AddLast(); this.LastIndex = 0; } int n = count - alreadyCopyCount; if (ChunkSize - this.LastIndex > n) { stream.Read(this.lastBuffer, this.LastIndex, n); this.LastIndex += count - alreadyCopyCount; alreadyCopyCount += n; } else { stream.Read(this.lastBuffer, this.LastIndex, ChunkSize - this.LastIndex); alreadyCopyCount += ChunkSize - this.LastIndex; this.LastIndex = ChunkSize; } } } /// <summary> /// 从stream写入CircularBuffer /// </summary> /// <param name="stream"></param> /// <returns></returns> //public async ETTask<int> WriteAsync(Stream stream) //{ // int size = this.ChunkSize - this.LastIndex; // // int n = await stream.ReadAsync(this.Last, this.LastIndex, size); // // if (n == 0) // { // return 0; // } // // this.LastIndex += n; // // if (this.LastIndex == this.ChunkSize) // { // this.AddLast(); // this.LastIndex = 0; // } // // return n; //} // 把CircularBuffer中数据写入buffer public override int Read(byte[] buffer, int offset, int count) { if (buffer.Length < offset + count) { throw new Exception($"bufferList length < coutn, buffer length: {buffer.Length} {offset} {count}"); } long length = this.Length; if (length < count) { count = (int)length; } int alreadyCopyCount = 0; while (alreadyCopyCount < count) { int n = count - alreadyCopyCount; if (ChunkSize - this.FirstIndex > n) { Array.Copy(this.First, this.FirstIndex, buffer, alreadyCopyCount + offset, n); this.FirstIndex += n; alreadyCopyCount += n; } else { Array.Copy(this.First, this.FirstIndex, buffer, alreadyCopyCount + offset, ChunkSize - this.FirstIndex); alreadyCopyCount += ChunkSize - this.FirstIndex; this.FirstIndex = 0; this.RemoveFirst(); } } return count; } // 把buffer写入CircularBuffer中 public override void Write(byte[] buffer, int offset, int count) { int alreadyCopyCount = 0; while (alreadyCopyCount < count) { if (this.LastIndex == ChunkSize) { this.AddLast(); this.LastIndex = 0; } int n = count - alreadyCopyCount; if (ChunkSize - this.LastIndex > n) { Array.Copy(buffer, alreadyCopyCount + offset, this.lastBuffer, this.LastIndex, n); this.LastIndex += count - alreadyCopyCount; alreadyCopyCount += n; } else { Array.Copy(buffer, alreadyCopyCount + offset, this.lastBuffer, this.LastIndex, ChunkSize - this.LastIndex); alreadyCopyCount += ChunkSize - this.LastIndex; this.LastIndex = ChunkSize; } } } public override void Flush() { throw new NotImplementedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Position { get; set; } } }
ET/Unity/Assets/Scripts/Core/Network/Circularbuffer.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Network/Circularbuffer.cs", "repo_id": "ET", "token_count": 4010 }
109
namespace ET { public class MessageAttribute: BaseAttribute { public ushort Opcode { get; } public MessageAttribute(ushort opcode = 0) { this.Opcode = opcode; } } }
ET/Unity/Assets/Scripts/Core/Network/MessageAttribute.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Network/MessageAttribute.cs", "repo_id": "ET", "token_count": 134 }
110
using System; namespace ET { /// <summary> /// RPC异常,带ErrorCode /// </summary> public class RpcException: Exception { public int Error { get; } public RpcException(int error, string message): base(message) { this.Error = error; } public override string ToString() { return $"Error: {this.Error}\n{base.ToString()}"; } } }
ET/Unity/Assets/Scripts/Core/Network/RpcException.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Network/RpcException.cs", "repo_id": "ET", "token_count": 232 }
111
fileFormatVersion: 2 guid: 9a2882ec78c6c471e8e74005e51f985f MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/Object/MessageObject.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/Object/MessageObject.cs.meta", "repo_id": "ET", "token_count": 95 }
112
using System; using System.Collections.Concurrent; using System.Threading; namespace ET { public class ThreadSynchronizationContext : SynchronizationContext { // 线程同步队列,发送接收socket回调都放到该队列,由poll线程统一执行 private readonly ConcurrentQueue<Action> queue = new(); private Action a; public void Update() { while (true) { if (!this.queue.TryDequeue(out a)) { return; } try { a(); } catch (Exception e) { Log.Error(e); } } } public override void Post(SendOrPostCallback callback, object state) { this.Post(() => callback(state)); } public void Post(Action action) { this.queue.Enqueue(action); } } }
ET/Unity/Assets/Scripts/Core/ThreadSynchronizationContext.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/ThreadSynchronizationContext.cs", "repo_id": "ET", "token_count": 594 }
113
fileFormatVersion: 2 guid: 395a79eb78315e84e92fde7209c84fda folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/World/Module/Actor.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/World/Module/Actor.meta", "repo_id": "ET", "token_count": 68 }
114
fileFormatVersion: 2 guid: fdea67585847303418ec523256daa007 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/World/Module/Config.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/World/Module/Config.meta", "repo_id": "ET", "token_count": 66 }
115
using System; namespace ET { public interface IEvent { Type Type { get; } } public abstract class AEvent<S, A>: IEvent where S: class, IScene where A: struct { public Type Type { get { return typeof (A); } } protected abstract ETTask Run(S scene, A a); public async ETTask Handle(S scene, A a) { try { await Run(scene, a); } catch (Exception e) { Log.Error(e); } } } }
ET/Unity/Assets/Scripts/Core/World/Module/EventSystem/IEvent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/World/Module/EventSystem/IEvent.cs", "repo_id": "ET", "token_count": 206 }
116
fileFormatVersion: 2 guid: bfdee72346bcdc149b84d5348ba2e350 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Core/World/Module/Log/NLogger.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Core/World/Module/Log/NLogger.cs.meta", "repo_id": "ET", "token_count": 94 }
117
using System.IO; using UnityEditor; using UnityEngine; namespace ET { public static class AssemblyEditor { [InitializeOnLoadMethod] static void Initialize() { EditorApplication.playModeStateChanged += change => { switch (change) { case PlayModeStateChange.ExitingEditMode: { OnExitingEditMode(); break; } case PlayModeStateChange.ExitingPlayMode: { OnExitingPlayMode(); break; } } }; } /// <summary> /// 退出编辑模式时处理(即将进入运行模式) /// EnableDll模式时, 屏蔽掉Library的dll(通过改文件后缀方式屏蔽), 仅使用Define.CodeDir下的dll /// </summary> static void OnExitingEditMode() { GlobalConfig globalConfig = Resources.Load<GlobalConfig>("GlobalConfig"); if (!globalConfig.EnableDll) { return; } foreach (string dll in AssemblyTool.DllNames) { string dllFile = $"{Application.dataPath}/../Library/ScriptAssemblies/{dll}.dll"; if (File.Exists(dllFile)) { string dllDisableFile = $"{Application.dataPath}/../Library/ScriptAssemblies/{dll}.dll.DISABLE"; if (File.Exists(dllDisableFile)) { File.Delete(dllDisableFile); } File.Move(dllFile, dllDisableFile); } string pdbFile = $"{Application.dataPath}/../Library/ScriptAssemblies/{dll}.pdb"; if (File.Exists(pdbFile)) { string pdbDisableFile = $"{Application.dataPath}/../Library/ScriptAssemblies/{dll}.pdb.DISABLE"; if (File.Exists(pdbDisableFile)) { File.Delete(pdbDisableFile); } File.Move(pdbFile, pdbDisableFile); } } } /// <summary> /// 退出运行模式时处理(即将进入编辑模式) /// 还原Library里面屏蔽掉的dll(HybridCLR或者非EnableDll模式都会用到这个目录下的dll, 故需要还原) /// </summary> static void OnExitingPlayMode() { foreach (string dll in AssemblyTool.DllNames) { string dllDisableFile = $"{Application.dataPath}/../Library/ScriptAssemblies/{dll}.dll.DISABLE"; if (File.Exists(dllDisableFile)) { string dllFile = $"{Application.dataPath}/../Library/ScriptAssemblies/{dll}.dll"; if (File.Exists(dllFile)) { File.Delete(dllDisableFile); } else { File.Move(dllDisableFile, dllFile); } } string pdbDisableFile = $"{Application.dataPath}/../Library/ScriptAssemblies/{dll}.pdb.DISABLE"; if (File.Exists(pdbDisableFile)) { string pdbFile = $"{Application.dataPath}/../Library/ScriptAssemblies/{dll}.pdb"; if (File.Exists(pdbFile)) { File.Delete(pdbDisableFile); } else { File.Move(pdbDisableFile, pdbFile); } } } } } }
ET/Unity/Assets/Scripts/Editor/Assembly/AssemblyEditor.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/Assembly/AssemblyEditor.cs", "repo_id": "ET", "token_count": 2328 }
118
using System; using UnityEditor; namespace ET { [TypeDrawer] public class DoubleTypeDrawer: ITypeDrawer { public bool HandlesType(Type type) { return type == typeof (double); } public object DrawAndGetNewValue(Type memberType, string memberName, object value, object target) { return EditorGUILayout.DoubleField(memberName, (double) value); } } }
ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/DoubleTypeDrawer.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/DoubleTypeDrawer.cs", "repo_id": "ET", "token_count": 184 }
119
using System; using UnityEditor; namespace ET { [TypeDrawer] public class IntTypeDrawer: ITypeDrawer { [TypeDrawer] public bool HandlesType(Type type) { return type == typeof (int); } public object DrawAndGetNewValue(Type memberType, string memberName, object value, object target) { return EditorGUILayout.IntField(memberName, (int) value); } } }
ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/IntTypeDrawer.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/IntTypeDrawer.cs", "repo_id": "ET", "token_count": 197 }
120
using System; using UnityEditor; using UnityEngine; namespace ET { [TypeDrawer] public class Vector4TypeDrawer: ITypeDrawer { public bool HandlesType(Type type) { return type == typeof (Vector4); } public object DrawAndGetNewValue(Type memberType, string memberName, object value, object target) { return EditorGUILayout.Vector4Field(memberName, (Vector4) value); } } }
ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/Vector4TypeDrawer.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/Vector4TypeDrawer.cs", "repo_id": "ET", "token_count": 193 }
121
fileFormatVersion: 2 guid: 3be1c35d4fd53dd479a81cadf627f263 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Editor/LogRedirection.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/LogRedirection.meta", "repo_id": "ET", "token_count": 69 }
122
using System; using System.Collections.Generic; using UnityEditor; using UnityEngine; //Object并非C#基础中的Object,而是 UnityEngine.Object using Object = UnityEngine.Object; //自定义ReferenceCollector类在界面中的显示与功能 [CustomEditor(typeof (ReferenceCollector))] public class ReferenceCollectorEditor: Editor { //输入在textfield中的字符串 private string searchKey { get { return _searchKey; } set { if (_searchKey != value) { _searchKey = value; heroPrefab = referenceCollector.Get<Object>(searchKey); } } } private ReferenceCollector referenceCollector; private Object heroPrefab; private string _searchKey = ""; private void DelNullReference() { var dataProperty = serializedObject.FindProperty("data"); for (int i = dataProperty.arraySize - 1; i >= 0; i--) { var gameObjectProperty = dataProperty.GetArrayElementAtIndex(i).FindPropertyRelative("gameObject"); if (gameObjectProperty.objectReferenceValue == null) { dataProperty.DeleteArrayElementAtIndex(i); EditorUtility.SetDirty(referenceCollector); serializedObject.ApplyModifiedProperties(); serializedObject.UpdateIfRequiredOrScript(); } } } private void OnEnable() { //将被选中的gameobject所挂载的ReferenceCollector赋值给编辑器类中的ReferenceCollector,方便操作 referenceCollector = (ReferenceCollector) target; } public override void OnInspectorGUI() { //使ReferenceCollector支持撤销操作,还有Redo,不过没有在这里使用 Undo.RecordObject(referenceCollector, "Changed Settings"); var dataProperty = serializedObject.FindProperty("data"); //开始水平布局,如果是比较新版本学习U3D的,可能不知道这东西,这个是老GUI系统的知识,除了用在编辑器里,还可以用在生成的游戏中 GUILayout.BeginHorizontal(); //下面几个if都是点击按钮就会返回true调用里面的东西 if (GUILayout.Button("添加引用")) { //添加新的元素,具体的函数注释 // Guid.NewGuid().GetHashCode().ToString() 就是新建后默认的key AddReference(dataProperty, Guid.NewGuid().GetHashCode().ToString(), null); } if (GUILayout.Button("全部删除")) { referenceCollector.Clear(); } if (GUILayout.Button("删除空引用")) { DelNullReference(); } if (GUILayout.Button("排序")) { referenceCollector.Sort(); } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); //可以在编辑器中对searchKey进行赋值,只要输入对应的Key值,就可以点后面的删除按钮删除相对应的元素 searchKey = EditorGUILayout.TextField(searchKey); //添加的可以用于选中Object的框,这里的object也是(UnityEngine.Object //第三个参数为是否只能引用scene中的Object EditorGUILayout.ObjectField(heroPrefab, typeof (Object), false); if (GUILayout.Button("删除")) { referenceCollector.Remove(searchKey); heroPrefab = null; } GUILayout.EndHorizontal(); EditorGUILayout.Space(); var delList = new List<int>(); SerializedProperty property; //遍历ReferenceCollector中data list的所有元素,显示在编辑器中 for (int i = referenceCollector.data.Count - 1; i >= 0; i--) { GUILayout.BeginHorizontal(); //这里的知识点在ReferenceCollector中有说 property = dataProperty.GetArrayElementAtIndex(i).FindPropertyRelative("key"); property.stringValue = EditorGUILayout.TextField(property.stringValue, GUILayout.Width(150)); property = dataProperty.GetArrayElementAtIndex(i).FindPropertyRelative("gameObject"); property.objectReferenceValue = EditorGUILayout.ObjectField(property.objectReferenceValue, typeof(Object), true); if (GUILayout.Button("X")) { //将元素添加进删除list delList.Add(i); } GUILayout.EndHorizontal(); } var eventType = Event.current.type; //在Inspector 窗口上创建区域,向区域拖拽资源对象,获取到拖拽到区域的对象 if (eventType == EventType.DragUpdated || eventType == EventType.DragPerform) { // Show a copy icon on the drag DragAndDrop.visualMode = DragAndDropVisualMode.Copy; if (eventType == EventType.DragPerform) { DragAndDrop.AcceptDrag(); foreach (var o in DragAndDrop.objectReferences) { AddReference(dataProperty, o.name, o); } } Event.current.Use(); } //遍历删除list,将其删除掉 foreach (var i in delList) { dataProperty.DeleteArrayElementAtIndex(i); } serializedObject.ApplyModifiedProperties(); serializedObject.UpdateIfRequiredOrScript(); } //添加元素,具体知识点在ReferenceCollector中说了 private void AddReference(SerializedProperty dataProperty, string key, Object obj) { int index = dataProperty.arraySize; dataProperty.InsertArrayElementAtIndex(index); var element = dataProperty.GetArrayElementAtIndex(index); element.FindPropertyRelative("key").stringValue = key; element.FindPropertyRelative("gameObject").objectReferenceValue = obj; } }
ET/Unity/Assets/Scripts/Editor/ReferenceCollectorEditor/ReferenceCollectorEditor.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/ReferenceCollectorEditor/ReferenceCollectorEditor.cs", "repo_id": "ET", "token_count": 2375 }
123
using Unity.Mathematics; namespace ET.Client { public class AI_XunLuo: AAIHandler { public override int Check(AIComponent aiComponent, AIConfig aiConfig) { long sec = TimeInfo.Instance.ClientNow() / 1000 % 15; if (sec < 10) { return 0; } return 1; } public override async ETTask Execute(AIComponent aiComponent, AIConfig aiConfig, ETCancellationToken cancellationToken) { Scene root = aiComponent.Root(); Unit myUnit = UnitHelper.GetMyUnitFromClientScene(root); if (myUnit == null) { return; } Log.Debug("开始巡逻"); while (true) { XunLuoPathComponent xunLuoPathComponent = myUnit.GetComponent<XunLuoPathComponent>(); float3 nextTarget = xunLuoPathComponent.GetCurrent(); await myUnit.MoveToAsync(nextTarget, cancellationToken); if (cancellationToken.IsCancel()) { return; } xunLuoPathComponent.MoveNext(); } } } }
ET/Unity/Assets/Scripts/Hotfix/Client/Demo/AI/AI_XunLuo.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Demo/AI/AI_XunLuo.cs", "repo_id": "ET", "token_count": 662 }
124
fileFormatVersion: 2 guid: 9517a733443387b49a227cfb10aa82d6 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Client/Demo/Main/Move/MoveHelper.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Demo/Main/Move/MoveHelper.cs.meta", "repo_id": "ET", "token_count": 93 }
125
fileFormatVersion: 2 guid: 6c4d413c1206d8844b7f6ccc95dd2ce6 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Client/Demo/Main/Unit/M2C_RemoveUnitsHandler.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Demo/Main/Unit/M2C_RemoveUnitsHandler.cs.meta", "repo_id": "ET", "token_count": 97 }
126
fileFormatVersion: 2 guid: 657f5f7736369e24786203c1c377ec14 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Client/Demo/NetClient/Ping.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Demo/NetClient/Ping.meta", "repo_id": "ET", "token_count": 68 }
127
fileFormatVersion: 2 guid: 38ab027e1bcebae4992db7e8e2552667 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/EntryEvent2_InitServer.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/EntryEvent2_InitServer.cs.meta", "repo_id": "ET", "token_count": 94 }
128
using System; namespace ET.Server { [Invoke((long)SceneType.Gate)] public class NetComponentOnReadInvoker_Gate: AInvokeHandler<NetComponentOnRead> { public override void Handle(NetComponentOnRead args) { HandleAsync(args).Coroutine(); } private async ETTask HandleAsync(NetComponentOnRead args) { Session session = args.Session; object message = args.Message; Scene root = args.Session.Root(); // 根据消息接口判断是不是Actor消息,不同的接口做不同的处理,比如需要转发给Chat Scene,可以做一个IChatMessage接口 switch (message) { case ISessionMessage: { MessageSessionDispatcher.Instance.Handle(session, message); break; } case FrameMessage frameMessage: { Player player = session.GetComponent<SessionPlayerComponent>().Player; ActorId roomActorId = player.GetComponent<PlayerRoomComponent>().RoomActorId; frameMessage.PlayerId = player.Id; root.GetComponent<MessageSender>().Send(roomActorId, frameMessage); break; } case IRoomMessage actorRoom: { Player player = session.GetComponent<SessionPlayerComponent>().Player; ActorId roomActorId = player.GetComponent<PlayerRoomComponent>().RoomActorId; actorRoom.PlayerId = player.Id; root.GetComponent<MessageSender>().Send(roomActorId, actorRoom); break; } case ILocationMessage actorLocationMessage: { long unitId = session.GetComponent<SessionPlayerComponent>().Player.Id; root.GetComponent<MessageLocationSenderComponent>().Get(LocationType.Unit).Send(unitId, actorLocationMessage); break; } case ILocationRequest actorLocationRequest: // gate session收到actor rpc消息,先向actor 发送rpc请求,再将请求结果返回客户端 { long unitId = session.GetComponent<SessionPlayerComponent>().Player.Id; int rpcId = actorLocationRequest.RpcId; // 这里要保存客户端的rpcId long instanceId = session.InstanceId; IResponse iResponse = await root.GetComponent<MessageLocationSenderComponent>().Get(LocationType.Unit).Call(unitId, actorLocationRequest); iResponse.RpcId = rpcId; // session可能已经断开了,所以这里需要判断 if (session.InstanceId == instanceId) { session.Send(iResponse); } break; } case IRequest actorRequest: // 分发IActorRequest消息,目前没有用到,需要的自己添加 { break; } case IMessage actorMessage: // 分发IActorMessage消息,目前没有用到,需要的自己添加 { break; } default: { throw new Exception($"not found handler: {message}"); } } } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Gate/NetComponentOnReadInvoker_Gate.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Gate/NetComponentOnReadInvoker_Gate.cs", "repo_id": "ET", "token_count": 1954 }
129
using System; namespace ET.Server { [MessageLocationHandler(SceneType.Map)] public class C2M_TestRobotCaseHandler : MessageLocationHandler<Unit, C2M_TestRobotCase, M2C_TestRobotCase> { protected override async ETTask Run(Unit unit, C2M_TestRobotCase request, M2C_TestRobotCase response) { response.N = request.N; await ETTask.CompletedTask; } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Map/C2M_TestRobotCaseHandler.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Map/C2M_TestRobotCaseHandler.cs", "repo_id": "ET", "token_count": 138 }
130
using System; using Unity.Mathematics; namespace ET.Server { [MessageHandler(SceneType.Map)] public class M2M_UnitTransferRequestHandler: MessageHandler<Scene, M2M_UnitTransferRequest, M2M_UnitTransferResponse> { protected override async ETTask Run(Scene scene, M2M_UnitTransferRequest request, M2M_UnitTransferResponse response) { UnitComponent unitComponent = scene.GetComponent<UnitComponent>(); Unit unit = MongoHelper.Deserialize<Unit>(request.Unit); unitComponent.AddChild(unit); unitComponent.Add(unit); foreach (byte[] bytes in request.Entitys) { Entity entity = MongoHelper.Deserialize<Entity>(bytes); unit.AddComponent(entity); } unit.AddComponent<MoveComponent>(); unit.AddComponent<PathfindingComponent, string>(scene.Name); unit.Position = new float3(-10, 0, -10); unit.AddComponent<MailBoxComponent, MailBoxType>(MailBoxType.OrderedMessage); // 通知客户端开始切场景 M2C_StartSceneChange m2CStartSceneChange = M2C_StartSceneChange.Create(); m2CStartSceneChange.SceneInstanceId = scene.InstanceId; m2CStartSceneChange.SceneName = scene.Name; MapMessageHelper.SendToClient(unit, m2CStartSceneChange); // 通知客户端创建My Unit M2C_CreateMyUnit m2CCreateUnits = M2C_CreateMyUnit.Create(); m2CCreateUnits.Unit = UnitHelper.CreateUnitInfo(unit); MapMessageHelper.SendToClient(unit, m2CCreateUnits); // 加入aoi unit.AddComponent<AOIEntity, int, float3>(9 * 1000, unit.Position); // 解锁location,可以接收发给Unit的消息 await scene.Root().GetComponent<LocationProxyComponent>().UnLock(LocationType.Unit, unit.Id, request.OldActorId, unit.GetActorId()); } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Map/Transfer/M2M_UnitTransferRequestHandler.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Map/Transfer/M2M_UnitTransferRequestHandler.cs", "repo_id": "ET", "token_count": 878 }
131
using System.Net; namespace ET.Server { [Invoke((long)SceneType.Realm)] public class FiberInit_Realm: AInvokeHandler<FiberInit, ETTask> { public override async ETTask Handle(FiberInit fiberInit) { Scene root = fiberInit.Fiber.Root; root.AddComponent<MailBoxComponent, MailBoxType>(MailBoxType.UnOrderedMessage); root.AddComponent<TimerComponent>(); root.AddComponent<CoroutineLockComponent>(); root.AddComponent<ProcessInnerSender>(); root.AddComponent<MessageSender>(); StartSceneConfig startSceneConfig = StartSceneConfigCategory.Instance.Get(root.Fiber.Id); root.AddComponent<NetComponent, IPEndPoint, NetworkProtocol>(startSceneConfig.InnerIPPort, NetworkProtocol.UDP); await ETTask.CompletedTask; } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Realm/FiberInit_Realm.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Realm/FiberInit_Realm.cs", "repo_id": "ET", "token_count": 353 }
132
fileFormatVersion: 2 guid: ea87d2f8e44c2ad40b21b8104d9176de MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Robot/RobotManagerComponentSystem.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Robot/RobotManagerComponentSystem.cs.meta", "repo_id": "ET", "token_count": 97 }
133
fileFormatVersion: 2 guid: a86d2aec3f36c405fa581cf362886820 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Map.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Map.meta", "repo_id": "ET", "token_count": 68 }
134
using System; namespace ET.Server { [MessageHandler(SceneType.Match)] public class G2Match_MatchHandler : MessageHandler<Scene, G2Match_Match, Match2G_Match> { protected override async ETTask Run(Scene scene, G2Match_Match request, Match2G_Match response) { MatchComponent matchComponent = scene.GetComponent<MatchComponent>(); matchComponent.Match(request.Id).Coroutine(); await ETTask.CompletedTask; } } }
ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Match/G2Match_MatchHandler.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Match/G2Match_MatchHandler.cs", "repo_id": "ET", "token_count": 143 }
135
fileFormatVersion: 2 guid: 663974eab9143cd4aa7740221e48e4f2 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/Module/AOI.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Module/AOI.meta", "repo_id": "ET", "token_count": 69 }
136
using System; namespace ET.Server { public static partial class LocationProxyComponentSystem { private static ActorId GetLocationSceneId(long key) { return StartSceneConfigCategory.Instance.LocationConfig.ActorId; } public static async ETTask Add(this LocationProxyComponent self, int type, long key, ActorId actorId) { Fiber fiber = self.Fiber(); Log.Info($"location proxy add {key}, {actorId} {TimeInfo.Instance.ServerNow()}"); ObjectAddRequest objectAddRequest = ObjectAddRequest.Create(); objectAddRequest.Type = type; objectAddRequest.Key = key; objectAddRequest.ActorId = actorId; await fiber.Root.GetComponent<MessageSender>().Call(GetLocationSceneId(key), objectAddRequest); } public static async ETTask Lock(this LocationProxyComponent self, int type, long key, ActorId actorId, int time = 60000) { Fiber fiber = self.Fiber(); Log.Info($"location proxy lock {key}, {actorId} {TimeInfo.Instance.ServerNow()}"); ObjectLockRequest objectLockRequest = ObjectLockRequest.Create(); objectLockRequest.Type = type; objectLockRequest.Key = key; objectLockRequest.ActorId = actorId; objectLockRequest.Time = time; await fiber.Root.GetComponent<MessageSender>().Call(GetLocationSceneId(key), objectLockRequest); } public static async ETTask UnLock(this LocationProxyComponent self, int type, long key, ActorId oldActorId, ActorId newActorId) { Fiber fiber = self.Fiber(); Log.Info($"location proxy unlock {key}, {newActorId} {TimeInfo.Instance.ServerNow()}"); ObjectUnLockRequest objectUnLockRequest = ObjectUnLockRequest.Create(); objectUnLockRequest.Type = type; objectUnLockRequest.Key = key; objectUnLockRequest.OldActorId = oldActorId; objectUnLockRequest.NewActorId = newActorId; await fiber.Root.GetComponent<MessageSender>().Call(GetLocationSceneId(key), objectUnLockRequest); } public static async ETTask Remove(this LocationProxyComponent self, int type, long key) { Fiber fiber = self.Fiber(); Log.Info($"location proxy remove {key}, {TimeInfo.Instance.ServerNow()}"); ObjectRemoveRequest objectRemoveRequest = ObjectRemoveRequest.Create(); objectRemoveRequest.Type = type; objectRemoveRequest.Key = key; await fiber.Root.GetComponent<MessageSender>().Call(GetLocationSceneId(key), objectRemoveRequest); } public static async ETTask<ActorId> Get(this LocationProxyComponent self, int type, long key) { if (key == 0) { throw new Exception($"get location key 0"); } // location server配置到共享区,一个大战区可以配置N多个location server,这里暂时为1 ObjectGetRequest objectGetRequest = ObjectGetRequest.Create(); objectGetRequest.Type = type; objectGetRequest.Key = key; ObjectGetResponse response = (ObjectGetResponse) await self.Root().GetComponent<MessageSender>().Call(GetLocationSceneId(key), objectGetRequest); return response.ActorId; } public static async ETTask AddLocation(this Entity self, int type) { await self.Root().GetComponent<LocationProxyComponent>().Add(type, self.Id, self.GetActorId()); } public static async ETTask RemoveLocation(this Entity self, int type) { await self.Root().GetComponent<LocationProxyComponent>().Remove(type, self.Id); } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Module/ActorLocation/LocationProxyComponentSystem.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Module/ActorLocation/LocationProxyComponentSystem.cs", "repo_id": "ET", "token_count": 1567 }
137
using System; namespace ET.Server { [MessageHandler(SceneType.Location)] public class ObjectUnLockRequestHandler: MessageHandler<Scene, ObjectUnLockRequest, ObjectUnLockResponse> { protected override async ETTask Run(Scene scene, ObjectUnLockRequest request, ObjectUnLockResponse response) { scene.GetComponent<LocationManagerComoponent>().Get(request.Type).UnLock(request.Key, request.OldActorId, request.NewActorId); await ETTask.CompletedTask; } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Module/ActorLocation/ObjectUnLockRequestHandler.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Module/ActorLocation/ObjectUnLockRequestHandler.cs", "repo_id": "ET", "token_count": 183 }
138
fileFormatVersion: 2 guid: eabf7791ed07a864b814f3f85914930c MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/Module/Message/MessageSenderSystem.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Module/Message/MessageSenderSystem.cs.meta", "repo_id": "ET", "token_count": 95 }
139
using System; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; namespace ET.Server { [EntitySystemOf(typeof(RouterComponent))] [FriendOf(typeof (RouterComponent))] [FriendOf(typeof (RouterNode))] public static partial class RouterComponentSystem { [EntitySystem] private static void Awake(this RouterComponent self, IPEndPoint outerAddress, string innerIP) { self.OuterUdp = new UdpTransport(outerAddress); self.OuterTcp = new TcpTransport(outerAddress); self.InnerSocket = new UdpTransport(new IPEndPoint(IPAddress.Parse(innerIP), 0)); } [EntitySystem] private static void Destroy(this RouterComponent self) { self.OuterUdp.Dispose(); self.OuterTcp.Dispose(); self.InnerSocket.Dispose(); self.IPEndPoint = null; } [EntitySystem] private static void Update(this RouterComponent self) { self.OuterUdp.Update(); self.OuterTcp.Update(); self.InnerSocket.Update(); long timeNow = TimeInfo.Instance.ClientNow(); self.RecvOuterUdp(timeNow); self.RecvOuterTcp(timeNow); self.RecvInner(timeNow); // 每秒钟检查一次 if (timeNow - self.LastCheckTime > 1000) { self.CheckConnectTimeout(timeNow); self.LastCheckTime = timeNow; } } private static IPEndPoint CloneAddress(this RouterComponent self) { IPEndPoint ipEndPoint = (IPEndPoint) self.IPEndPoint; return new IPEndPoint(ipEndPoint.Address, ipEndPoint.Port); } // 接收tcp消息 private static void RecvOuterTcp(this RouterComponent self, long timeNow) { while (self.OuterTcp != null && self.OuterTcp.Available() > 0) { try { int messageLength = self.OuterTcp.Recv(self.Cache, ref self.IPEndPoint); self.RecvOuterHandler(messageLength, timeNow, self.OuterTcp); } catch (Exception e) { Log.Error(e); } } } // 接收udp消息 private static void RecvOuterUdp(this RouterComponent self, long timeNow) { while (self.OuterUdp != null && self.OuterUdp.Available() > 0) { try { int messageLength = self.OuterUdp.Recv(self.Cache, ref self.IPEndPoint); self.RecvOuterHandler(messageLength, timeNow, self.OuterUdp); } catch (Exception e) { Log.Error(e); } } } private static void CheckConnectTimeout(this RouterComponent self, long timeNow) { int n = self.checkTimeout.Count < 10? self.checkTimeout.Count : 10; for (int i = 0; i < n; ++i) { uint id = self.checkTimeout.Dequeue(); RouterNode node = self.GetChild<RouterNode>(id); if (node == null) { continue; } // 已经连接上了 switch (node.Status) { case RouterStatus.Sync: // 超时了 if (timeNow > node.LastRecvOuterTime + 10 * 1000) { self.OnError(id, ErrorCore.ERR_KcpRouterConnectFail); continue; } break; case RouterStatus.Msg: // 比session超时应该多10秒钟 if (timeNow > node.LastRecvOuterTime + ConstValue.SessionTimeoutTime + 10 * 1000) { self.OnError(id, ErrorCore.ERR_KcpRouterTimeout); continue; } break; default: throw new ArgumentOutOfRangeException(); } self.checkTimeout.Enqueue(id); } } private static void RecvInner(this RouterComponent self, long timeNow) { while (self.InnerSocket != null && self.InnerSocket.Available() > 0) { try { int messageLength = self.InnerSocket.Recv(self.Cache, ref self.IPEndPoint); self.RecvInnerHandler(messageLength, timeNow); } catch (Exception e) { Log.Error(e); } } } private static void RecvOuterHandler(this RouterComponent self, int messageLength, long timeNow, IKcpTransport transport) { // 长度小于1,不是正常的消息 if (messageLength < 1) { return; } // accept byte flag = self.Cache[0]; switch (flag) { case KcpProtocalType.RouterReconnectSYN: { if (messageLength < 13) { break; } uint outerConn = BitConverter.ToUInt32(self.Cache, 1); uint innerConn = BitConverter.ToUInt32(self.Cache, 5); uint connectId = BitConverter.ToUInt32(self.Cache, 9); string realAddress = self.Cache.ToStr(13, messageLength - 13); // RouterAck之后ConnectIdNodes会删除,加入到OuterNodes中来 RouterNode routerNode = self.GetChild<RouterNode>(outerConn); if (routerNode == null) { Log.Info($"router create reconnect: {self.IPEndPoint} {realAddress} {outerConn} {innerConn}"); routerNode = self.New(realAddress, outerConn, innerConn, connectId, self.CloneAddress()); } // 不是自己的,outerConn冲突, 直接break,也就是说这个软路由上有个跟自己outerConn冲突的连接,就不能连接了 // 这个路由连接不上,客户端会换个软路由,所以没关系 if (routerNode.InnerConn != innerConn) { Log.Warning($"kcp router router reconnect inner conn diff1: {routerNode.SyncIpEndPoint} {(IPEndPoint) self.IPEndPoint}"); break; } if (routerNode.OuterConn != outerConn) { Log.Warning($"kcp router router reconnect outer conn diff1: {routerNode.SyncIpEndPoint} {(IPEndPoint) self.IPEndPoint}"); break; } // reconnect检查了InnerConn跟OuterConn,到这里肯定保证了是同一客户端, 如果connectid不一样,证明是两次不同的连接,可以删除老的连接 if (routerNode.ConnectId != connectId) { Log.Warning($"kcp router router reconnect connectId diff, maybe router count too less: {connectId} {routerNode.ConnectId} {routerNode.SyncIpEndPoint} {(IPEndPoint) self.IPEndPoint}"); self.OnError(routerNode.Id, ErrorCore.ERR_KcpRouterSame); break; } // 校验内网地址 if (routerNode.InnerAddress != realAddress) { Log.Warning($"router sync error2: {routerNode.OuterConn} {routerNode.InnerAddress} {outerConn} {realAddress}"); break; } if (++routerNode.RouterSyncCount > 40) { self.OnError(routerNode.Id, ErrorCore.ERR_KcpRouterRouterSyncCountTooMuchTimes); break; } routerNode.KcpTransport = transport; // 转发到内网 self.Cache.WriteTo(0, KcpProtocalType.RouterReconnectSYN); self.Cache.WriteTo(1, outerConn); self.Cache.WriteTo(5, innerConn); self.InnerSocket.Send(self.Cache, 0, 9, routerNode.InnerIpEndPoint); if (!routerNode.CheckOuterCount(timeNow)) { self.OnError(routerNode.Id, ErrorCore.ERR_KcpRouterTooManyPackets); } break; } case KcpProtocalType.RouterSYN: { if (messageLength < 13) { break; } uint outerConn = BitConverter.ToUInt32(self.Cache, 1); uint innerConn = BitConverter.ToUInt32(self.Cache, 5); uint connectId = BitConverter.ToUInt32(self.Cache, 9); string realAddress = self.Cache.ToStr(13, messageLength - 13); // innerconn会在ack的时候赋值,所以routersync过程绝对是routerNode.InnerConn绝对是0 if (innerConn != 0) { Log.Warning($"kcp router syn status innerConn != 0: {outerConn} {innerConn}"); break; } RouterNode routerNode = self.GetChild<RouterNode>(outerConn); if (routerNode == null) { routerNode = self.New(realAddress, outerConn, innerConn, connectId, self.CloneAddress()); Log.Info($"router create: {realAddress} {outerConn} {innerConn} {routerNode.SyncIpEndPoint}"); } if (routerNode.Status != RouterStatus.Sync) { Log.Warning($"kcp router syn status error: {outerConn} {innerConn} {routerNode.InnerConn}"); break; } // innerconn会在ack的时候赋值,所以routersync过程绝对是routerNode.InnerConn绝对是0 if (routerNode.InnerConn != innerConn) { Log.Warning($"kcp router syn status InnerConn != 0: {outerConn} {innerConn} {routerNode.InnerConn}"); break; } if (++routerNode.RouterSyncCount > 40) { self.OnError(routerNode.Id, ErrorCore.ERR_KcpRouterRouterSyncCountTooMuchTimes); break; } // 这里可以注释,因增加了connectid的检查,第三方很难通过检查 // 校验ip,连接过程中ip不能变化 //if (!Equals(routerNode.SyncIpEndPoint, self.IPEndPoint)) //{ // Log.Warning($"kcp router syn ip is diff1: {routerNode.SyncIpEndPoint} {self.IPEndPoint}"); // break; //} // 这里因为InnerConn是0,无法保证连接是同一客户端发过来的,所以这里如果connectid不同,则break。注意逻辑跟reconnect不一样 if (routerNode.ConnectId != connectId) { Log.Warning($"kcp router router connect connectId diff, maybe router count too less: {connectId} {routerNode.ConnectId} {routerNode.SyncIpEndPoint} {(IPEndPoint) self.IPEndPoint}"); break; } // 校验内网地址 if (routerNode.InnerAddress != realAddress) { Log.Warning($"router sync error2: {routerNode.OuterConn} {routerNode.InnerAddress} {outerConn} {realAddress}"); break; } routerNode.KcpTransport = transport; self.Cache.WriteTo(0, KcpProtocalType.RouterACK); self.Cache.WriteTo(1, routerNode.InnerConn); self.Cache.WriteTo(5, routerNode.OuterConn); routerNode.KcpTransport.Send(self.Cache, 0, 9, routerNode.SyncIpEndPoint); if (!routerNode.CheckOuterCount(timeNow)) { self.OnError(routerNode.Id, ErrorCore.ERR_KcpRouterTooManyPackets); } break; } case KcpProtocalType.SYN: { // 长度!=13,不是accpet消息 if (messageLength != 9) { break; } uint outerConn = BitConverter.ToUInt32(self.Cache, 1); // remote uint innerConn = BitConverter.ToUInt32(self.Cache, 5); RouterNode routerNode = self.GetChild<RouterNode>(outerConn); if (routerNode == null) { Log.Warning($"kcp router syn not found outer nodes: {outerConn} {innerConn}"); break; } if (++routerNode.SyncCount > 20) { self.OnError(routerNode.Id, ErrorCore.ERR_KcpRouterSyncCountTooMuchTimes); break; } // 校验ip,连接过程中ip不能变化 IPEndPoint ipEndPoint = (IPEndPoint) self.IPEndPoint; if (!Equals(routerNode.SyncIpEndPoint.Address, ipEndPoint.Address)) { Log.Warning($"kcp router syn ip is diff3: {routerNode.SyncIpEndPoint.Address} {ipEndPoint.Address}"); break; } routerNode.KcpTransport = transport; routerNode.LastRecvOuterTime = timeNow; routerNode.OuterIpEndPoint = self.CloneAddress(); // 转发到内网, 带上客户端的地址 self.Cache.WriteTo(0, KcpProtocalType.SYN); self.Cache.WriteTo(1, outerConn); self.Cache.WriteTo(5, innerConn); byte[] addressBytes = ipEndPoint.ToString().ToByteArray(); Array.Copy(addressBytes, 0, self.Cache, 9, addressBytes.Length); Log.Info($"kcp router syn: {outerConn} {innerConn} {routerNode.InnerIpEndPoint} {routerNode.OuterIpEndPoint}"); self.InnerSocket.Send(self.Cache, 0, 9 + addressBytes.Length, routerNode.InnerIpEndPoint); if (!routerNode.CheckOuterCount(timeNow)) { self.OnError(routerNode.Id, ErrorCore.ERR_KcpRouterTooManyPackets); } break; } case KcpProtocalType.FIN: // 断开 { // 长度!=13,不是DisConnect消息 if (messageLength != 13) { break; } uint outerConn = BitConverter.ToUInt32(self.Cache, 1); uint innerConn = BitConverter.ToUInt32(self.Cache, 5); RouterNode routerNode = self.GetChild<RouterNode>(outerConn); if (routerNode == null) { Log.Warning($"kcp router outer fin not found outer nodes: {outerConn} {innerConn}"); break; } // 比对innerConn if (routerNode.InnerConn != innerConn) { Log.Warning($"router node innerConn error: {innerConn} {outerConn} {routerNode.Status}"); break; } routerNode.KcpTransport = transport; routerNode.LastRecvOuterTime = timeNow; Log.Info($"kcp router outer fin: {outerConn} {innerConn} {routerNode.InnerIpEndPoint}"); self.InnerSocket.Send(self.Cache, 0, messageLength, routerNode.InnerIpEndPoint); if (!routerNode.CheckOuterCount(timeNow)) { self.OnError(routerNode.Id, ErrorCore.ERR_KcpRouterTooManyPackets); } break; } case KcpProtocalType.MSG: { // 长度<9,不是Msg消息 if (messageLength < 9) { break; } // 处理chanel uint outerConn = BitConverter.ToUInt32(self.Cache, 1); // remote uint innerConn = BitConverter.ToUInt32(self.Cache, 5); // local RouterNode routerNode = self.GetChild<RouterNode>(outerConn); if (routerNode == null) { Log.Warning($"kcp router msg not found outer nodes: {outerConn} {innerConn}"); break; } if (routerNode.Status != RouterStatus.Msg) { Log.Warning($"router node status error: {innerConn} {outerConn} {routerNode.Status}"); break; } // 比对innerConn if (routerNode.InnerConn != innerConn) { Log.Warning($"router node innerConn error: {innerConn} {outerConn} {routerNode.Status}"); break; } // 重连的时候,没有经过syn阶段,可能没有设置OuterIpEndPoint,重连请求Router的Socket跟发送消息的Socket不是同一个,所以udp出来的公网地址可能会变化 if (!Equals(routerNode.OuterIpEndPoint, self.IPEndPoint)) { routerNode.OuterIpEndPoint = self.CloneAddress(); } routerNode.KcpTransport = transport; routerNode.LastRecvOuterTime = timeNow; self.InnerSocket.Send(self.Cache, 0, messageLength, routerNode.InnerIpEndPoint); if (!routerNode.CheckOuterCount(timeNow)) { self.OnError(routerNode.Id, ErrorCore.ERR_KcpRouterTooManyPackets); } break; } } } private static void RecvInnerHandler(this RouterComponent self, int messageLength, long timeNow) { // 长度小于1,不是正常的消息 if (messageLength < 1) { return; } // accept byte flag = self.Cache[0]; switch (flag) { case KcpProtocalType.RouterReconnectACK: { uint innerConn = BitConverter.ToUInt32(self.Cache, 1); uint outerConn = BitConverter.ToUInt32(self.Cache, 5); RouterNode routerNode = self.GetChild<RouterNode>(outerConn); if (routerNode == null) { Log.Warning($"router node error: {innerConn} {outerConn}"); break; } // 必须校验innerConn,防止伪造 if (innerConn != routerNode.InnerConn) { Log.Warning( $"router node innerConn error: {innerConn} {routerNode.InnerConn} {outerConn} {routerNode.OuterConn} {routerNode.Status}"); break; } // 必须校验outerConn,防止伪造 if (outerConn != routerNode.OuterConn) { Log.Warning( $"router node outerConn error: {innerConn} {routerNode.InnerConn} {outerConn} {routerNode.OuterConn} {routerNode.Status}"); break; } routerNode.Status = RouterStatus.Msg; routerNode.LastRecvInnerTime = timeNow; // 转发出去 self.Cache.WriteTo(0, KcpProtocalType.RouterReconnectACK); self.Cache.WriteTo(1, routerNode.InnerConn); self.Cache.WriteTo(5, routerNode.OuterConn); Log.Info($"kcp router RouterAck: {outerConn} {innerConn} {routerNode.SyncIpEndPoint}"); routerNode.KcpTransport.Send(self.Cache, 0, 9, routerNode.SyncIpEndPoint); break; } case KcpProtocalType.ACK: { uint innerConn = BitConverter.ToUInt32(self.Cache, 1); // remote uint outerConn = BitConverter.ToUInt32(self.Cache, 5); // local RouterNode routerNode = self.GetChild<RouterNode>(outerConn); if (routerNode == null) { Log.Warning($"kcp router ack not found outer nodes: {outerConn} {innerConn}"); break; } routerNode.Status = RouterStatus.Msg; routerNode.InnerConn = innerConn; routerNode.LastRecvInnerTime = timeNow; // 转发出去 Log.Info($"kcp router ack: {outerConn} {innerConn} {routerNode.OuterIpEndPoint}"); routerNode.KcpTransport.Send(self.Cache, 0, messageLength, routerNode.OuterIpEndPoint); break; } case KcpProtocalType.FIN: // 断开 { // 长度!=13,不是DisConnect消息 if (messageLength != 13) { break; } uint innerConn = BitConverter.ToUInt32(self.Cache, 1); uint outerConn = BitConverter.ToUInt32(self.Cache, 5); RouterNode routerNode = self.GetChild<RouterNode>(outerConn); if (routerNode == null) { Log.Warning($"kcp router inner fin not found outer nodes: {outerConn} {innerConn}"); break; } // 比对innerConn if (routerNode.InnerConn != innerConn) { Log.Warning($"router node innerConn error: {innerConn} {outerConn} {routerNode.Status}"); break; } // 重连,这个字段可能为空,需要客户端发送消息上来才能设置 if (routerNode.OuterIpEndPoint == null) { break; } routerNode.LastRecvInnerTime = timeNow; Log.Info($"kcp router inner fin: {outerConn} {innerConn} {routerNode.OuterIpEndPoint}"); routerNode.KcpTransport.Send(self.Cache, 0, messageLength, routerNode.OuterIpEndPoint); break; } case KcpProtocalType.MSG: { // 长度<9,不是Msg消息 if (messageLength < 9) { break; } // 处理chanel uint innerConn = BitConverter.ToUInt32(self.Cache, 1); // remote uint outerConn = BitConverter.ToUInt32(self.Cache, 5); // local RouterNode routerNode = self.GetChild<RouterNode>(outerConn); if (routerNode == null) { Log.Warning($"kcp router inner msg not found outer nodes: {outerConn} {innerConn}"); break; } // 比对innerConn if (routerNode.InnerConn != innerConn) { Log.Warning($"router node innerConn error: {innerConn} {outerConn} {routerNode.Status}"); break; } // 重连,这个字段可能为空,需要客户端发送消息上来才能设置 if (routerNode.OuterIpEndPoint == null) { break; } routerNode.LastRecvInnerTime = timeNow; routerNode.KcpTransport.Send(self.Cache, 0, messageLength, routerNode.OuterIpEndPoint); break; } } } private static RouterNode New(this RouterComponent self, string innerAddress, uint outerConn, uint innerConn, uint connectId, IPEndPoint syncEndPoint) { RouterNode routerNode = self.AddChildWithId<RouterNode>(outerConn); routerNode.InnerConn = innerConn; routerNode.ConnectId = connectId; routerNode.InnerIpEndPoint = NetworkHelper.ToIPEndPoint(innerAddress); routerNode.SyncIpEndPoint = syncEndPoint; routerNode.InnerAddress = innerAddress; routerNode.LastRecvInnerTime = TimeInfo.Instance.ClientNow(); self.checkTimeout.Enqueue(outerConn); routerNode.Status = RouterStatus.Sync; Log.Info($"router new: outerConn: {outerConn} innerConn: {innerConn} {syncEndPoint}"); return routerNode; } public static void OnError(this RouterComponent self, long id, int error) { RouterNode routerNode = self.GetChild<RouterNode>(id); if (routerNode == null) { return; } Log.Info($"router node remove: {routerNode.OuterConn} {routerNode.InnerConn} {error}"); self.Remove(id); } private static void Remove(this RouterComponent self, long id) { RouterNode routerNode = self.GetChild<RouterNode>(id); if (routerNode == null) { return; } Log.Info($"router remove: {routerNode.Id} outerConn: {routerNode.OuterConn} innerConn: {routerNode.InnerConn}"); routerNode.Dispose(); } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Module/Router/RouterComponentSystem.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Module/Router/RouterComponentSystem.cs", "repo_id": "ET", "token_count": 16293 }
140
fileFormatVersion: 2 guid: 9ac96337bfa5b4a7c8385ab25b8d36af folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Share/LockStep.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Share/LockStep.meta", "repo_id": "ET", "token_count": 71 }
141
using System; namespace ET { public abstract class MessageHandler<E, Message>: HandlerObject, IMHandler where E : Entity where Message : class, IMessage { protected abstract ETTask Run(E entity, Message message); public async ETTask Handle(Entity entity, Address fromAddress, MessageObject actorMessage) { if (actorMessage is not Message msg) { Log.Error($"消息类型转换错误: {actorMessage.GetType().FullName} to {typeof (Message).Name}"); return; } if (entity is not E e) { Log.Error($"Actor类型转换错误: {entity.GetType().FullName} to {typeof (E).Name} --{typeof (Message).FullName}"); return; } await this.Run(e, msg); } public Type GetRequestType() { if (typeof (ILocationMessage).IsAssignableFrom(typeof (Message))) { Log.Error($"message is IActorLocationMessage but handler is AMActorHandler: {typeof (Message)}"); } return typeof (Message); } public Type GetResponseType() { return null; } } public abstract class MessageHandler<E, Request, Response>: HandlerObject, IMHandler where E : Entity where Request : MessageObject, IRequest where Response : MessageObject, IResponse { protected abstract ETTask Run(E unit, Request request, Response response); public async ETTask Handle(Entity entity, Address fromAddress, MessageObject actorMessage) { try { Fiber fiber = entity.Fiber(); if (actorMessage is not Request request) { Log.Error($"消息类型转换错误: {actorMessage.GetType().FullName} to {typeof (Request).Name}"); return; } if (entity is not E ee) { Log.Error($"Actor类型转换错误: {entity.GetType().FullName} to {typeof (E).FullName} --{typeof (Request).FullName}"); return; } int rpcId = request.RpcId; Response response = ObjectPool.Instance.Fetch<Response>(); try { await this.Run(ee, request, response); } catch (RpcException exception) { response.Error = exception.Error; response.Message = exception.ToString(); } catch (Exception exception) { response.Error = ErrorCore.ERR_RpcFail; response.Message = exception.ToString(); } response.RpcId = rpcId; fiber.Root.GetComponent<ProcessInnerSender>().Reply(fromAddress, response); } catch (Exception e) { throw new Exception($"解释消息失败: {actorMessage.GetType().FullName}", e); } } public Type GetRequestType() { if (typeof (ILocationRequest).IsAssignableFrom(typeof (Request))) { Log.Error($"message is IActorLocationMessage but handler is AMActorRpcHandler: {typeof (Request)}"); } return typeof (Request); } public Type GetResponseType() { return typeof (Response); } } }
ET/Unity/Assets/Scripts/Hotfix/Share/Module/Actor/MessageHandler.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Share/Module/Actor/MessageHandler.cs", "repo_id": "ET", "token_count": 1836 }
142
fileFormatVersion: 2 guid: 069fa286008182847950a814f31931e3 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Share/Module/Move.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Share/Module/Move.meta", "repo_id": "ET", "token_count": 68 }
143
fileFormatVersion: 2 guid: 47e7fc164e924ff44845e0ffc715841c folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/HotfixView/Client/Demo/UI/UILobby.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/Demo/UI/UILobby.meta", "repo_id": "ET", "token_count": 69 }
144
fileFormatVersion: 2 guid: 625bee0f0ae290a45bd36d5e3fe4e222 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/HotfixView/Client/Demo/Unit.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/Demo/Unit.meta", "repo_id": "ET", "token_count": 69 }
145
namespace ET.Client { [Event(SceneType.LockStep)] public class LoginFinish_CreateUILSLobby: AEvent<Scene, LoginFinish> { protected override async ETTask Run(Scene scene, LoginFinish args) { await UIHelper.Create(scene, UIType.UILSLobby, UILayer.Mid); } } }
ET/Unity/Assets/Scripts/HotfixView/Client/LockStep/UI/UILSLobby/LoginFinish_CreateUILSLobby.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/LockStep/UI/UILSLobby/LoginFinish_CreateUILSLobby.cs", "repo_id": "ET", "token_count": 104 }
146
using System; using UnityEngine; using UnityEngine.UI; namespace ET.Client { [EntitySystemOf(typeof(UILSRoomComponent))] [FriendOf(typeof (UILSRoomComponent))] public static partial class UILSRoomComponentSystem { [EntitySystem] private static void Awake(this UILSRoomComponent self) { ReferenceCollector rc = self.GetParent<UI>().GameObject.GetComponent<ReferenceCollector>(); GameObject replay = rc.Get<GameObject>("Replay"); GameObject play = rc.Get<GameObject>("Play"); self.frameText = rc.Get<GameObject>("progress").GetComponent<Text>(); Room room = self.Room(); if (room.IsReplay) { replay.SetActive(true); play.SetActive(false); self.totalFrame = rc.Get<GameObject>("framecount").GetComponent<Text>(); self.jumpToField = rc.Get<GameObject>("jumpToCount").GetComponent<InputField>(); self.jump = rc.Get<GameObject>("jump").GetComponent<Button>(); self.jump.onClick.AddListener(self.JumpReplay); self.replaySpeed = rc.Get<GameObject>("speed").GetComponent<Button>(); self.replaySpeed.onClick.AddListener(self.OnReplaySpeedClicked); self.totalFrame.text = self.Room().Replay.FrameInputs.Count.ToString(); } else { replay.SetActive(false); play.SetActive(true); self.predictFrameText = rc.Get<GameObject>("predict").GetComponent<Text>(); self.saveReplay = rc.Get<GameObject>("SaveReplay").GetComponent<Button>(); self.saveName = rc.Get<GameObject>("SaveName").GetComponent<InputField>(); self.saveReplay.onClick.AddListener(self.OnSaveReplay); } } [EntitySystem] private static void Update(this UILSRoomComponent self) { Room room = self.Room(); if (self.frame != room.AuthorityFrame) { self.frame = room.AuthorityFrame; self.frameText.text = room.AuthorityFrame.ToString(); } if (!room.IsReplay) { if (self.predictFrame != room.PredictionFrame) { self.predictFrame = room.PredictionFrame; self.predictFrameText.text = room.PredictionFrame.ToString(); } } } private static void OnSaveReplay(this UILSRoomComponent self) { string name = self.saveName.text; LSClientHelper.SaveReplay(self.Room(), name); } private static void JumpReplay(this UILSRoomComponent self) { int toFrame = int.Parse(self.jumpToField.text); LSClientHelper.JumpReplay(self.Room(), toFrame); } private static void OnReplaySpeedClicked(this UILSRoomComponent self) { LSReplayUpdater lsReplayUpdater = self.Room().GetComponent<LSReplayUpdater>(); lsReplayUpdater.ChangeReplaySpeed(); self.replaySpeed.gameObject.Get<GameObject>("Text").GetComponent<Text>().text = $"X{lsReplayUpdater.ReplaySpeed}"; } } }
ET/Unity/Assets/Scripts/HotfixView/Client/LockStep/UI/UILSRoom/UILSRoomComponentSystem.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/LockStep/UI/UILSRoom/UILSRoomComponentSystem.cs", "repo_id": "ET", "token_count": 1578 }
147
fileFormatVersion: 2 guid: 7dc6e02500db83a47adc9d6105d36be1 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/HotfixView/Client/Plugins.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/Plugins.meta", "repo_id": "ET", "token_count": 70 }
148
fileFormatVersion: 2 guid: 02e2918d6ce48b743b1ba9ac7894a023 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Loader/Define.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Loader/Define.cs.meta", "repo_id": "ET", "token_count": 95 }
149
fileFormatVersion: 2 guid: 36527db572638af47b03c805671cba75 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Loader/MonoBehaviour/GlobalConfig.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Loader/MonoBehaviour/GlobalConfig.cs.meta", "repo_id": "ET", "token_count": 91 }
150
fileFormatVersion: 2 guid: e6d1622fb1ba04799bf3c11259c90778 TextScriptImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Loader/Plugins/HybridCLR/Generated/link.xml.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Loader/Plugins/HybridCLR/Generated/link.xml.meta", "repo_id": "ET", "token_count": 65 }
151
namespace ET.Client { public struct Wait_SceneChangeFinish: IWaitType { public int Error { get; set; } } }
ET/Unity/Assets/Scripts/Model/Client/Demo/Main/Scene/Wait_SceneChangeFinish.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Client/Demo/Main/Scene/Wait_SceneChangeFinish.cs", "repo_id": "ET", "token_count": 94 }
152
namespace ET.Client { [ChildOf(typeof(NetComponent))] public class RouterConnector: Entity, IAwake, IDestroy { public byte Flag { get; set; } } }
ET/Unity/Assets/Scripts/Model/Client/Demo/NetClient/Router/RouterConnector.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Client/Demo/NetClient/Router/RouterConnector.cs", "repo_id": "ET", "token_count": 72 }
153
namespace ET.Client { [ComponentOf(typeof(Session))] public class ClientSessionErrorComponent: Entity, IAwake, IDestroy { } }
ET/Unity/Assets/Scripts/Model/Client/Module/Message/ClientSessionErrorComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Client/Module/Message/ClientSessionErrorComponent.cs", "repo_id": "ET", "token_count": 56 }
154
using MemoryPack; using System.Collections.Generic; namespace ET { [MemoryPackable] [Message(LockStepOuter.C2G_Match)] [ResponseType(nameof(G2C_Match))] public partial class C2G_Match : MessageObject, ISessionRequest { public static C2G_Match Create(bool isFromPool = false) { return ObjectPool.Instance.Fetch(typeof(C2G_Match), isFromPool) as C2G_Match; } [MemoryPackOrder(0)] public int RpcId { get; set; } public override void Dispose() { if (!this.IsFromPool) { return; } this.RpcId = default; ObjectPool.Instance.Recycle(this); } } [MemoryPackable] [Message(LockStepOuter.G2C_Match)] public partial class G2C_Match : MessageObject, ISessionResponse { public static G2C_Match Create(bool isFromPool = false) { return ObjectPool.Instance.Fetch(typeof(G2C_Match), isFromPool) as G2C_Match; } [MemoryPackOrder(0)] public int RpcId { get; set; } [MemoryPackOrder(1)] public int Error { get; set; } [MemoryPackOrder(2)] public string Message { get; set; } public override void Dispose() { if (!this.IsFromPool) { return; } this.RpcId = default; this.Error = default; this.Message = default; ObjectPool.Instance.Recycle(this); } } /// <summary> /// 匹配成功,通知客户端切换场景 /// </summary> [MemoryPackable] [Message(LockStepOuter.Match2G_NotifyMatchSuccess)] public partial class Match2G_NotifyMatchSuccess : MessageObject, IMessage { public static Match2G_NotifyMatchSuccess Create(bool isFromPool = false) { return ObjectPool.Instance.Fetch(typeof(Match2G_NotifyMatchSuccess), isFromPool) as Match2G_NotifyMatchSuccess; } [MemoryPackOrder(0)] public int RpcId { get; set; } /// <summary> /// 房间的ActorId /// </summary> [MemoryPackOrder(1)] public ActorId ActorId { get; set; } public override void Dispose() { if (!this.IsFromPool) { return; } this.RpcId = default; this.ActorId = default; ObjectPool.Instance.Recycle(this); } } /// <summary> /// 客户端通知房间切换场景完成 /// </summary> [MemoryPackable] [Message(LockStepOuter.C2Room_ChangeSceneFinish)] public partial class C2Room_ChangeSceneFinish : MessageObject, IRoomMessage { public static C2Room_ChangeSceneFinish Create(bool isFromPool = false) { return ObjectPool.Instance.Fetch(typeof(C2Room_ChangeSceneFinish), isFromPool) as C2Room_ChangeSceneFinish; } [MemoryPackOrder(0)] public long PlayerId { get; set; } public override void Dispose() { if (!this.IsFromPool) { return; } this.PlayerId = default; ObjectPool.Instance.Recycle(this); } } [MemoryPackable] [Message(LockStepOuter.LockStepUnitInfo)] public partial class LockStepUnitInfo : MessageObject { public static LockStepUnitInfo Create(bool isFromPool = false) { return ObjectPool.Instance.Fetch(typeof(LockStepUnitInfo), isFromPool) as LockStepUnitInfo; } [MemoryPackOrder(0)] public long PlayerId { get; set; } [MemoryPackOrder(1)] public TrueSync.TSVector Position { get; set; } [MemoryPackOrder(2)] public TrueSync.TSQuaternion Rotation { get; set; } public override void Dispose() { if (!this.IsFromPool) { return; } this.PlayerId = default; this.Position = default; this.Rotation = default; ObjectPool.Instance.Recycle(this); } } /// <summary> /// 房间通知客户端进入战斗 /// </summary> [MemoryPackable] [Message(LockStepOuter.Room2C_Start)] public partial class Room2C_Start : MessageObject, IMessage { public static Room2C_Start Create(bool isFromPool = false) { return ObjectPool.Instance.Fetch(typeof(Room2C_Start), isFromPool) as Room2C_Start; } [MemoryPackOrder(0)] public long StartTime { get; set; } [MemoryPackOrder(1)] public List<LockStepUnitInfo> UnitInfo { get; set; } = new(); public override void Dispose() { if (!this.IsFromPool) { return; } this.StartTime = default; this.UnitInfo.Clear(); ObjectPool.Instance.Recycle(this); } } [MemoryPackable] [Message(LockStepOuter.FrameMessage)] public partial class FrameMessage : MessageObject, IMessage { public static FrameMessage Create(bool isFromPool = false) { return ObjectPool.Instance.Fetch(typeof(FrameMessage), isFromPool) as FrameMessage; } [MemoryPackOrder(0)] public int Frame { get; set; } [MemoryPackOrder(1)] public long PlayerId { get; set; } [MemoryPackOrder(2)] public LSInput Input { get; set; } public override void Dispose() { if (!this.IsFromPool) { return; } this.Frame = default; this.PlayerId = default; this.Input = default; ObjectPool.Instance.Recycle(this); } } [MemoryPackable] [Message(LockStepOuter.OneFrameInputs)] public partial class OneFrameInputs : MessageObject, IMessage { public static OneFrameInputs Create(bool isFromPool = false) { return ObjectPool.Instance.Fetch(typeof(OneFrameInputs), isFromPool) as OneFrameInputs; } [MongoDB.Bson.Serialization.Attributes.BsonDictionaryOptions(MongoDB.Bson.Serialization.Options.DictionaryRepresentation.ArrayOfArrays)] [MemoryPackOrder(1)] public Dictionary<long, LSInput> Inputs { get; set; } = new(); public override void Dispose() { if (!this.IsFromPool) { return; } this.Inputs.Clear(); ObjectPool.Instance.Recycle(this); } } [MemoryPackable] [Message(LockStepOuter.Room2C_AdjustUpdateTime)] public partial class Room2C_AdjustUpdateTime : MessageObject, IMessage { public static Room2C_AdjustUpdateTime Create(bool isFromPool = false) { return ObjectPool.Instance.Fetch(typeof(Room2C_AdjustUpdateTime), isFromPool) as Room2C_AdjustUpdateTime; } [MemoryPackOrder(0)] public int DiffTime { get; set; } public override void Dispose() { if (!this.IsFromPool) { return; } this.DiffTime = default; ObjectPool.Instance.Recycle(this); } } [MemoryPackable] [Message(LockStepOuter.C2Room_CheckHash)] public partial class C2Room_CheckHash : MessageObject, IRoomMessage { public static C2Room_CheckHash Create(bool isFromPool = false) { return ObjectPool.Instance.Fetch(typeof(C2Room_CheckHash), isFromPool) as C2Room_CheckHash; } [MemoryPackOrder(0)] public long PlayerId { get; set; } [MemoryPackOrder(1)] public int Frame { get; set; } [MemoryPackOrder(2)] public long Hash { get; set; } public override void Dispose() { if (!this.IsFromPool) { return; } this.PlayerId = default; this.Frame = default; this.Hash = default; ObjectPool.Instance.Recycle(this); } } [MemoryPackable] [Message(LockStepOuter.Room2C_CheckHashFail)] public partial class Room2C_CheckHashFail : MessageObject, IMessage { public static Room2C_CheckHashFail Create(bool isFromPool = false) { return ObjectPool.Instance.Fetch(typeof(Room2C_CheckHashFail), isFromPool) as Room2C_CheckHashFail; } [MemoryPackOrder(0)] public int Frame { get; set; } [MemoryPackOrder(1)] public byte[] LSWorldBytes { get; set; } public override void Dispose() { if (!this.IsFromPool) { return; } this.Frame = default; this.LSWorldBytes = default; ObjectPool.Instance.Recycle(this); } } [MemoryPackable] [Message(LockStepOuter.G2C_Reconnect)] public partial class G2C_Reconnect : MessageObject, IMessage { public static G2C_Reconnect Create(bool isFromPool = false) { return ObjectPool.Instance.Fetch(typeof(G2C_Reconnect), isFromPool) as G2C_Reconnect; } [MemoryPackOrder(0)] public long StartTime { get; set; } [MemoryPackOrder(1)] public List<LockStepUnitInfo> UnitInfos { get; set; } = new(); [MemoryPackOrder(2)] public int Frame { get; set; } public override void Dispose() { if (!this.IsFromPool) { return; } this.StartTime = default; this.UnitInfos.Clear(); this.Frame = default; ObjectPool.Instance.Recycle(this); } } public static class LockStepOuter { public const ushort C2G_Match = 11002; public const ushort G2C_Match = 11003; public const ushort Match2G_NotifyMatchSuccess = 11004; public const ushort C2Room_ChangeSceneFinish = 11005; public const ushort LockStepUnitInfo = 11006; public const ushort Room2C_Start = 11007; public const ushort FrameMessage = 11008; public const ushort OneFrameInputs = 11009; public const ushort Room2C_AdjustUpdateTime = 11010; public const ushort C2Room_CheckHash = 11011; public const ushort Room2C_CheckHashFail = 11012; public const ushort G2C_Reconnect = 11013; } }
ET/Unity/Assets/Scripts/Model/Generate/ClientServer/Message/LockStepOuter_C_11001.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Generate/ClientServer/Message/LockStepOuter_C_11001.cs", "repo_id": "ET", "token_count": 5013 }
155
using CommandLine; namespace ET.Server { public class CreateRobotArgs: Object { [Option("Num", Required = false, Default = 1)] public int Num { get; set; } } }
ET/Unity/Assets/Scripts/Model/Server/Demo/Robot/Console/CreateRobotArgs.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Demo/Robot/Console/CreateRobotArgs.cs", "repo_id": "ET", "token_count": 75 }
156
namespace ET.Server { [ChildOf(typeof (RoomServerComponent))] public class RoomPlayer: Entity, IAwake { public int Progress { get; set; } public bool IsOnline { get; set; } = true; } }
ET/Unity/Assets/Scripts/Model/Server/LockStep/Map/RoomPlayer.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/LockStep/Map/RoomPlayer.cs", "repo_id": "ET", "token_count": 87 }
157
namespace ET.Server { [ComponentOf(typeof(Scene))] public class AOIManagerComponent: Entity, IAwake { public const int CellSize = 10 * 1000; } }
ET/Unity/Assets/Scripts/Model/Server/Module/AOI/AOIManagerComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Module/AOI/AOIManagerComponent.cs", "repo_id": "ET", "token_count": 72 }
158
using System; namespace ET.Server { [ComponentOf(typeof(Scene))] public class DBManagerComponent: Entity, IAwake { public DBComponent[] DBComponents = new DBComponent[IdGenerater.MaxZone]; } }
ET/Unity/Assets/Scripts/Model/Server/Module/DB/DBManagerComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Module/DB/DBManagerComponent.cs", "repo_id": "ET", "token_count": 88 }
159
using System.Collections.Generic; using System.Net; namespace ET.Server { [ComponentOf(typeof(Scene))] public class ProcessOuterSender: Entity, IAwake<IPEndPoint>, IUpdate, IDestroy { public const long TIMEOUT_TIME = 40 * 1000; public int RpcId; public readonly Dictionary<int, MessageSenderStruct> requestCallback = new(); public AService AService; public NetworkProtocol InnerProtocol = NetworkProtocol.KCP; } }
ET/Unity/Assets/Scripts/Model/Server/Module/Message/ProcessOuterSender.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Module/Message/ProcessOuterSender.cs", "repo_id": "ET", "token_count": 205 }
160
namespace ET { public class FixedTimeCounter: Object { private long startTime; private int startFrame; public int Interval { get; private set; } public FixedTimeCounter(long startTime, int startFrame, int interval) { this.startTime = startTime; this.startFrame = startFrame; this.Interval = interval; } public void ChangeInterval(int interval, int frame) { this.startTime += (frame - this.startFrame) * this.Interval; this.startFrame = frame; this.Interval = interval; } public long FrameTime(int frame) { return this.startTime + (frame - this.startFrame) * this.Interval; } public void Reset(long time, int frame) { this.startTime = time; this.startFrame = frame; } } }
ET/Unity/Assets/Scripts/Model/Share/LockStep/FixedTimeCounter.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/LockStep/FixedTimeCounter.cs", "repo_id": "ET", "token_count": 439 }
161
using System; using System.Collections.Generic; namespace ET { [UniqueId(-1, 1)] public static class LSQueneUpdateIndex { public const int None = -1; public const int LSUpdate = 0; public const int Max = 1; } [Code] public class LSEntitySystemSingleton: Singleton<LSEntitySystemSingleton>, ISingletonAwake { private TypeSystems TypeSystems { get; set; } private readonly DoubleMap<Type, long> lsEntityTypeLongHashCode = new(); public void Awake() { this.TypeSystems = new(LSQueneUpdateIndex.Max); foreach (Type type in CodeTypes.Instance.GetTypes(typeof (LSEntitySystemAttribute))) { SystemObject obj = (SystemObject)Activator.CreateInstance(type); if (obj is not ISystemType iSystemType) { continue; } TypeSystems.OneTypeSystems oneTypeSystems = this.TypeSystems.GetOrCreateOneTypeSystems(iSystemType.Type()); oneTypeSystems.Map.Add(iSystemType.SystemType(), obj); int index = iSystemType.GetInstanceQueueIndex(); if (index > LSQueneUpdateIndex.None && index < LSQueneUpdateIndex.Max) { oneTypeSystems.QueueFlag[index] = true; } } foreach (var kv in CodeTypes.Instance.GetTypes()) { Type type = kv.Value; if (typeof(LSEntity).IsAssignableFrom(type)) { long hash = type.FullName.GetLongHashCode(); try { this.lsEntityTypeLongHashCode.Add(type, type.FullName.GetLongHashCode()); } catch (Exception e) { Type sameHashType = this.lsEntityTypeLongHashCode.GetKeyByValue(hash); throw new Exception($"long hash add fail: {type.FullName} {sameHashType.FullName}", e); } } } } public long GetLongHashCode(Type type) { return this.lsEntityTypeLongHashCode.GetValueByKey(type); } public TypeSystems.OneTypeSystems GetOneTypeSystems(Type type) { return this.TypeSystems.GetOneTypeSystems(type); } public void LSRollback(Entity entity) { if (entity is not ILSRollback) { return; } List<SystemObject> iLSRollbackSystems = this.TypeSystems.GetSystems(entity.GetType(), typeof (ILSRollbackSystem)); if (iLSRollbackSystems == null) { return; } foreach (ILSRollbackSystem iLSRollbackSystem in iLSRollbackSystems) { if (iLSRollbackSystem == null) { continue; } try { iLSRollbackSystem.Run(entity); } catch (Exception e) { Log.Error(e); } } } public void LSUpdate(LSEntity entity) { if (entity is not ILSUpdate) { return; } List<SystemObject> iLSUpdateSystems = TypeSystems.GetSystems(entity.GetType(), typeof (ILSUpdateSystem)); if (iLSUpdateSystems == null) { return; } foreach (ILSUpdateSystem iLSUpdateSystem in iLSUpdateSystems) { try { iLSUpdateSystem.Run(entity); } catch (Exception e) { Log.Error(e); } } } } }
ET/Unity/Assets/Scripts/Model/Share/LockStep/LSEntitySystemSingleton.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/LockStep/LSEntitySystemSingleton.cs", "repo_id": "ET", "token_count": 2273 }
162
using System.Collections.Generic; using MemoryPack; namespace ET { [MemoryPackable] public partial class Replay: Object { [MemoryPackOrder(1)] public List<LockStepUnitInfo> UnitInfos; [MemoryPackOrder(2)] public List<OneFrameInputs> FrameInputs = new(); [MemoryPackOrder(3)] public List<byte[]> Snapshots = new(); } }
ET/Unity/Assets/Scripts/Model/Share/LockStep/Replay.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/LockStep/Replay.cs", "repo_id": "ET", "token_count": 175 }
163
fileFormatVersion: 2 guid: 22534ff56546c094d904521502f2103f MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Share/Module/Console/ConsoleComponent.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Console/ConsoleComponent.cs.meta", "repo_id": "ET", "token_count": 92 }
164
using System.Collections.Generic; namespace ET { public class LogMsg: Singleton<LogMsg>, ISingletonAwake { private readonly HashSet<ushort> ignore = new() { OuterMessage.C2G_Ping, OuterMessage.G2C_Ping, OuterMessage.C2G_Benchmark, OuterMessage.G2C_Benchmark, }; public void Awake() { } public void Debug(Fiber fiber, object msg) { ushort opcode = OpcodeType.Instance.GetOpcode(msg.GetType()); if (this.ignore.Contains(opcode)) { return; } fiber.Log.Debug(msg.ToString()); } } }
ET/Unity/Assets/Scripts/Model/Share/Module/Message/LogMsg.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Message/LogMsg.cs", "repo_id": "ET", "token_count": 370 }
165
fileFormatVersion: 2 guid: 26fd94c36353aad4591969119ce93bb4 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Share/Module/Move.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Move.meta", "repo_id": "ET", "token_count": 65 }
166
fileFormatVersion: 2 guid: 972155bb07920b648bbeecab259ed50b folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Share/Module/ObjectWait.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/ObjectWait.meta", "repo_id": "ET", "token_count": 66 }
167
using Unity.Mathematics; namespace ET { public struct ChangePosition { public Unit Unit; public float3 OldPos; } public struct ChangeRotation { public Unit Unit; } }
ET/Unity/Assets/Scripts/Model/Share/Module/Unit/UnitEventType.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Unit/UnitEventType.cs", "repo_id": "ET", "token_count": 94 }
168
fileFormatVersion: 2 guid: e995cd03c9bc1f14b8b4a18641af2121 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ModelView/Client/Demo.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ModelView/Client/Demo.meta", "repo_id": "ET", "token_count": 70 }
169
fileFormatVersion: 2 guid: a2978aee6ea76e041b629850500540e3 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ModelView/Client/Demo/UI/UILogin/UILoginComponent.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ModelView/Client/Demo/UI/UILogin/UILoginComponent.cs.meta", "repo_id": "ET", "token_count": 92 }
170
using UnityEngine; namespace ET { [ChildOf(typeof(LSUnitViewComponent))] public class LSUnitView: Entity, IAwake<GameObject>, IUpdate, ILSRollback { public GameObject GameObject { get; set; } public Transform Transform { get; set; } public EntityRef<LSUnit> Unit; public Vector3 Position; public Quaternion Rotation; public float totalTime; public float t; } }
ET/Unity/Assets/Scripts/ModelView/Client/LockStep/LSUnitView.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ModelView/Client/LockStep/LSUnitView.cs", "repo_id": "ET", "token_count": 172 }
171
fileFormatVersion: 2 guid: ffdd1cc7fd912e644aa1f2a2721b303a folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ModelView/Client/Module.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ModelView/Client/Module.meta", "repo_id": "ET", "token_count": 70 }
172
fileFormatVersion: 2 guid: a7f1c0a5d19958641a51189a19e3a90a folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/Compression.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/Compression.meta", "repo_id": "ET", "token_count": 72 }
173
fileFormatVersion: 2 guid: f2e1c415f6411874394e1a7e10615580 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcArrayUtils.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcArrayUtils.cs.meta", "repo_id": "ET", "token_count": 94 }
174
fileFormatVersion: 2 guid: d5f2be45ab4f5ca4899942591a76ef57 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcMatrix4X4.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcMatrix4X4.cs.meta", "repo_id": "ET", "token_count": 95 }
175
/* Copyright (c) 2009-2010 Mikko Mononen memon@inside.org recast4j copyright (c) 2015-2019 Piotr Piastucki piotr@jtilia.org DotRecast Copyright (c) 2023 Choi Ikpil ikpil@naver.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using DotRecast.Core; using DotRecast.Detour.Crowd.Tracking; namespace DotRecast.Detour.Crowd { using static DotRecast.Core.RcMath; /** * Members in this module implement local steering and dynamic avoidance features. * * The crowd is the big beast of the navigation features. It not only handles a lot of the path management for you, but * also local steering and dynamic avoidance between members of the crowd. I.e. It can keep your agents from running * into each other. * * Main class: Crowd * * The #dtNavMeshQuery and #dtPathCorridor classes provide perfectly good, easy to use path planning features. But in * the end they only give you points that your navigation client should be moving toward. When it comes to deciding * things like agent velocity and steering to avoid other agents, that is up to you to implement. Unless, of course, you * decide to use Crowd. * * Basically, you add an agent to the crowd, providing various configuration settings such as maximum speed and * acceleration. You also provide a local target to move toward. The crowd manager then provides, with every update, the * new agent position and velocity for the frame. The movement will be constrained to the navigation mesh, and steering * will be applied to ensure agents managed by the crowd do not collide with each other. * * This is very powerful feature set. But it comes with limitations. * * The biggest limitation is that you must give control of the agent's position completely over to the crowd manager. * You can update things like maximum speed and acceleration. But in order for the crowd manager to do its thing, it * can't allow you to constantly be giving it overrides to position and velocity. So you give up direct control of the * agent's movement. It belongs to the crowd. * * The second biggest limitation revolves around the fact that the crowd manager deals with local planning. So the * agent's target should never be more than 256 polygons away from its current position. If it is, you risk your agent * failing to reach its target. So you may still need to do long distance planning and provide the crowd manager with * intermediate targets. * * Other significant limitations: * * - All agents using the crowd manager will use the same #dtQueryFilter. - Crowd management is relatively expensive. * The maximum agents under crowd management at any one time is between 20 and 30. A good place to start is a maximum of * 25 agents for 0.5ms per frame. * * @note This is a summary list of members. Use the index or search feature to find minor members. * * @struct dtCrowdAgentParams * @see CrowdAgent, Crowd::AddAgent(), Crowd::UpdateAgentParameters() * * @var dtCrowdAgentParams::obstacleAvoidanceType * @par * * #dtCrowd permits agents to use different avoidance configurations. This value is the index of the * #dtObstacleAvoidanceParams within the crowd. * * @see dtObstacleAvoidanceParams, dtCrowd::SetObstacleAvoidanceParams(), dtCrowd::GetObstacleAvoidanceParams() * * @var dtCrowdAgentParams::collisionQueryRange * @par * * Collision elements include other agents and navigation mesh boundaries. * * This value is often based on the agent radius and/or maximum speed. E.g. radius * 8 * * @var dtCrowdAgentParams::pathOptimizationRange * @par * * Only applicable if #updateFlags includes the #DT_CROWD_OPTIMIZE_VIS flag. * * This value is often based on the agent radius. E.g. radius * 30 * * @see dtPathCorridor::OptimizePathVisibility() * * @var dtCrowdAgentParams::separationWeight * @par * * A higher value will result in agents trying to stay farther away from each other at the cost of more difficult * steering in tight spaces. * */ /** * This is the core class of the refs crowd module. See the refs crowd documentation for a summary of the crowd * features. A common method for setting up the crowd is as follows: -# Allocate the crowd -# Set the avoidance * configurations using #SetObstacleAvoidanceParams(). -# Add agents using #AddAgent() and make an initial movement * request using #RequestMoveTarget(). A common process for managing the crowd is as follows: -# Call #Update() to allow * the crowd to manage its agents. -# Retrieve agent information using #GetActiveAgents(). -# Make movement requests * using #RequestMoveTarget() when movement goal changes. -# Repeat every frame. Some agent configuration settings can * be updated using #UpdateAgentParameters(). But the crowd owns the agent position. So it is not possible to update an * active agent's position. If agent position must be fed back into the crowd, the agent must be removed and re-added. * Notes: - Path related information is available for newly added agents only after an #Update() has been performed. - * Agent objects are kept in a pool and re-used. So it is important when using agent objects to check the value of * #dtCrowdAgent::active to determine if the agent is actually in use or not. - This class is meant to provide 'local' * movement. There is a limit of 256 polygons in the path corridor. So it is not meant to provide automatic pathfinding * services over long distances. * * @see DtAllocCrowd(), DtFreeCrowd(), Init(), dtCrowdAgent */ public class DtCrowd { /// The maximum number of corners a crowd agent will look ahead in the path. /// This value is used for sizing the crowd agent corner buffers. /// Due to the behavior of the crowd manager, the actual number of useful /// corners will be one less than this number. /// @ingroup crowd public const int DT_CROWDAGENT_MAX_CORNERS = 4; /// The maximum number of crowd avoidance configurations supported by the /// crowd manager. /// @ingroup crowd /// @see dtObstacleAvoidanceParams, dtCrowd::SetObstacleAvoidanceParams(), dtCrowd::GetObstacleAvoidanceParams(), /// dtCrowdAgentParams::obstacleAvoidanceType public const int DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS = 8; /// The maximum number of query filter types supported by the crowd manager. /// @ingroup crowd /// @see dtQueryFilter, dtCrowd::GetFilter() dtCrowd::GetEditableFilter(), /// dtCrowdAgentParams::queryFilterType public const int DT_CROWD_MAX_QUERY_FILTER_TYPE = 16; private readonly RcAtomicInteger _agentId = new RcAtomicInteger(); private readonly List<DtCrowdAgent> _agents; private readonly DtPathQueue _pathQ; private readonly DtObstacleAvoidanceParams[] _obstacleQueryParams = new DtObstacleAvoidanceParams[DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS]; private readonly DtObstacleAvoidanceQuery _obstacleQuery; private DtProximityGrid _grid; private readonly RcVec3f _ext = new RcVec3f(); private readonly IDtQueryFilter[] _filters = new IDtQueryFilter[DT_CROWD_MAX_QUERY_FILTER_TYPE]; private DtNavMeshQuery _navQuery; private DtNavMesh _navMesh; private readonly DtCrowdConfig _config; private readonly DtCrowdTelemetry _telemetry = new DtCrowdTelemetry(); private int _velocitySampleCount; public DtCrowd(DtCrowdConfig config, DtNavMesh nav) : this(config, nav, i => new DtQueryDefaultFilter()) { } public DtCrowd(DtCrowdConfig config, DtNavMesh nav, Func<int, IDtQueryFilter> queryFilterFactory) { _config = config; _ext.Set(config.maxAgentRadius * 2.0f, config.maxAgentRadius * 1.5f, config.maxAgentRadius * 2.0f); _obstacleQuery = new DtObstacleAvoidanceQuery(config.maxObstacleAvoidanceCircles, config.maxObstacleAvoidanceSegments); for (int i = 0; i < DT_CROWD_MAX_QUERY_FILTER_TYPE; i++) { _filters[i] = queryFilterFactory.Invoke(i); } // Init obstacle query option. for (int i = 0; i < DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS; ++i) { _obstacleQueryParams[i] = new DtObstacleAvoidanceParams(); } // Allocate temp buffer for merging paths. _pathQ = new DtPathQueue(config); _agents = new List<DtCrowdAgent>(); // The navQuery is mostly used for local searches, no need for large node pool. _navMesh = nav; _navQuery = new DtNavMeshQuery(nav); } public void SetNavMesh(DtNavMesh nav) { _navMesh = nav; _navQuery = new DtNavMeshQuery(nav); } /// Sets the shared avoidance configuration for the specified index. /// @param[in] idx The index. [Limits: 0 <= value < /// #DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS] /// @param[in] option The new configuration. public void SetObstacleAvoidanceParams(int idx, DtObstacleAvoidanceParams option) { if (idx >= 0 && idx < DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS) { _obstacleQueryParams[idx] = new DtObstacleAvoidanceParams(option); } } /// Gets the shared avoidance configuration for the specified index. /// @param[in] idx The index of the configuration to retreive. /// [Limits: 0 <= value < #DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS] /// @return The requested configuration. public DtObstacleAvoidanceParams GetObstacleAvoidanceParams(int idx) { if (idx >= 0 && idx < DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS) { return _obstacleQueryParams[idx]; } return null; } /// Updates the specified agent's configuration. /// @param[in] idx The agent index. [Limits: 0 <= value < #GetAgentCount()] /// @param[in] params The new agent configuration. public void UpdateAgentParameters(DtCrowdAgent agent, DtCrowdAgentParams option) { agent.option = option; } /** * Adds a new agent to the crowd. * * @param pos * The requested position of the agent. [(x, y, z)] * @param params * The configuration of the agent. * @return The newly created agent object */ public DtCrowdAgent AddAgent(RcVec3f pos, DtCrowdAgentParams option) { DtCrowdAgent ag = new DtCrowdAgent(_agentId.GetAndIncrement()); _agents.Add(ag); UpdateAgentParameters(ag, option); // Find nearest position on navmesh and place the agent there. var status = _navQuery.FindNearestPoly(pos, _ext, _filters[ag.option.queryFilterType], out var refs, out var nearestPt, out var _); if (status.Failed()) { nearestPt = pos; refs = 0; } ag.corridor.Reset(refs, nearestPt); ag.boundary.Reset(); ag.partial = false; ag.topologyOptTime = 0; ag.targetReplanTime = 0; ag.dvel = RcVec3f.Zero; ag.nvel = RcVec3f.Zero; ag.vel = RcVec3f.Zero; ag.npos = nearestPt; ag.desiredSpeed = 0; if (refs != 0) { ag.state = DtCrowdAgentState.DT_CROWDAGENT_STATE_WALKING; } else { ag.state = DtCrowdAgentState.DT_CROWDAGENT_STATE_INVALID; } ag.targetState = DtMoveRequestState.DT_CROWDAGENT_TARGET_NONE; return ag; } /** * Removes the agent from the crowd. * * @param agent * Agent to be removed */ public void RemoveAgent(DtCrowdAgent agent) { _agents.Remove(agent); } private bool RequestMoveTargetReplan(DtCrowdAgent ag, long refs, RcVec3f pos) { ag.SetTarget(refs, pos); ag.targetReplan = true; return true; } /// Submits a new move request for the specified agent. /// @param[in] idx The agent index. [Limits: 0 <= value < #GetAgentCount()] /// @param[in] ref The position's polygon reference. /// @param[in] pos The position within the polygon. [(x, y, z)] /// @return True if the request was successfully submitted. /// /// This method is used when a new target is set. /// /// The position will be constrained to the surface of the navigation mesh. /// /// The request will be processed during the next #Update(). public bool RequestMoveTarget(DtCrowdAgent agent, long refs, RcVec3f pos) { if (refs == 0) { return false; } // Initialize request. agent.SetTarget(refs, pos); agent.targetReplan = false; return true; } /// Submits a new move request for the specified agent. /// @param[in] idx The agent index. [Limits: 0 <= value < #GetAgentCount()] /// @param[in] vel The movement velocity. [(x, y, z)] /// @return True if the request was successfully submitted. public bool RequestMoveVelocity(DtCrowdAgent agent, RcVec3f vel) { // Initialize request. agent.targetRef = 0; agent.targetPos = vel; agent.targetPathQueryResult = null; agent.targetReplan = false; agent.targetState = DtMoveRequestState.DT_CROWDAGENT_TARGET_VELOCITY; return true; } /// Resets any request for the specified agent. /// @param[in] idx The agent index. [Limits: 0 <= value < #GetAgentCount()] /// @return True if the request was successfully reseted. public bool ResetMoveTarget(DtCrowdAgent agent) { // Initialize request. agent.targetRef = 0; agent.targetPos = RcVec3f.Zero; agent.dvel = RcVec3f.Zero; agent.targetPathQueryResult = null; agent.targetReplan = false; agent.targetState = DtMoveRequestState.DT_CROWDAGENT_TARGET_NONE; return true; } /** * Gets the active agents int the agent pool. * * @return List of active agents */ public IList<DtCrowdAgent> GetActiveAgents() { return _agents; } public RcVec3f GetQueryExtents() { return _ext; } public IDtQueryFilter GetFilter(int i) { return i >= 0 && i < DT_CROWD_MAX_QUERY_FILTER_TYPE ? _filters[i] : null; } public DtProximityGrid GetGrid() { return _grid; } public DtPathQueue GetPathQueue() { return _pathQ; } public DtCrowdTelemetry Telemetry() { return _telemetry; } public DtCrowdConfig Config() { return _config; } public DtCrowdTelemetry Update(float dt, DtCrowdAgentDebugInfo debug) { _velocitySampleCount = 0; _telemetry.Start(); IList<DtCrowdAgent> agents = GetActiveAgents(); // Check that all agents still have valid paths. CheckPathValidity(agents, dt); // Update async move request and path finder. UpdateMoveRequest(agents, dt); // Optimize path topology. UpdateTopologyOptimization(agents, dt); // Register agents to proximity grid. BuildProximityGrid(agents); // Get nearby navmesh segments and agents to collide with. BuildNeighbours(agents); // Find next corner to steer to. FindCorners(agents, debug); // Trigger off-mesh connections (depends on corners). TriggerOffMeshConnections(agents); // Calculate steering. CalculateSteering(agents); // Velocity planning. PlanVelocity(debug, agents); // Integrate. Integrate(dt, agents); // Handle collisions. HandleCollisions(agents); MoveAgents(agents); // Update agents using off-mesh connection. UpdateOffMeshConnections(agents, dt); return _telemetry; } private void CheckPathValidity(IList<DtCrowdAgent> agents, float dt) { using var timer = _telemetry.ScopedTimer(DtCrowdTimerLabel.CheckPathValidity); foreach (DtCrowdAgent ag in agents) { if (ag.state != DtCrowdAgentState.DT_CROWDAGENT_STATE_WALKING) { continue; } ag.targetReplanTime += dt; bool replan = false; // First check that the current location is valid. RcVec3f agentPos = new RcVec3f(); long agentRef = ag.corridor.GetFirstPoly(); agentPos = ag.npos; if (!_navQuery.IsValidPolyRef(agentRef, _filters[ag.option.queryFilterType])) { // Current location is not valid, try to reposition. // TODO: this can snap agents, how to handle that? _navQuery.FindNearestPoly(ag.npos, _ext, _filters[ag.option.queryFilterType], out agentRef, out var nearestPt, out var _); agentPos = nearestPt; if (agentRef == 0) { // Could not find location in navmesh, set state to invalid. ag.corridor.Reset(0, agentPos); ag.partial = false; ag.boundary.Reset(); ag.state = DtCrowdAgentState.DT_CROWDAGENT_STATE_INVALID; continue; } // Make sure the first polygon is valid, but leave other valid // polygons in the path so that replanner can adjust the path // better. ag.corridor.FixPathStart(agentRef, agentPos); // ag.corridor.TrimInvalidPath(agentRef, agentPos, m_navquery, // &m_filter); ag.boundary.Reset(); ag.npos = agentPos; replan = true; } // If the agent does not have move target or is controlled by // velocity, no need to recover the target nor replan. if (ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_NONE || ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_VELOCITY) { continue; } // Try to recover move request position. if (ag.targetState != DtMoveRequestState.DT_CROWDAGENT_TARGET_NONE && ag.targetState != DtMoveRequestState.DT_CROWDAGENT_TARGET_FAILED) { if (!_navQuery.IsValidPolyRef(ag.targetRef, _filters[ag.option.queryFilterType])) { // Current target is not valid, try to reposition. _navQuery.FindNearestPoly(ag.targetPos, _ext, _filters[ag.option.queryFilterType], out ag.targetRef, out var nearestPt, out var _); ag.targetPos = nearestPt; replan = true; } if (ag.targetRef == 0) { // Failed to reposition target, fail moverequest. ag.corridor.Reset(agentRef, agentPos); ag.partial = false; ag.targetState = DtMoveRequestState.DT_CROWDAGENT_TARGET_NONE; } } // If nearby corridor is not valid, replan. if (!ag.corridor.IsValid(_config.checkLookAhead, _navQuery, _filters[ag.option.queryFilterType])) { // Fix current path. // ag.corridor.TrimInvalidPath(agentRef, agentPos, m_navquery, // &m_filter); // ag.boundary.Reset(); replan = true; } // If the end of the path is near and it is not the requested // location, replan. if (ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_VALID) { if (ag.targetReplanTime > _config.targetReplanDelay && ag.corridor.GetPathCount() < _config.checkLookAhead && ag.corridor.GetLastPoly() != ag.targetRef) { replan = true; } } // Try to replan path to goal. if (replan) { if (ag.targetState != DtMoveRequestState.DT_CROWDAGENT_TARGET_NONE) { RequestMoveTargetReplan(ag, ag.targetRef, ag.targetPos); } } } } private void UpdateMoveRequest(IList<DtCrowdAgent> agents, float dt) { using var timer = _telemetry.ScopedTimer(DtCrowdTimerLabel.UpdateMoveRequest); RcSortedQueue<DtCrowdAgent> queue = new RcSortedQueue<DtCrowdAgent>((a1, a2) => a2.targetReplanTime.CompareTo(a1.targetReplanTime)); // Fire off new requests. List<long> reqPath = new List<long>(); foreach (DtCrowdAgent ag in agents) { if (ag.state == DtCrowdAgentState.DT_CROWDAGENT_STATE_INVALID) { continue; } if (ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_NONE || ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_VELOCITY) { continue; } if (ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_REQUESTING) { List<long> path = ag.corridor.GetPath(); if (0 == path.Count) { throw new ArgumentException("Empty path"); } // Quick search towards the goal. _navQuery.InitSlicedFindPath(path[0], ag.targetRef, ag.npos, ag.targetPos, _filters[ag.option.queryFilterType], 0); _navQuery.UpdateSlicedFindPath(_config.maxTargetFindPathIterations, out var _); DtStatus status; if (ag.targetReplan) // && npath > 10) { // Try to use existing steady path during replan if possible. status = _navQuery.FinalizeSlicedFindPathPartial(path, ref reqPath); } else { // Try to move towards target when goal changes. status = _navQuery.FinalizeSlicedFindPath(ref reqPath); } RcVec3f reqPos = new RcVec3f(); if (status.Succeeded() && reqPath.Count > 0) { // In progress or succeed. if (reqPath[reqPath.Count - 1] != ag.targetRef) { // Partial path, constrain target position inside the // last polygon. var cr = _navQuery.ClosestPointOnPoly(reqPath[reqPath.Count - 1], ag.targetPos, out reqPos, out var _); if (cr.Failed()) { reqPath = new List<long>(); } } else { reqPos = ag.targetPos; } } else { // Could not find path, start the request from current // location. reqPos = ag.npos; reqPath = new List<long>(); reqPath.Add(path[0]); } ag.corridor.SetCorridor(reqPos, reqPath); ag.boundary.Reset(); ag.partial = false; if (reqPath[reqPath.Count - 1] == ag.targetRef) { ag.targetState = DtMoveRequestState.DT_CROWDAGENT_TARGET_VALID; ag.targetReplanTime = 0; } else { // The path is longer or potentially unreachable, full plan. ag.targetState = DtMoveRequestState.DT_CROWDAGENT_TARGET_WAITING_FOR_QUEUE; } ag.targetReplanWaitTime = 0; } if (ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_WAITING_FOR_QUEUE) { queue.Enqueue(ag); } } while (!queue.IsEmpty()) { DtCrowdAgent ag = queue.Dequeue(); ag.targetPathQueryResult = _pathQ.Request(ag.corridor.GetLastPoly(), ag.targetRef, ag.corridor.GetTarget(), ag.targetPos, _filters[ag.option.queryFilterType]); if (ag.targetPathQueryResult != null) { ag.targetState = DtMoveRequestState.DT_CROWDAGENT_TARGET_WAITING_FOR_PATH; } else { _telemetry.RecordMaxTimeToEnqueueRequest(ag.targetReplanWaitTime); ag.targetReplanWaitTime += dt; } } // Update requests. using (var timer2 = _telemetry.ScopedTimer(DtCrowdTimerLabel.PathQueueUpdate)) { _pathQ.Update(_navMesh); } // Process path results. foreach (DtCrowdAgent ag in agents) { if (ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_NONE || ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_VELOCITY) { continue; } if (ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_WAITING_FOR_PATH) { // _telemetry.RecordPathWaitTime(ag.targetReplanTime); // Poll path queue. DtStatus status = ag.targetPathQueryResult.status; if (status.Failed()) { // Path find failed, retry if the target location is still // valid. ag.targetPathQueryResult = null; if (ag.targetRef != 0) { ag.targetState = DtMoveRequestState.DT_CROWDAGENT_TARGET_REQUESTING; } else { ag.targetState = DtMoveRequestState.DT_CROWDAGENT_TARGET_FAILED; } ag.targetReplanTime = 0; } else if (status.Succeeded()) { List<long> path = ag.corridor.GetPath(); if (0 == path.Count) { throw new ArgumentException("Empty path"); } // Apply results. var targetPos = ag.targetPos; bool valid = true; List<long> res = ag.targetPathQueryResult.path; if (status.Failed() || 0 == res.Count) { valid = false; } if (status.IsPartial()) { ag.partial = true; } else { ag.partial = false; } // Merge result and existing path. // The agent might have moved whilst the request is // being processed, so the path may have changed. // We assume that the end of the path is at the same // location // where the request was issued. // The last ref in the old path should be the same as // the location where the request was issued.. if (valid && path[path.Count - 1] != res[0]) { valid = false; } if (valid) { // Put the old path infront of the old path. if (path.Count > 1) { path.RemoveAt(path.Count - 1); path.AddRange(res); res = path; // Remove trackbacks for (int j = 1; j < res.Count - 1; ++j) { if (j - 1 >= 0 && j + 1 < res.Count) { if (res[j - 1] == res[j + 1]) { res.RemoveAt(j + 1); res.RemoveAt(j); j -= 2; } } } } // Check for partial path. if (res[res.Count - 1] != ag.targetRef) { // Partial path, constrain target position inside // the last polygon. var cr = _navQuery.ClosestPointOnPoly(res[res.Count - 1], targetPos, out var nearest, out var _); if (cr.Succeeded()) { targetPos = nearest; } else { valid = false; } } } if (valid) { // Set current corridor. ag.corridor.SetCorridor(targetPos, res); // Force to update boundary. ag.boundary.Reset(); ag.targetState = DtMoveRequestState.DT_CROWDAGENT_TARGET_VALID; } else { // Something went wrong. ag.targetState = DtMoveRequestState.DT_CROWDAGENT_TARGET_FAILED; } ag.targetReplanTime = 0; } _telemetry.RecordMaxTimeToFindPath(ag.targetReplanWaitTime); ag.targetReplanWaitTime += dt; } } } private void UpdateTopologyOptimization(IList<DtCrowdAgent> agents, float dt) { using var timer = _telemetry.ScopedTimer(DtCrowdTimerLabel.UpdateTopologyOptimization); RcSortedQueue<DtCrowdAgent> queue = new RcSortedQueue<DtCrowdAgent>((a1, a2) => a2.topologyOptTime.CompareTo(a1.topologyOptTime)); foreach (DtCrowdAgent ag in agents) { if (ag.state != DtCrowdAgentState.DT_CROWDAGENT_STATE_WALKING) { continue; } if (ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_NONE || ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_VELOCITY) { continue; } if ((ag.option.updateFlags & DtCrowdAgentParams.DT_CROWD_OPTIMIZE_TOPO) == 0) { continue; } ag.topologyOptTime += dt; if (ag.topologyOptTime >= _config.topologyOptimizationTimeThreshold) { queue.Enqueue(ag); } } while (!queue.IsEmpty()) { DtCrowdAgent ag = queue.Dequeue(); ag.corridor.OptimizePathTopology(_navQuery, _filters[ag.option.queryFilterType], _config.maxTopologyOptimizationIterations); ag.topologyOptTime = 0; } } private void BuildProximityGrid(IList<DtCrowdAgent> agents) { using var timer = _telemetry.ScopedTimer(DtCrowdTimerLabel.BuildProximityGrid); _grid = new DtProximityGrid(_config.maxAgentRadius * 3); foreach (DtCrowdAgent ag in agents) { RcVec3f p = ag.npos; float r = ag.option.radius; _grid.AddItem(ag, p.x - r, p.z - r, p.x + r, p.z + r); } } private void BuildNeighbours(IList<DtCrowdAgent> agents) { using var timer = _telemetry.ScopedTimer(DtCrowdTimerLabel.BuildNeighbours); foreach (DtCrowdAgent ag in agents) { if (ag.state != DtCrowdAgentState.DT_CROWDAGENT_STATE_WALKING) { continue; } // Update the collision boundary after certain distance has been passed or // if it has become invalid. float updateThr = ag.option.collisionQueryRange * 0.25f; if (RcVec3f.Dist2DSqr(ag.npos, ag.boundary.GetCenter()) > Sqr(updateThr) || !ag.boundary.IsValid(_navQuery, _filters[ag.option.queryFilterType])) { ag.boundary.Update(ag.corridor.GetFirstPoly(), ag.npos, ag.option.collisionQueryRange, _navQuery, _filters[ag.option.queryFilterType]); } // Query neighbour agents GetNeighbours(ag.npos, ag.option.height, ag.option.collisionQueryRange, ag, ref ag.neis, _grid); } } private int GetNeighbours(RcVec3f pos, float height, float range, DtCrowdAgent skip, ref List<DtCrowdNeighbour> result, DtProximityGrid grid) { result.Clear(); var proxAgents = new HashSet<DtCrowdAgent>(); int nids = grid.QueryItems(pos.x - range, pos.z - range, pos.x + range, pos.z + range, ref proxAgents); foreach (DtCrowdAgent ag in proxAgents) { if (ag == skip) { continue; } // Check for overlap. RcVec3f diff = pos.Subtract(ag.npos); if (Math.Abs(diff.y) >= (height + ag.option.height) / 2.0f) { continue; } diff.y = 0; float distSqr = RcVec3f.LenSqr(diff); if (distSqr > Sqr(range)) { continue; } result.Add(new DtCrowdNeighbour(ag, distSqr)); } result.Sort((o1, o2) => o1.dist.CompareTo(o2.dist)); return result.Count; } private void FindCorners(IList<DtCrowdAgent> agents, DtCrowdAgentDebugInfo debug) { using var timer = _telemetry.ScopedTimer(DtCrowdTimerLabel.FindCorners); DtCrowdAgent debugAgent = debug != null ? debug.agent : null; foreach (DtCrowdAgent ag in agents) { if (ag.state != DtCrowdAgentState.DT_CROWDAGENT_STATE_WALKING) { continue; } if (ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_NONE || ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_VELOCITY) { continue; } // Find corners for steering ag.corridor.FindCorners(ref ag.corners, DT_CROWDAGENT_MAX_CORNERS, _navQuery, _filters[ag.option.queryFilterType]); // Check to see if the corner after the next corner is directly visible, // and short cut to there. if ((ag.option.updateFlags & DtCrowdAgentParams.DT_CROWD_OPTIMIZE_VIS) != 0 && ag.corners.Count > 0) { RcVec3f target = ag.corners[Math.Min(1, ag.corners.Count - 1)].pos; ag.corridor.OptimizePathVisibility(target, ag.option.pathOptimizationRange, _navQuery, _filters[ag.option.queryFilterType]); // Copy data for debug purposes. if (debugAgent == ag) { debug.optStart = ag.corridor.GetPos(); debug.optEnd = target; } } else { // Copy data for debug purposes. if (debugAgent == ag) { debug.optStart = RcVec3f.Zero; debug.optEnd = RcVec3f.Zero; } } } } private void TriggerOffMeshConnections(IList<DtCrowdAgent> agents) { using var timer = _telemetry.ScopedTimer(DtCrowdTimerLabel.TriggerOffMeshConnections); foreach (DtCrowdAgent ag in agents) { if (ag.state != DtCrowdAgentState.DT_CROWDAGENT_STATE_WALKING) { continue; } if (ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_NONE || ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_VELOCITY) { continue; } // Check float triggerRadius = ag.option.radius * 2.25f; if (ag.OverOffmeshConnection(triggerRadius)) { // Prepare to off-mesh connection. DtCrowdAgentAnimation anim = ag.animation; // Adjust the path over the off-mesh connection. long[] refs = new long[2]; if (ag.corridor.MoveOverOffmeshConnection(ag.corners[ag.corners.Count - 1].refs, refs, ref anim.startPos, ref anim.endPos, _navQuery)) { anim.initPos = ag.npos; anim.polyRef = refs[1]; anim.active = true; anim.t = 0.0f; anim.tmax = (RcVec3f.Dist2D(anim.startPos, anim.endPos) / ag.option.maxSpeed) * 0.5f; ag.state = DtCrowdAgentState.DT_CROWDAGENT_STATE_OFFMESH; ag.corners.Clear(); ag.neis.Clear(); continue; } else { // Path validity check will ensure that bad/blocked connections will be replanned. } } } } private void CalculateSteering(IList<DtCrowdAgent> agents) { using var timer = _telemetry.ScopedTimer(DtCrowdTimerLabel.CalculateSteering); foreach (DtCrowdAgent ag in agents) { if (ag.state != DtCrowdAgentState.DT_CROWDAGENT_STATE_WALKING) { continue; } if (ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_NONE) { continue; } RcVec3f dvel = new RcVec3f(); if (ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_VELOCITY) { dvel = ag.targetPos; ag.desiredSpeed = ag.targetPos.Length(); } else { // Calculate steering direction. if ((ag.option.updateFlags & DtCrowdAgentParams.DT_CROWD_ANTICIPATE_TURNS) != 0) { dvel = ag.CalcSmoothSteerDirection(); } else { dvel = ag.CalcStraightSteerDirection(); } // Calculate speed scale, which tells the agent to slowdown at the end of the path. float slowDownRadius = ag.option.radius * 2; // TODO: make less hacky. float speedScale = ag.GetDistanceToGoal(slowDownRadius) / slowDownRadius; ag.desiredSpeed = ag.option.maxSpeed; dvel = dvel.Scale(ag.desiredSpeed * speedScale); } // Separation if ((ag.option.updateFlags & DtCrowdAgentParams.DT_CROWD_SEPARATION) != 0) { float separationDist = ag.option.collisionQueryRange; float invSeparationDist = 1.0f / separationDist; float separationWeight = ag.option.separationWeight; float w = 0; RcVec3f disp = new RcVec3f(); for (int j = 0; j < ag.neis.Count; ++j) { DtCrowdAgent nei = ag.neis[j].agent; RcVec3f diff = ag.npos.Subtract(nei.npos); diff.y = 0; float distSqr = RcVec3f.LenSqr(diff); if (distSqr < 0.00001f) { continue; } if (distSqr > Sqr(separationDist)) { continue; } float dist = (float)Math.Sqrt(distSqr); float weight = separationWeight * (1.0f - Sqr(dist * invSeparationDist)); disp = RcVec3f.Mad(disp, diff, weight / dist); w += 1.0f; } if (w > 0.0001f) { // Adjust desired velocity. dvel = RcVec3f.Mad(dvel, disp, 1.0f / w); // Clamp desired velocity to desired speed. float speedSqr = RcVec3f.LenSqr(dvel); float desiredSqr = Sqr(ag.desiredSpeed); if (speedSqr > desiredSqr) { dvel = dvel.Scale(desiredSqr / speedSqr); } } } // Set the desired velocity. ag.dvel = dvel; } } private void PlanVelocity(DtCrowdAgentDebugInfo debug, IList<DtCrowdAgent> agents) { using var timer = _telemetry.ScopedTimer(DtCrowdTimerLabel.PlanVelocity); DtCrowdAgent debugAgent = debug != null ? debug.agent : null; foreach (DtCrowdAgent ag in agents) { if (ag.state != DtCrowdAgentState.DT_CROWDAGENT_STATE_WALKING) { continue; } if ((ag.option.updateFlags & DtCrowdAgentParams.DT_CROWD_OBSTACLE_AVOIDANCE) != 0) { _obstacleQuery.Reset(); // Add neighbours as obstacles. for (int j = 0; j < ag.neis.Count; ++j) { DtCrowdAgent nei = ag.neis[j].agent; _obstacleQuery.AddCircle(nei.npos, nei.option.radius, nei.vel, nei.dvel); } // Append neighbour segments as obstacles. for (int j = 0; j < ag.boundary.GetSegmentCount(); ++j) { RcVec3f[] s = ag.boundary.GetSegment(j); RcVec3f s3 = s[1]; //Array.Copy(s, 3, s3, 0, 3); if (DtUtils.TriArea2D(ag.npos, s[0], s3) < 0.0f) { continue; } _obstacleQuery.AddSegment(s[0], s3); } DtObstacleAvoidanceDebugData vod = null; if (debugAgent == ag) { vod = debug.vod; } // Sample new safe velocity. bool adaptive = true; int ns = 0; DtObstacleAvoidanceParams option = _obstacleQueryParams[ag.option.obstacleAvoidanceType]; if (adaptive) { ns = _obstacleQuery.SampleVelocityAdaptive(ag.npos, ag.option.radius, ag.desiredSpeed, ag.vel, ag.dvel, out ag.nvel, option, vod); } else { ns = _obstacleQuery.SampleVelocityGrid(ag.npos, ag.option.radius, ag.desiredSpeed, ag.vel, ag.dvel, out ag.nvel, option, vod); } _velocitySampleCount += ns; } else { // If not using velocity planning, new velocity is directly the desired velocity. ag.nvel = ag.dvel; } } } private void Integrate(float dt, IList<DtCrowdAgent> agents) { using var timer = _telemetry.ScopedTimer(DtCrowdTimerLabel.Integrate); foreach (DtCrowdAgent ag in agents) { if (ag.state != DtCrowdAgentState.DT_CROWDAGENT_STATE_WALKING) { continue; } ag.Integrate(dt); } } private void HandleCollisions(IList<DtCrowdAgent> agents) { using var timer = _telemetry.ScopedTimer(DtCrowdTimerLabel.HandleCollisions); for (int iter = 0; iter < 4; ++iter) { foreach (DtCrowdAgent ag in agents) { long idx0 = ag.idx; if (ag.state != DtCrowdAgentState.DT_CROWDAGENT_STATE_WALKING) { continue; } ag.disp = RcVec3f.Zero; float w = 0; for (int j = 0; j < ag.neis.Count; ++j) { DtCrowdAgent nei = ag.neis[j].agent; long idx1 = nei.idx; RcVec3f diff = ag.npos.Subtract(nei.npos); diff.y = 0; float dist = RcVec3f.LenSqr(diff); if (dist > Sqr(ag.option.radius + nei.option.radius)) { continue; } dist = (float)Math.Sqrt(dist); float pen = (ag.option.radius + nei.option.radius) - dist; if (dist < 0.0001f) { // Agents on top of each other, try to choose diverging separation directions. if (idx0 > idx1) { diff.Set(-ag.dvel.z, 0, ag.dvel.x); } else { diff.Set(ag.dvel.z, 0, -ag.dvel.x); } pen = 0.01f; } else { pen = (1.0f / dist) * (pen * 0.5f) * _config.collisionResolveFactor; } ag.disp = RcVec3f.Mad(ag.disp, diff, pen); w += 1.0f; } if (w > 0.0001f) { float iw = 1.0f / w; ag.disp = ag.disp.Scale(iw); } } foreach (DtCrowdAgent ag in agents) { if (ag.state != DtCrowdAgentState.DT_CROWDAGENT_STATE_WALKING) { continue; } ag.npos = ag.npos.Add(ag.disp); } } } private void MoveAgents(IList<DtCrowdAgent> agents) { using var timer = _telemetry.ScopedTimer(DtCrowdTimerLabel.MoveAgents); foreach (DtCrowdAgent ag in agents) { if (ag.state != DtCrowdAgentState.DT_CROWDAGENT_STATE_WALKING) { continue; } // Move along navmesh. ag.corridor.MovePosition(ag.npos, _navQuery, _filters[ag.option.queryFilterType]); // Get valid constrained position back. ag.npos = ag.corridor.GetPos(); // If not using path, truncate the corridor to just one poly. if (ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_NONE || ag.targetState == DtMoveRequestState.DT_CROWDAGENT_TARGET_VELOCITY) { ag.corridor.Reset(ag.corridor.GetFirstPoly(), ag.npos); ag.partial = false; } } } private void UpdateOffMeshConnections(IList<DtCrowdAgent> agents, float dt) { using var timer = _telemetry.ScopedTimer(DtCrowdTimerLabel.UpdateOffMeshConnections); foreach (DtCrowdAgent ag in agents) { DtCrowdAgentAnimation anim = ag.animation; if (!anim.active) { continue; } anim.t += dt; if (anim.t > anim.tmax) { // Reset animation anim.active = false; // Prepare agent for walking. ag.state = DtCrowdAgentState.DT_CROWDAGENT_STATE_WALKING; continue; } // Update position float ta = anim.tmax * 0.15f; float tb = anim.tmax; if (anim.t < ta) { float u = Tween(anim.t, 0.0f, ta); ag.npos = RcVec3f.Lerp(anim.initPos, anim.startPos, u); } else { float u = Tween(anim.t, ta, tb); ag.npos = RcVec3f.Lerp(anim.startPos, anim.endPos, u); } // Update velocity. ag.vel = RcVec3f.Zero; ag.dvel = RcVec3f.Zero; } } private float Tween(float t, float t0, float t1) { return Clamp((t - t0) / (t1 - t0), 0.0f, 1.0f); } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/DtCrowd.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/DtCrowd.cs", "repo_id": "ET", "token_count": 29301 }
176
namespace DotRecast.Detour.Crowd { public class DtCrowdTimerLabel { public static readonly DtCrowdTimerLabel CheckPathValidity = new DtCrowdTimerLabel(nameof(CheckPathValidity)); public static readonly DtCrowdTimerLabel UpdateMoveRequest = new DtCrowdTimerLabel(nameof(UpdateMoveRequest)); public static readonly DtCrowdTimerLabel PathQueueUpdate = new DtCrowdTimerLabel(nameof(PathQueueUpdate)); public static readonly DtCrowdTimerLabel UpdateTopologyOptimization = new DtCrowdTimerLabel(nameof(UpdateTopologyOptimization)); public static readonly DtCrowdTimerLabel BuildProximityGrid = new DtCrowdTimerLabel(nameof(BuildProximityGrid)); public static readonly DtCrowdTimerLabel BuildNeighbours = new DtCrowdTimerLabel(nameof(BuildNeighbours)); public static readonly DtCrowdTimerLabel FindCorners = new DtCrowdTimerLabel(nameof(FindCorners)); public static readonly DtCrowdTimerLabel TriggerOffMeshConnections = new DtCrowdTimerLabel(nameof(TriggerOffMeshConnections)); public static readonly DtCrowdTimerLabel CalculateSteering = new DtCrowdTimerLabel(nameof(CalculateSteering)); public static readonly DtCrowdTimerLabel PlanVelocity = new DtCrowdTimerLabel(nameof(PlanVelocity)); public static readonly DtCrowdTimerLabel Integrate = new DtCrowdTimerLabel(nameof(Integrate)); public static readonly DtCrowdTimerLabel HandleCollisions = new DtCrowdTimerLabel(nameof(HandleCollisions)); public static readonly DtCrowdTimerLabel MoveAgents = new DtCrowdTimerLabel(nameof(MoveAgents)); public static readonly DtCrowdTimerLabel UpdateOffMeshConnections = new DtCrowdTimerLabel(nameof(UpdateOffMeshConnections)); public readonly string Label; private DtCrowdTimerLabel(string labelName) { Label = labelName; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/DtCrowdTimerLabel.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/DtCrowdTimerLabel.cs", "repo_id": "ET", "token_count": 650 }
177
/* recast4j copyright (c) 2021 Piotr Piastucki piotr@jtilia.org DotRecast Copyright (c) 2023 Choi Ikpil ikpil@naver.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ using DotRecast.Core; namespace DotRecast.Detour.Dynamic.Io { public static class ByteUtils { public static int GetInt(byte[] data, int position, RcByteOrder order) { return order == RcByteOrder.BIG_ENDIAN ? GetIntBE(data, position) : GetIntLE(data, position); } public static int GetIntBE(byte[] data, int position) { return ((data[position] & 0xff) << 24) | ((data[position + 1] & 0xff) << 16) | ((data[position + 2] & 0xff) << 8) | (data[position + 3] & 0xff); } public static int GetIntLE(byte[] data, int position) { return ((data[position + 3] & 0xff) << 24) | ((data[position + 2] & 0xff) << 16) | ((data[position + 1] & 0xff) << 8) | (data[position] & 0xff); } public static int GetShort(byte[] data, int position, RcByteOrder order) { return order == RcByteOrder.BIG_ENDIAN ? GetShortBE(data, position) : GetShortLE(data, position); } public static int GetShortBE(byte[] data, int position) { return ((data[position] & 0xff) << 8) | (data[position + 1] & 0xff); } public static int GetShortLE(byte[] data, int position) { return ((data[position + 1] & 0xff) << 8) | (data[position] & 0xff); } public static int PutInt(int value, byte[] data, int position, RcByteOrder order) { if (order == RcByteOrder.BIG_ENDIAN) { data[position] = (byte)((uint)value >> 24); data[position + 1] = (byte)((uint)value >> 16); data[position + 2] = (byte)((uint)value >> 8); data[position + 3] = (byte)(value & 0xFF); } else { data[position] = (byte)(value & 0xFF); data[position + 1] = (byte)((uint)value >> 8); data[position + 2] = (byte)((uint)value >> 16); data[position + 3] = (byte)((uint)value >> 24); } return position + 4; } public static int PutShort(int value, byte[] data, int position, RcByteOrder order) { if (order == RcByteOrder.BIG_ENDIAN) { data[position] = (byte)((uint)value >> 8); data[position + 1] = (byte)(value & 0xFF); } else { data[position] = (byte)(value & 0xFF); data[position + 1] = (byte)((uint)value >> 8); } return position + 2; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Dynamic/Io/ByteUtils.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Dynamic/Io/ByteUtils.cs", "repo_id": "ET", "token_count": 1557 }
178
fileFormatVersion: 2 guid: 63a0b74c08dba82489dc938f57aa3129 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/BVTreeBuilder.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/BVTreeBuilder.cs.meta", "repo_id": "ET", "token_count": 95 }
179
using DotRecast.Recast; namespace DotRecast.Detour.Extras.Jumplink { public interface IGroundSampler { void Sample(JumpLinkBuilderConfig acfg, RecastBuilderResult result, EdgeSampler es); } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/IGroundSampler.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/IGroundSampler.cs", "repo_id": "ET", "token_count": 79 }
180
using System; using DotRecast.Core; namespace DotRecast.Detour.Extras.Jumplink { public class JumpTrajectory : Trajectory { private readonly float jumpHeight; public JumpTrajectory(float jumpHeight) { this.jumpHeight = jumpHeight; } public override RcVec3f Apply(RcVec3f start, RcVec3f end, float u) { return new RcVec3f { x = Lerp(start.x, end.x, u), y = InterpolateHeight(start.y, end.y, u), z = Lerp(start.z, end.z, u) }; } private float InterpolateHeight(float ys, float ye, float u) { if (u == 0f) { return ys; } else if (u == 1.0f) { return ye; } float h1, h2; if (ys >= ye) { // jump down h1 = jumpHeight; h2 = jumpHeight + ys - ye; } else { // jump up h1 = jumpHeight + ys - ye; h2 = jumpHeight; } float t = (float)(Math.Sqrt(h1) / (Math.Sqrt(h2) + Math.Sqrt(h1))); if (u <= t) { float v1 = 1.0f - (u / t); return ys + h1 - h1 * v1 * v1; } float v = (u - t) / (1.0f - t); return ys + h1 - h2 * v * v; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/JumpTrajectory.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/JumpTrajectory.cs", "repo_id": "ET", "token_count": 948 }
181
fileFormatVersion: 2 guid: 08c1d87f203838441a485e23de767c14 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.TileCache/DtCompressedTile.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.TileCache/DtCompressedTile.cs.meta", "repo_id": "ET", "token_count": 93 }
182
fileFormatVersion: 2 guid: 811f303a5087f704d981285221ff6e5d MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.TileCache/Io/DtTileCacheReader.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.TileCache/Io/DtTileCacheReader.cs.meta", "repo_id": "ET", "token_count": 94 }
183
using System.Collections.Generic; namespace DotRecast.Detour { public class BVItemYComparer : IComparer<BVItem> { public static readonly BVItemYComparer Shared = new BVItemYComparer(); private BVItemYComparer() { } public int Compare(BVItem a, BVItem b) { return a.bmin[1].CompareTo(b.bmin[1]); } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/BVItemYComparer.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/BVItemYComparer.cs", "repo_id": "ET", "token_count": 188 }
184
namespace DotRecast.Detour { public readonly struct DtFindPathOption { public static readonly DtFindPathOption NoOption = new DtFindPathOption(DefaultQueryHeuristic.Default, 0, 0); public static readonly DtFindPathOption AnyAngle = new DtFindPathOption(DefaultQueryHeuristic.Default, DtNavMeshQuery.DT_FINDPATH_ANY_ANGLE, float.MaxValue); public static readonly DtFindPathOption ZeroScale = new DtFindPathOption(new DefaultQueryHeuristic(0.0f), 0, 0); public readonly IQueryHeuristic heuristic; public readonly int options; public readonly float raycastLimit; public DtFindPathOption(IQueryHeuristic heuristic, int options, float raycastLimit) { this.heuristic = heuristic; this.options = options; this.raycastLimit = raycastLimit; } public DtFindPathOption(int options, float raycastLimit) : this(DefaultQueryHeuristic.Default, options, raycastLimit) { } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtFindPathOption.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtFindPathOption.cs", "repo_id": "ET", "token_count": 400 }
185
/* Copyright (c) 2009-2010 Mikko Mononen memon@inside.org recast4j copyright (c) 2015-2019 Piotr Piastucki piotr@jtilia.org DotRecast Copyright (c) 2023 Choi Ikpil ikpil@naver.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ using DotRecast.Core; namespace DotRecast.Detour { /** * Configuration parameters used to define multi-tile navigation meshes. The values are used to allocate space during * the initialization of a navigation mesh. * * @see NavMesh */ public struct DtNavMeshParams { /** The world space origin of the navigation mesh's tile space. [(x, y, z)] */ public RcVec3f orig; /** The width of each tile. (Along the x-axis.) */ public float tileWidth; /** The height of each tile. (Along the z-axis.) */ public float tileHeight; /** The maximum number of tiles the navigation mesh can contain. */ public int maxTiles; /** The maximum number of polygons each tile can contain. */ public int maxPolys; } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtNavMeshParams.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtNavMeshParams.cs", "repo_id": "ET", "token_count": 527 }
186
/* Copyright (c) 2009-2010 Mikko Mononen memon@inside.org recast4j copyright (c) 2015-2019 Piotr Piastucki piotr@jtilia.org DotRecast Copyright (c) 2023 Choi Ikpil ikpil@naver.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ namespace DotRecast.Detour { /** Defines a polygon within a MeshTile object. */ public class DtPoly { /** The polygon is a standard convex polygon that is part of the surface of the mesh. */ public const int DT_POLYTYPE_GROUND = 0; /** The polygon is an off-mesh connection consisting of two vertices. */ public const int DT_POLYTYPE_OFFMESH_CONNECTION = 1; public readonly int index; /** The indices of the polygon's vertices. The actual vertices are located in MeshTile::verts. */ public readonly int[] verts; /** Packed data representing neighbor polygons references and flags for each edge. */ public readonly int[] neis; /** The user defined polygon flags. */ public int flags; /** The number of vertices in the polygon. */ public int vertCount; /// The bit packed area id and polygon type. /// @note Use the structure's set and get methods to access this value. public int areaAndtype; public DtPoly(int index, int maxVertsPerPoly) { this.index = index; verts = new int[maxVertsPerPoly]; neis = new int[maxVertsPerPoly]; } /** Sets the user defined area id. [Limit: &lt; {@link org.recast4j.detour.NavMesh#DT_MAX_AREAS}] */ public void SetArea(int a) { areaAndtype = (areaAndtype & 0xc0) | (a & 0x3f); } /** Sets the polygon type. (See: #dtPolyTypes.) */ public void SetPolyType(int t) { areaAndtype = (areaAndtype & 0x3f) | (t << 6); } /** Gets the user defined area id. */ public int GetArea() { return areaAndtype & 0x3f; } /** Gets the polygon type. (See: #dtPolyTypes) */ public int GetPolyType() { return areaAndtype >> 6; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtPoly.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtPoly.cs", "repo_id": "ET", "token_count": 1091 }
187
namespace DotRecast.Detour { public readonly struct DtSegInterval { public readonly long refs; public readonly int tmin; public readonly int tmax; public DtSegInterval(long refs, int tmin, int tmax) { this.refs = refs; this.tmin = tmin; this.tmax = tmax; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtSegInterval.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtSegInterval.cs", "repo_id": "ET", "token_count": 188 }
188
fileFormatVersion: 2 guid: b0a01b7388685794689768195bc8edaf folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/Geom.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/Geom.meta", "repo_id": "ET", "token_count": 68 }
189
fileFormatVersion: 2 guid: b23cdc04270a5e045bb0f4f4c198e384 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcContourSet.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcContourSet.cs.meta", "repo_id": "ET", "token_count": 95 }
190
fileFormatVersion: 2 guid: 92d78e46578e77640ac67b6e2fe00cd3 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcPartitionType.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcPartitionType.cs.meta", "repo_id": "ET", "token_count": 94 }
191
using System; using System.Diagnostics; using System.Runtime.CompilerServices; namespace ET { [AsyncMethodBuilder(typeof (AsyncETVoidMethodBuilder))] internal struct ETVoid: ICriticalNotifyCompletion { [DebuggerHidden] public void Coroutine() { } [DebuggerHidden] public bool IsCompleted => true; [DebuggerHidden] public void OnCompleted(Action continuation) { } [DebuggerHidden] public void UnsafeOnCompleted(Action continuation) { } } }
ET/Unity/Assets/Scripts/ThirdParty/ETTask/ETVoid.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/ETTask/ETVoid.cs", "repo_id": "ET", "token_count": 247 }
192
fileFormatVersion: 2 guid: 065051fee12dc95449d2eb1dd337adbe MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/Kcp/Utils.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/Kcp/Utils.cs.meta", "repo_id": "ET", "token_count": 91 }
193
using System; namespace NativeCollection.UnsafeType { public static class HashHelpers { public const uint HashCollisionThreshold = 100; // This is the maximum prime smaller than Array.MaxLength. public const int MaxPrimeArrayLength = 0x7FFFFFC3; public const int HashPrime = 101; private static readonly int[] s_primes = new int[72] { 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369 }; public static bool IsPrime(int candidate) { if ((candidate & 1) == 0) return candidate == 2; int num = (int) Math.Sqrt((double) candidate); for (int index = 3; index <= num; index += 2) { if (candidate % index == 0) return false; } return true; } public static int GetPrime(int min) { if (min < 0) throw new ArgumentException("SR.Arg_HTCapacityOverflow"); foreach (int prime in HashHelpers.s_primes) { if (prime >= min) return prime; } for (int candidate = min | 1; candidate < int.MaxValue; candidate += 2) { if (HashHelpers.IsPrime(candidate) && (candidate - 1) % 101 != 0) return candidate; } return min; } public static int ExpandPrime(int oldSize) { int min = 2 * oldSize; return (uint) min > 2147483587U && 2147483587 > oldSize ? 2147483587 : HashHelpers.GetPrime(min); } /// <summary>Returns approximate reciprocal of the divisor: ceil(2**64 / divisor).</summary> /// <remarks>This should only be used on 64-bit.</remarks> public static ulong GetFastModMultiplier(uint divisor) => ulong.MaxValue / divisor + 1; } }
ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/HashHelpers.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/HashHelpers.cs", "repo_id": "ET", "token_count": 1552 }
194
using System; using System.Runtime.CompilerServices; namespace NativeCollection.UnsafeType { public interface IPool : IDisposable { public void OnReturnToPool(); public void OnGetFromPool(); } public unsafe struct NativeStackPool<T> : IDisposable where T: unmanaged,IPool { public int MaxSize { get; private set; } private Stack<IntPtr>* _stack; public static NativeStackPool<T>* Create(int maxPoolSize) { NativeStackPool<T>* pool = (NativeStackPool<T>*)NativeMemoryHelper.Alloc((UIntPtr)Unsafe.SizeOf<NativeStackPool<T>>()); pool->_stack = Stack<IntPtr>.Create(); pool->MaxSize = maxPoolSize; return pool; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T* Alloc() { if (_stack->TryPop(out var itemPtr)) { var item = (T*)itemPtr; item->OnGetFromPool(); return item; } return null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Return(T* ptr) { if (_stack->Count>=MaxSize) { ptr->Dispose(); NativeMemoryHelper.Free(ptr); NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<T>()); return; } ptr->OnReturnToPool(); _stack->Push(new IntPtr(ptr)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool IsPoolMax() { return _stack->Count >= MaxSize; } public void Clear() { while (_stack->TryPop(out var ptr)) { T* item = (T*)ptr; item->Dispose(); NativeMemoryHelper.Free(item); NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<T>()); } } public void Dispose() { Clear(); _stack->Dispose(); NativeMemoryHelper.Free(_stack); NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<Stack<T>>()); } } }
ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/NativeStackPool.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/NativeStackPool.cs", "repo_id": "ET", "token_count": 1133 }
195
using System; using System.IO; namespace TrueSync { /// <summary> /// Represents a Q31.32 fixed-point number. /// </summary> [Serializable] public partial struct FP : IEquatable<FP>, IComparable<FP> { public long _serializedValue; public const long MAX_VALUE = long.MaxValue; public const long MIN_VALUE = long.MinValue; public const int NUM_BITS = 64; public const int FRACTIONAL_PLACES = 32; public const long ONE = 1L << FRACTIONAL_PLACES; public const long TEN = 10L << FRACTIONAL_PLACES; public const long HALF = 1L << (FRACTIONAL_PLACES - 1); public const long PI_TIMES_2 = 0x6487ED511; public const long PI = 0x3243F6A88; public const long PI_OVER_2 = 0x1921FB544; public const long LN2 = 0xB17217F7; public const long LOG2MAX = 0x1F00000000; public const long LOG2MIN = -0x2000000000; public const int LUT_SIZE = (int)(PI_OVER_2 >> 15); // Precision of this type is 2^-32, that is 2,3283064365386962890625E-10 public static readonly decimal Precision = (decimal)(new FP(1L));//0.00000000023283064365386962890625m; public static readonly FP MaxValue = new FP(MAX_VALUE-1); public static readonly FP MinValue = new FP(MIN_VALUE+2); public static readonly FP One = new FP(ONE); public static readonly FP Ten = new FP(TEN); public static readonly FP Half = new FP(HALF); public static readonly FP Zero = new FP(); public static readonly FP PositiveInfinity = new FP(MAX_VALUE); public static readonly FP NegativeInfinity = new FP(MIN_VALUE+1); public static readonly FP NaN = new FP(MIN_VALUE); public static readonly FP EN1 = FP.One / 10; public static readonly FP EN2 = FP.One / 100; public static readonly FP EN3 = FP.One / 1000; public static readonly FP EN4 = FP.One / 10000; public static readonly FP EN5 = FP.One / 100000; public static readonly FP EN6 = FP.One / 1000000; public static readonly FP EN7 = FP.One / 10000000; public static readonly FP EN8 = FP.One / 100000000; public static readonly FP Epsilon = FP.EN3; /// <summary> /// The value of Pi /// </summary> public static readonly FP Pi = new FP(PI); public static readonly FP PiOver2 = new FP(PI_OVER_2); public static readonly FP PiTimes2 = new FP(PI_TIMES_2); public static readonly FP PiInv = (FP)0.3183098861837906715377675267M; public static readonly FP PiOver2Inv = (FP)0.6366197723675813430755350535M; public static readonly FP Deg2Rad = Pi / new FP(180); public static readonly FP Rad2Deg = new FP(180) / Pi; public static readonly FP LutInterval = (FP)(LUT_SIZE - 1) / PiOver2; public static readonly FP Log2Max = new FP(LOG2MAX); public static readonly FP Log2Min = new FP(LOG2MIN); public static readonly FP Ln2 = new FP(LN2); /// <summary> /// Returns a number indicating the sign of a Fix64 number. /// Returns 1 if the value is positive, 0 if is 0, and -1 if it is negative. /// </summary> public static int Sign(FP value) { return value._serializedValue < 0 ? -1 : value._serializedValue > 0 ? 1 : 0; } /// <summary> /// Returns the absolute value of a Fix64 number. /// Note: Abs(Fix64.MinValue) == Fix64.MaxValue. /// </summary> public static FP Abs(FP value) { if (value._serializedValue == MIN_VALUE) { return MaxValue; } // branchless implementation, see http://www.strchr.com/optimized_abs_function var mask = value._serializedValue >> 63; FP result; result._serializedValue = (value._serializedValue + mask) ^ mask; return result; //return new FP((value._serializedValue + mask) ^ mask); } /// <summary> /// Returns the absolute value of a Fix64 number. /// FastAbs(Fix64.MinValue) is undefined. /// </summary> public static FP FastAbs(FP value) { // branchless implementation, see http://www.strchr.com/optimized_abs_function var mask = value._serializedValue >> 63; FP result; result._serializedValue = (value._serializedValue + mask) ^ mask; return result; //return new FP((value._serializedValue + mask) ^ mask); } /// <summary> /// Returns the largest integer less than or equal to the specified number. /// </summary> public static FP Floor(FP value) { // Just zero out the fractional part FP result; result._serializedValue = (long)((ulong)value._serializedValue & 0xFFFFFFFF00000000); return result; //return new FP((long)((ulong)value._serializedValue & 0xFFFFFFFF00000000)); } /// <summary> /// Returns the smallest integral value that is greater than or equal to the specified number. /// </summary> public static FP Ceiling(FP value) { var hasFractionalPart = (value._serializedValue & 0x00000000FFFFFFFF) != 0; return hasFractionalPart ? Floor(value) + One : value; } /// <summary> /// Rounds a value to the nearest integral value. /// If the value is halfway between an even and an uneven value, returns the even value. /// </summary> public static FP Round(FP value) { var fractionalPart = value._serializedValue & 0x00000000FFFFFFFF; var integralPart = Floor(value); if (fractionalPart < 0x80000000) { return integralPart; } if (fractionalPart > 0x80000000) { return integralPart + One; } // if number is halfway between two values, round to the nearest even number // this is the method used by System.Math.Round(). return (integralPart._serializedValue & ONE) == 0 ? integralPart : integralPart + One; } /// <summary> /// Adds x and y. Performs saturating addition, i.e. in case of overflow, /// rounds to MinValue or MaxValue depending on sign of operands. /// </summary> public static FP operator +(FP x, FP y) { FP result; result._serializedValue = x._serializedValue + y._serializedValue; return result; //return new FP(x._serializedValue + y._serializedValue); } /// <summary> /// Adds x and y performing overflow checking. Should be inlined by the CLR. /// </summary> public static FP OverflowAdd(FP x, FP y) { var xl = x._serializedValue; var yl = y._serializedValue; var sum = xl + yl; // if signs of operands are equal and signs of sum and x are different if (((~(xl ^ yl) & (xl ^ sum)) & MIN_VALUE) != 0) { sum = xl > 0 ? MAX_VALUE : MIN_VALUE; } FP result; result._serializedValue = sum; return result; //return new FP(sum); } /// <summary> /// Adds x and y witout performing overflow checking. Should be inlined by the CLR. /// </summary> public static FP FastAdd(FP x, FP y) { FP result; result._serializedValue = x._serializedValue + y._serializedValue; return result; //return new FP(x._serializedValue + y._serializedValue); } /// <summary> /// Subtracts y from x. Performs saturating substraction, i.e. in case of overflow, /// rounds to MinValue or MaxValue depending on sign of operands. /// </summary> public static FP operator -(FP x, FP y) { FP result; result._serializedValue = x._serializedValue - y._serializedValue; return result; //return new FP(x._serializedValue - y._serializedValue); } /// <summary> /// Subtracts y from x witout performing overflow checking. Should be inlined by the CLR. /// </summary> public static FP OverflowSub(FP x, FP y) { var xl = x._serializedValue; var yl = y._serializedValue; var diff = xl - yl; // if signs of operands are different and signs of sum and x are different if ((((xl ^ yl) & (xl ^ diff)) & MIN_VALUE) != 0) { diff = xl < 0 ? MIN_VALUE : MAX_VALUE; } FP result; result._serializedValue = diff; return result; //return new FP(diff); } /// <summary> /// Subtracts y from x witout performing overflow checking. Should be inlined by the CLR. /// </summary> public static FP FastSub(FP x, FP y) { return new FP(x._serializedValue - y._serializedValue); } static long AddOverflowHelper(long x, long y, ref bool overflow) { var sum = x + y; // x + y overflows if sign(x) ^ sign(y) != sign(sum) overflow |= ((x ^ y ^ sum) & MIN_VALUE) != 0; return sum; } public static FP operator *(FP x, FP y) { var xl = x._serializedValue; var yl = y._serializedValue; var xlo = (ulong)(xl & 0x00000000FFFFFFFF); var xhi = xl >> FRACTIONAL_PLACES; var ylo = (ulong)(yl & 0x00000000FFFFFFFF); var yhi = yl >> FRACTIONAL_PLACES; var lolo = xlo * ylo; var lohi = (long)xlo * yhi; var hilo = xhi * (long)ylo; var hihi = xhi * yhi; var loResult = lolo >> FRACTIONAL_PLACES; var midResult1 = lohi; var midResult2 = hilo; var hiResult = hihi << FRACTIONAL_PLACES; var sum = (long)loResult + midResult1 + midResult2 + hiResult; FP result;// = default(FP); result._serializedValue = sum; return result; } /// <summary> /// Performs multiplication without checking for overflow. /// Useful for performance-critical code where the values are guaranteed not to cause overflow /// </summary> public static FP OverflowMul(FP x, FP y) { var xl = x._serializedValue; var yl = y._serializedValue; var xlo = (ulong)(xl & 0x00000000FFFFFFFF); var xhi = xl >> FRACTIONAL_PLACES; var ylo = (ulong)(yl & 0x00000000FFFFFFFF); var yhi = yl >> FRACTIONAL_PLACES; var lolo = xlo * ylo; var lohi = (long)xlo * yhi; var hilo = xhi * (long)ylo; var hihi = xhi * yhi; var loResult = lolo >> FRACTIONAL_PLACES; var midResult1 = lohi; var midResult2 = hilo; var hiResult = hihi << FRACTIONAL_PLACES; bool overflow = false; var sum = AddOverflowHelper((long)loResult, midResult1, ref overflow); sum = AddOverflowHelper(sum, midResult2, ref overflow); sum = AddOverflowHelper(sum, hiResult, ref overflow); bool opSignsEqual = ((xl ^ yl) & MIN_VALUE) == 0; // if signs of operands are equal and sign of result is negative, // then multiplication overflowed positively // the reverse is also true if (opSignsEqual) { if (sum < 0 || (overflow && xl > 0)) { return MaxValue; } } else { if (sum > 0) { return MinValue; } } // if the top 32 bits of hihi (unused in the result) are neither all 0s or 1s, // then this means the result overflowed. var topCarry = hihi >> FRACTIONAL_PLACES; if (topCarry != 0 && topCarry != -1 /*&& xl != -17 && yl != -17*/) { return opSignsEqual ? MaxValue : MinValue; } // If signs differ, both operands' magnitudes are greater than 1, // and the result is greater than the negative operand, then there was negative overflow. if (!opSignsEqual) { long posOp, negOp; if (xl > yl) { posOp = xl; negOp = yl; } else { posOp = yl; negOp = xl; } if (sum > negOp && negOp < -ONE && posOp > ONE) { return MinValue; } } FP result; result._serializedValue = sum; return result; //return new FP(sum); } /// <summary> /// Performs multiplication without checking for overflow. /// Useful for performance-critical code where the values are guaranteed not to cause overflow /// </summary> public static FP FastMul(FP x, FP y) { var xl = x._serializedValue; var yl = y._serializedValue; var xlo = (ulong)(xl & 0x00000000FFFFFFFF); var xhi = xl >> FRACTIONAL_PLACES; var ylo = (ulong)(yl & 0x00000000FFFFFFFF); var yhi = yl >> FRACTIONAL_PLACES; var lolo = xlo * ylo; var lohi = (long)xlo * yhi; var hilo = xhi * (long)ylo; var hihi = xhi * yhi; var loResult = lolo >> FRACTIONAL_PLACES; var midResult1 = lohi; var midResult2 = hilo; var hiResult = hihi << FRACTIONAL_PLACES; var sum = (long)loResult + midResult1 + midResult2 + hiResult; FP result;// = default(FP); result._serializedValue = sum; return result; //return new FP(sum); } //[MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static int CountLeadingZeroes(ulong x) { int result = 0; while ((x & 0xF000000000000000) == 0) { result += 4; x <<= 4; } while ((x & 0x8000000000000000) == 0) { result += 1; x <<= 1; } return result; } public static FP operator /(FP x, FP y) { var xl = x._serializedValue; var yl = y._serializedValue; if (yl == 0) { return MAX_VALUE; //throw new DivideByZeroException(); } var remainder = (ulong)(xl >= 0 ? xl : -xl); var divider = (ulong)(yl >= 0 ? yl : -yl); var quotient = 0UL; var bitPos = NUM_BITS / 2 + 1; // If the divider is divisible by 2^n, take advantage of it. while ((divider & 0xF) == 0 && bitPos >= 4) { divider >>= 4; bitPos -= 4; } while (remainder != 0 && bitPos >= 0) { int shift = CountLeadingZeroes(remainder); if (shift > bitPos) { shift = bitPos; } remainder <<= shift; bitPos -= shift; var div = remainder / divider; remainder = remainder % divider; quotient += div << bitPos; // Detect overflow if ((div & ~(0xFFFFFFFFFFFFFFFF >> bitPos)) != 0) { return ((xl ^ yl) & MIN_VALUE) == 0 ? MaxValue : MinValue; } remainder <<= 1; --bitPos; } // rounding ++quotient; var result = (long)(quotient >> 1); if (((xl ^ yl) & MIN_VALUE) != 0) { result = -result; } FP r; r._serializedValue = result; return r; //return new FP(result); } public static FP operator %(FP x, FP y) { FP result; result._serializedValue = x._serializedValue == MIN_VALUE & y._serializedValue == -1 ? 0 : x._serializedValue % y._serializedValue; return result; //return new FP( // x._serializedValue == MIN_VALUE & y._serializedValue == -1 ? // 0 : // x._serializedValue % y._serializedValue); } /// <summary> /// Performs modulo as fast as possible; throws if x == MinValue and y == -1. /// Use the operator (%) for a more reliable but slower modulo. /// </summary> public static FP FastMod(FP x, FP y) { FP result; result._serializedValue = x._serializedValue % y._serializedValue; return result; //return new FP(x._serializedValue % y._serializedValue); } public static FP operator -(FP x) { return x._serializedValue == MIN_VALUE ? MaxValue : new FP(-x._serializedValue); } public static bool operator ==(FP x, FP y) { return x._serializedValue == y._serializedValue; } public static bool operator !=(FP x, FP y) { return x._serializedValue != y._serializedValue; } public static bool operator >(FP x, FP y) { return x._serializedValue > y._serializedValue; } public static bool operator <(FP x, FP y) { return x._serializedValue < y._serializedValue; } public static bool operator >=(FP x, FP y) { return x._serializedValue >= y._serializedValue; } public static bool operator <=(FP x, FP y) { return x._serializedValue <= y._serializedValue; } /// <summary> /// Returns the square root of a specified number. /// </summary> /// <exception cref="ArgumentOutOfRangeException"> /// The argument was negative. /// </exception> public static FP Sqrt(FP x) { var xl = x._serializedValue; if (xl < 0) { // We cannot represent infinities like Single and Double, and Sqrt is // mathematically undefined for x < 0. So we just throw an exception. throw new ArgumentOutOfRangeException("Negative value passed to Sqrt", "x"); } var num = (ulong)xl; var result = 0UL; // second-to-top bit var bit = 1UL << (NUM_BITS - 2); while (bit > num) { bit >>= 2; } // The main part is executed twice, in order to avoid // using 128 bit values in computations. for (var i = 0; i < 2; ++i) { // First we get the top 48 bits of the answer. while (bit != 0) { if (num >= result + bit) { num -= result + bit; result = (result >> 1) + bit; } else { result = result >> 1; } bit >>= 2; } if (i == 0) { // Then process it again to get the lowest 16 bits. if (num > (1UL << (NUM_BITS / 2)) - 1) { // The remainder 'num' is too large to be shifted left // by 32, so we have to add 1 to result manually and // adjust 'num' accordingly. // num = a - (result + 0.5)^2 // = num + result^2 - (result + 0.5)^2 // = num - result - 0.5 num -= result; num = (num << (NUM_BITS / 2)) - 0x80000000UL; result = (result << (NUM_BITS / 2)) + 0x80000000UL; } else { num <<= (NUM_BITS / 2); result <<= (NUM_BITS / 2); } bit = 1UL << (NUM_BITS / 2 - 2); } } // Finally, if next bit would have been 1, round the result upwards. if (num > result) { ++result; } FP r; r._serializedValue = (long)result; return r; //return new FP((long)result); } /// <summary> /// Returns the Sine of x. /// This function has about 9 decimals of accuracy for small values of x. /// It may lose accuracy as the value of x grows. /// Performance: about 25% slower than Math.Sin() in x64, and 200% slower in x86. /// </summary> public static FP Sin(FP x) { bool flipHorizontal, flipVertical; var clampedL = ClampSinValue(x._serializedValue, out flipHorizontal, out flipVertical); var clamped = new FP(clampedL); // Find the two closest values in the LUT and perform linear interpolation // This is what kills the performance of this function on x86 - x64 is fine though var rawIndex = FastMul(clamped, LutInterval); var roundedIndex = Round(rawIndex); var indexError = 0;//FastSub(rawIndex, roundedIndex); var nearestValue = new FP(SinLut[flipHorizontal ? SinLut.Length - 1 - (int)roundedIndex : (int)roundedIndex]); var secondNearestValue = new FP(SinLut[flipHorizontal ? SinLut.Length - 1 - (int)roundedIndex - Sign(indexError) : (int)roundedIndex + Sign(indexError)]); var delta = FastMul(indexError, FastAbs(FastSub(nearestValue, secondNearestValue)))._serializedValue; var interpolatedValue = nearestValue._serializedValue + (flipHorizontal ? -delta : delta); var finalValue = flipVertical ? -interpolatedValue : interpolatedValue; //FP a2 = new FP(finalValue); FP a2; a2._serializedValue = finalValue; return a2; } /// <summary> /// Returns a rough approximation of the Sine of x. /// This is at least 3 times faster than Sin() on x86 and slightly faster than Math.Sin(), /// however its accuracy is limited to 4-5 decimals, for small enough values of x. /// </summary> public static FP FastSin(FP x) { bool flipHorizontal, flipVertical; var clampedL = ClampSinValue(x._serializedValue, out flipHorizontal, out flipVertical); // Here we use the fact that the SinLut table has a number of entries // equal to (PI_OVER_2 >> 15) to use the angle to index directly into it var rawIndex = (uint)(clampedL >> 15); if (rawIndex >= LUT_SIZE) { rawIndex = LUT_SIZE - 1; } var nearestValue = SinLut[flipHorizontal ? SinLut.Length - 1 - (int)rawIndex : (int)rawIndex]; FP result; result._serializedValue = flipVertical ? -nearestValue : nearestValue; return result; //return new FP(flipVertical ? -nearestValue : nearestValue); } //[MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static long ClampSinValue(long angle, out bool flipHorizontal, out bool flipVertical) { // Clamp value to 0 - 2*PI using modulo; this is very slow but there's no better way AFAIK var clamped2Pi = angle % PI_TIMES_2; if (angle < 0) { clamped2Pi += PI_TIMES_2; } // The LUT contains values for 0 - PiOver2; every other value must be obtained by // vertical or horizontal mirroring flipVertical = clamped2Pi >= PI; // obtain (angle % PI) from (angle % 2PI) - much faster than doing another modulo var clampedPi = clamped2Pi; while (clampedPi >= PI) { clampedPi -= PI; } flipHorizontal = clampedPi >= PI_OVER_2; // obtain (angle % PI_OVER_2) from (angle % PI) - much faster than doing another modulo var clampedPiOver2 = clampedPi; if (clampedPiOver2 >= PI_OVER_2) { clampedPiOver2 -= PI_OVER_2; } return clampedPiOver2; } /// <summary> /// Returns the cosine of x. /// See Sin() for more details. /// </summary> public static FP Cos(FP x) { var xl = x._serializedValue; var rawAngle = xl + (xl > 0 ? -PI - PI_OVER_2 : PI_OVER_2); FP a2 = Sin(new FP(rawAngle)); return a2; } /// <summary> /// Returns a rough approximation of the cosine of x. /// See FastSin for more details. /// </summary> public static FP FastCos(FP x) { var xl = x._serializedValue; var rawAngle = xl + (xl > 0 ? -PI - PI_OVER_2 : PI_OVER_2); return FastSin(new FP(rawAngle)); } /// <summary> /// Returns the tangent of x. /// </summary> /// <remarks> /// This function is not well-tested. It may be wildly inaccurate. /// </remarks> public static FP Tan(FP x) { var clampedPi = x._serializedValue % PI; var flip = false; if (clampedPi < 0) { clampedPi = -clampedPi; flip = true; } if (clampedPi > PI_OVER_2) { flip = !flip; clampedPi = PI_OVER_2 - (clampedPi - PI_OVER_2); } var clamped = new FP(clampedPi); // Find the two closest values in the LUT and perform linear interpolation var rawIndex = FastMul(clamped, LutInterval); var roundedIndex = Round(rawIndex); var indexError = FastSub(rawIndex, roundedIndex); var nearestValue = new FP(TanLut[(int)roundedIndex]); var secondNearestValue = new FP(TanLut[(int)roundedIndex + Sign(indexError)]); var delta = FastMul(indexError, FastAbs(FastSub(nearestValue, secondNearestValue)))._serializedValue; var interpolatedValue = nearestValue._serializedValue + delta; var finalValue = flip ? -interpolatedValue : interpolatedValue; FP a2 = new FP(finalValue); return a2; } /// <summary> /// Returns the arctan of of the specified number, calculated using Euler series /// This function has at least 7 decimals of accuracy. /// </summary> public static FP Atan(FP z) { if (z.RawValue == 0) return Zero; // Force positive values for argument // Atan(-z) = -Atan(z). var neg = z.RawValue < 0; if (neg) { z = -z; } FP result; var two = (FP)2; var three = (FP)3; bool invert = z > One; if (invert) z = One / z; result = One; var term = One; var zSq = z * z; var zSq2 = zSq * two; var zSqPlusOne = zSq + One; var zSq12 = zSqPlusOne * two; var dividend = zSq2; var divisor = zSqPlusOne * three; for (var i = 2; i < 30; ++i) { term *= dividend / divisor; result += term; dividend += zSq2; divisor += zSq12; if (term.RawValue == 0) break; } result = result * z / zSqPlusOne; if (invert) { result = PiOver2 - result; } if (neg) { result = -result; } return result; } public static FP Atan2(FP y, FP x) { var yl = y._serializedValue; var xl = x._serializedValue; if (xl == 0) { if (yl > 0) { return PiOver2; } if (yl == 0) { return Zero; } return -PiOver2; } FP atan; var z = y / x; FP sm = FP.EN2 * 28; // Deal with overflow if (One + sm * z * z == MaxValue) { return y < Zero ? -PiOver2 : PiOver2; } if (Abs(z) < One) { atan = z / (One + sm * z * z); if (xl < 0) { if (yl < 0) { return atan - Pi; } return atan + Pi; } } else { atan = PiOver2 - z / (z * z + sm); if (yl < 0) { return atan - Pi; } } return atan; } public static FP Asin(FP value) { return FastSub(PiOver2, Acos(value)); } /// <summary> /// Returns the arccos of of the specified number, calculated using Atan and Sqrt /// This function has at least 7 decimals of accuracy. /// </summary> public static FP Acos(FP x) { if (x < -One || x > One) { throw new ArgumentOutOfRangeException("Must between -FP.One and FP.One", "x"); } if (x.RawValue == 0) return PiOver2; var result = Atan(Sqrt(One - x * x) / x); return x.RawValue < 0 ? result + Pi : result; } public static implicit operator FP(long value) { FP result; result._serializedValue = value * ONE; return result; //return new FP(value * ONE); } public static explicit operator long(FP value) { return value._serializedValue >> FRACTIONAL_PLACES; } public static implicit operator FP(float value) { FP result; result._serializedValue = (long)(value * ONE); return result; //return new FP((long)(value * ONE)); } public static explicit operator float(FP value) { return (float)value._serializedValue / ONE; } public static implicit operator FP(double value) { FP result; result._serializedValue = (long)(value * ONE); return result; //return new FP((long)(value * ONE)); } public static explicit operator double(FP value) { return (double)value._serializedValue / ONE; } public static explicit operator FP(decimal value) { FP result; result._serializedValue = (long)(value * ONE); return result; //return new FP((long)(value * ONE)); } public static implicit operator FP(int value) { FP result; result._serializedValue = value * ONE; return result; //return new FP(value * ONE); } public static explicit operator decimal(FP value) { return (decimal)value._serializedValue / ONE; } public float AsFloat() { return (float) this; } public int AsInt() { return (int) this; } public long AsLong() { return (long)this; } public double AsDouble() { return (double)this; } public decimal AsDecimal() { return (decimal)this; } public static float ToFloat(FP value) { return (float)value; } public static int ToInt(FP value) { return (int)value; } public static FP FromFloat(float value) { return (FP)value; } public static bool IsInfinity(FP value) { return value == NegativeInfinity || value == PositiveInfinity; } public static bool IsNaN(FP value) { return value == NaN; } public override bool Equals(object obj) { return obj is FP && ((FP)obj)._serializedValue == _serializedValue; } public override int GetHashCode() { return _serializedValue.GetHashCode(); } public bool Equals(FP other) { return _serializedValue == other._serializedValue; } public int CompareTo(FP other) { return _serializedValue.CompareTo(other._serializedValue); } public override string ToString() { return ((float)this).ToString(); } public string ToString(IFormatProvider provider) { return ((float)this).ToString(provider); } public string ToString(string format) { return ((float)this).ToString(format); } public static FP FromRaw(long rawValue) { return new FP(rawValue); } internal static void GenerateAcosLut() { using (var writer = new StreamWriter("Fix64AcosLut.cs")) { writer.Write( @"namespace TrueSync { partial struct FP { public static readonly long[] AcosLut = new[] {"); int lineCounter = 0; for (int i = 0; i < LUT_SIZE; ++i) { var angle = i / ((float)(LUT_SIZE - 1)); if (lineCounter++ % 8 == 0) { writer.WriteLine(); writer.Write(" "); } var acos = Math.Acos(angle); var rawValue = ((FP)acos)._serializedValue; writer.Write(string.Format("0x{0:X}L, ", rawValue)); } writer.Write( @" }; } }"); } } internal static void GenerateSinLut() { using (var writer = new StreamWriter("Fix64SinLut.cs")) { writer.Write( @"namespace FixMath.NET { partial struct Fix64 { public static readonly long[] SinLut = new[] {"); int lineCounter = 0; for (int i = 0; i < LUT_SIZE; ++i) { var angle = i * Math.PI * 0.5 / (LUT_SIZE - 1); if (lineCounter++ % 8 == 0) { writer.WriteLine(); writer.Write(" "); } var sin = Math.Sin(angle); var rawValue = ((FP)sin)._serializedValue; writer.Write(string.Format("0x{0:X}L, ", rawValue)); } writer.Write( @" }; } }"); } } internal static void GenerateTanLut() { using (var writer = new StreamWriter("Fix64TanLut.cs")) { writer.Write( @"namespace FixMath.NET { partial struct Fix64 { public static readonly long[] TanLut = new[] {"); int lineCounter = 0; for (int i = 0; i < LUT_SIZE; ++i) { var angle = i * Math.PI * 0.5 / (LUT_SIZE - 1); if (lineCounter++ % 8 == 0) { writer.WriteLine(); writer.Write(" "); } var tan = Math.Tan(angle); if (tan > (double)MaxValue || tan < 0.0) { tan = (double)MaxValue; } var rawValue = (((decimal)tan > (decimal)MaxValue || tan < 0.0) ? MaxValue : (FP)tan)._serializedValue; writer.Write(string.Format("0x{0:X}L, ", rawValue)); } writer.Write( @" }; } }"); } } /// <summary> /// The underlying integer representation /// </summary> public long RawValue { get { return _serializedValue; } } /// <summary> /// This is the constructor from raw value; it can only be used interally. /// </summary> /// <param name="rawValue"></param> FP(long rawValue) { _serializedValue = rawValue; } public FP(int value) { _serializedValue = value * ONE; } } }
ET/Unity/Assets/Scripts/ThirdParty/TrueSync/Fix64.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/TrueSync/Fix64.cs", "repo_id": "ET", "token_count": 18144 }
196
using System; using MemoryPack; using MongoDB.Bson.Serialization.Attributes; namespace TrueSync { /** * @brief Generates random numbers based on a deterministic approach. **/ [MemoryPackable] public partial class TSRandom { // From http://www.codeproject.com/Articles/164087/Random-Number-Generation // Class TSRandom generates random numbers // from a uniform distribution using the Mersenne // Twister algorithm. private const int N = 624; private const int M = 397; private const uint MATRIX_A = 0x9908b0dfU; private const uint UPPER_MASK = 0x80000000U; private const uint LOWER_MASK = 0x7fffffffU; private const int MAX_RAND_INT = 0x7fffffff; [BsonElement] [MemoryPackInclude] private uint[] mag01 = { 0x0U, MATRIX_A }; [BsonElement] [MemoryPackInclude] private uint[] mt = new uint[N]; [BsonElement] [MemoryPackInclude] private int mti = N + 1; [MemoryPackConstructor] private TSRandom() { } private TSRandom(int seed) { init_genrand((uint)seed); } private TSRandom(int[] init) { uint[] initArray = new uint[init.Length]; for (int i = 0; i < init.Length; ++i) initArray[i] = (uint)init[i]; init_by_array(initArray, (uint)initArray.Length); } public static int MaxRandomInt { get { return 0x7fffffff; } } /** * @brief Returns a random integer. **/ public int Next() { return genrand_int31(); } /** * @brief Returns a random integer. **/ public int CallNext() { return this.Next(); } /** * @brief Returns a integer between a min value [inclusive] and a max value [exclusive]. **/ public int Next(int minValue, int maxValue) { if (minValue > maxValue) { int tmp = maxValue; maxValue = minValue; minValue = tmp; } int range = maxValue - minValue; return minValue + Next() % range; } /** * @brief Returns a {@link FP} between a min value [inclusive] and a max value [inclusive]. **/ public FP Next(float minValue, float maxValue) { int minValueInt = (int)(minValue * 1000), maxValueInt = (int)(maxValue * 1000); if (minValueInt > maxValueInt) { int tmp = maxValueInt; maxValueInt = minValueInt; minValueInt = tmp; } return (FP.Floor((maxValueInt - minValueInt + 1) * NextFP() + minValueInt)) / 1000; } /** * @brief Returns a integer between a min value [inclusive] and a max value [exclusive]. **/ public int Range(int minValue, int maxValue) { return this.Next(minValue, maxValue); } /** * @brief Returns a {@link FP} between a min value [inclusive] and a max value [inclusive]. **/ public FP Range(float minValue, float maxValue) { return this.Next(minValue, maxValue); } /** * @brief Returns a {@link FP} between 0.0 [inclusive] and 1.0 [inclusive]. **/ public FP NextFP() { return ((FP) Next()) / (MaxRandomInt); } /** * @brief Returns a {@link FP} between 0.0 [inclusive] and 1.0 [inclusive]. **/ [MemoryPackIgnore] public FP value { get { return this.NextFP(); } } /** * @brief Returns a random {@link TSVector} representing a point inside a sphere with radius 1. **/ [MemoryPackIgnore] public TSVector insideUnitSphere { get { return new TSVector(value, value, value); } } private float NextFloat() { return (float)genrand_real2(); } private float NextFloat(bool includeOne) { if (includeOne) { return (float)genrand_real1(); } return (float)genrand_real2(); } private float NextFloatPositive() { return (float)genrand_real3(); } private double NextDouble() { return genrand_real2(); } private double NextDouble(bool includeOne) { if (includeOne) { return genrand_real1(); } return genrand_real2(); } private double NextDoublePositive() { return genrand_real3(); } private double Next53BitRes() { return genrand_res53(); } public void Initialize() { init_genrand((uint)DateTime.Now.Millisecond); } public void Initialize(int seed) { init_genrand((uint)seed); } public void Initialize(int[] init) { uint[] initArray = new uint[init.Length]; for (int i = 0; i < init.Length; ++i) initArray[i] = (uint)init[i]; init_by_array(initArray, (uint)initArray.Length); } private void init_genrand(uint s) { mt[0] = s & 0xffffffffU; for (mti = 1; mti < N; mti++) { mt[mti] = (uint)(1812433253U * (mt[mti - 1] ^ (mt[mti - 1] >> 30)) + mti); mt[mti] &= 0xffffffffU; } } private void init_by_array(uint[] init_key, uint key_length) { int i, j, k; init_genrand(19650218U); i = 1; j = 0; k = (int)(N > key_length ? N : key_length); for (; k > 0; k--) { mt[i] = (uint)((uint)(mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >> 30)) * 1664525U)) + init_key[j] + j); mt[i] &= 0xffffffffU; i++; j++; if (i >= N) { mt[0] = mt[N - 1]; i = 1; } if (j >= key_length) j = 0; } for (k = N - 1; k > 0; k--) { mt[i] = (uint)((uint)(mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >> 30)) * 1566083941U)) - i); mt[i] &= 0xffffffffU; i++; if (i >= N) { mt[0] = mt[N - 1]; i = 1; } } mt[0] = 0x80000000U; } uint genrand_int32() { uint y; if (mti >= N) { int kk; if (mti == N + 1) init_genrand(5489U); for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (y >> 1) ^ mag01[y & 0x1U]; } for (; kk < N - 1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (y >> 1) ^ mag01[y & 0x1U]; } y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (y >> 1) ^ mag01[y & 0x1U]; mti = 0; } y = mt[mti++]; y ^= (y >> 11); y ^= (y << 7) & 0x9d2c5680U; y ^= (y << 15) & 0xefc60000U; y ^= (y >> 18); return y; } private int genrand_int31() { return (int)(genrand_int32() >> 1); } FP genrand_FP() { return (FP)genrand_int32() * (FP.One / (FP)4294967295); } double genrand_real1() { return genrand_int32() * (1.0 / 4294967295.0); } double genrand_real2() { return genrand_int32() * (1.0 / 4294967296.0); } double genrand_real3() { return (((double)genrand_int32()) + 0.5) * (1.0 / 4294967296.0); } double genrand_res53() { uint a = genrand_int32() >> 5, b = genrand_int32() >> 6; return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0); } } }
ET/Unity/Assets/Scripts/ThirdParty/TrueSync/TSRandom.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/TrueSync/TSRandom.cs", "repo_id": "ET", "token_count": 4622 }
197
fileFormatVersion: 2 guid: d5d69583e5ecc46459ee4a0159b8b969 NativeFormatImporter: externalObjects: {} mainObjectFileID: 11400000 userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Settings/AssetBundleCollectorSetting.asset.meta/0
{ "file_path": "ET/Unity/Assets/Settings/AssetBundleCollectorSetting.asset.meta", "repo_id": "ET", "token_count": 76 }
198