text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
fileFormatVersion: 2 guid: 6fd8e3971f929c44dab7e9d1d9a90982 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Editor/Plugins/Example.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/Plugins/Example.meta", "repo_id": "ET", "token_count": 73 }
114
fileFormatVersion: 2 guid: f87d124589b266d41a4281a2a6ba3f63 timeCreated: 1498900429 licenseType: Free MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Editor/ServerCommandLineEditor/ServerCommandLineEditor.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Editor/ServerCommandLineEditor/ServerCommandLineEditor.cs.meta", "repo_id": "ET", "token_count": 102 }
115
fileFormatVersion: 2 guid: 2e5141370ec84e1282c5d0a38f2ef25b timeCreated: 1688537612
ET/Unity/Assets/Scripts/Hotfix/Client/Demo/Main.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Demo/Main.meta", "repo_id": "ET", "token_count": 38 }
116
namespace ET.Client { public static class CurrentSceneFactory { public static Scene Create(long id, string name, CurrentScenesComponent currentScenesComponent) { Scene currentScene = EntitySceneFactory.CreateScene(currentScenesComponent, id, IdGenerater.Instance.GenerateInstanceId(), SceneType.Current, name); currentScenesComponent.Scene = currentScene; EventSystem.Instance.Publish(currentScene, new AfterCreateCurrentScene()); return currentScene; } } }
ET/Unity/Assets/Scripts/Hotfix/Client/Demo/Main/Scene/CurrentSceneFactory.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Demo/Main/Scene/CurrentSceneFactory.cs", "repo_id": "ET", "token_count": 203 }
117
fileFormatVersion: 2 guid: 90e53c0be7b8aab4c827ed76d193ca42 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Client/Demo/Main/Unit/UnitHelper.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Demo/Main/Unit/UnitHelper.cs.meta", "repo_id": "ET", "token_count": 96 }
118
using System; using System.IO; using System.Net.Http; using System.Threading; namespace ET.Client { public static partial class HttpClientHelper { public static async ETTask<string> Get(string link) { try { using HttpClient httpClient = new(); HttpResponseMessage response = await httpClient.GetAsync(link); string result = await response.Content.ReadAsStringAsync(); return result; } catch (Exception e) { throw new Exception($"http request fail: {link.Substring(0,link.IndexOf('?'))}\n{e}"); } } } }
ET/Unity/Assets/Scripts/Hotfix/Client/Demo/NetClient/Router/HttpClientHelper.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Demo/NetClient/Router/HttpClientHelper.cs", "repo_id": "ET", "token_count": 329 }
119
fileFormatVersion: 2 guid: 915aaa51beb994638bd10e0d2ed9d8a7 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Client/LockStep/LSClientHelper.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/LockStep/LSClientHelper.cs.meta", "repo_id": "ET", "token_count": 96 }
120
fileFormatVersion: 2 guid: 6378fb95ea17e6d46b536062736457a5 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Client/Module/Message.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Module/Message.meta", "repo_id": "ET", "token_count": 68 }
121
fileFormatVersion: 2 guid: 126a4d951160c2d43a641b7da3a0840c MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/Benchmark/C2G_BenchmarkHandler.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Benchmark/C2G_BenchmarkHandler.cs.meta", "repo_id": "ET", "token_count": 96 }
122
using System; namespace ET.Server { [MessageSessionHandler(SceneType.Gate)] public class C2G_LoginGateHandler : MessageSessionHandler<C2G_LoginGate, G2C_LoginGate> { protected override async ETTask Run(Session session, C2G_LoginGate request, G2C_LoginGate response) { Scene root = session.Root(); string account = root.GetComponent<GateSessionKeyComponent>().Get(request.Key); if (account == null) { response.Error = ErrorCore.ERR_ConnectGateKeyError; response.Message = "Gate key验证失败!"; return; } session.RemoveComponent<SessionAcceptTimeoutComponent>(); PlayerComponent playerComponent = root.GetComponent<PlayerComponent>(); Player player = playerComponent.GetByAccount(account); if (player == null) { player = playerComponent.AddChild<Player, string>(account); playerComponent.Add(player); PlayerSessionComponent playerSessionComponent = player.AddComponent<PlayerSessionComponent>(); playerSessionComponent.AddComponent<MailBoxComponent, MailBoxType>(MailBoxType.GateSession); await playerSessionComponent.AddLocation(LocationType.GateSession); player.AddComponent<MailBoxComponent, MailBoxType>(MailBoxType.UnOrderedMessage); await player.AddLocation(LocationType.Player); session.AddComponent<SessionPlayerComponent>().Player = player; playerSessionComponent.Session = session; } else { // 判断是否在战斗 PlayerRoomComponent playerRoomComponent = player.GetComponent<PlayerRoomComponent>(); if (playerRoomComponent.RoomActorId != default) { CheckRoom(player, session).Coroutine(); } else { PlayerSessionComponent playerSessionComponent = player.GetComponent<PlayerSessionComponent>(); playerSessionComponent.Session = session; } } response.PlayerId = player.Id; await ETTask.CompletedTask; } private static async ETTask CheckRoom(Player player, Session session) { Fiber fiber = player.Fiber(); await fiber.WaitFrameFinish(); G2Room_Reconnect g2RoomReconnect = G2Room_Reconnect.Create(); g2RoomReconnect.PlayerId = player.Id; using Room2G_Reconnect room2GateReconnect = await fiber.Root.GetComponent<MessageSender>().Call( player.GetComponent<PlayerRoomComponent>().RoomActorId, g2RoomReconnect) as Room2G_Reconnect; G2C_Reconnect g2CReconnect = G2C_Reconnect.Create(); g2CReconnect.StartTime = room2GateReconnect.StartTime; g2CReconnect.Frame = room2GateReconnect.Frame; g2CReconnect.UnitInfos.AddRange(room2GateReconnect.UnitInfos); session.Send(g2CReconnect); session.AddComponent<SessionPlayerComponent>().Player = player; player.GetComponent<PlayerSessionComponent>().Session = session; } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Gate/C2G_LoginGateHandler.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Gate/C2G_LoginGateHandler.cs", "repo_id": "ET", "token_count": 1534 }
123
namespace ET.Server { [EntitySystemOf(typeof(Player))] [FriendOf(typeof(Player))] public static partial class PlayerSystem { [EntitySystem] private static void Awake(this Player self, string a) { self.Account = a; } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Gate/PlayerSystem.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Gate/PlayerSystem.cs", "repo_id": "ET", "token_count": 130 }
124
 using System.Collections.Generic; using System.IO; namespace ET.Server { public static partial class MapMessageHelper { public static void NoticeUnitAdd(Unit unit, Unit sendUnit) { M2C_CreateUnits createUnits = M2C_CreateUnits.Create(); createUnits.Units.Add(UnitHelper.CreateUnitInfo(sendUnit)); MapMessageHelper.SendToClient(unit, createUnits); } public static void NoticeUnitRemove(Unit unit, Unit sendUnit) { M2C_RemoveUnits removeUnits = M2C_RemoveUnits.Create(); removeUnits.Units.Add(sendUnit.Id); MapMessageHelper.SendToClient(unit, removeUnits); } public static void Broadcast(Unit unit, IMessage message) { (message as MessageObject).IsFromPool = false; Dictionary<long, EntityRef<AOIEntity>> dict = unit.GetBeSeePlayers(); // 网络底层做了优化,同一个消息不会多次序列化 MessageLocationSenderOneType oneTypeMessageLocationType = unit.Root().GetComponent<MessageLocationSenderComponent>().Get(LocationType.GateSession); foreach (AOIEntity u in dict.Values) { oneTypeMessageLocationType.Send(u.Unit.Id, message); } } public static void SendToClient(Unit unit, IMessage message) { unit.Root().GetComponent<MessageLocationSenderComponent>().Get(LocationType.GateSession).Send(unit.Id, message); } /// <summary> /// 发送协议给Actor /// </summary> public static void Send(Scene root, ActorId actorId, IMessage message) { root.GetComponent<MessageSender>().Send(actorId, message); } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Map/MapMessageHelper.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Map/MapMessageHelper.cs", "repo_id": "ET", "token_count": 830 }
125
fileFormatVersion: 2 guid: 90f2084c2789e40468c6eb5642275748 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Map/Unit.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Map/Unit.meta", "repo_id": "ET", "token_count": 68 }
126
using System.Collections.Generic; namespace ET.Server { public static partial class RealmGateAddressHelper { public static StartSceneConfig GetGate(int zone, string account) { ulong hash = (ulong)account.GetLongHashCode(); List<StartSceneConfig> zoneGates = StartSceneConfigCategory.Instance.Gates[zone]; return zoneGates[(int)(hash % (ulong)zoneGates.Count)]; } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Realm/RealmGateAddressHelper.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Realm/RealmGateAddressHelper.cs", "repo_id": "ET", "token_count": 142 }
127
fileFormatVersion: 2 guid: 5d37c22fa00c59f48a444cc04a1621e4 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Map/FiberInit_Map.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Map/FiberInit_Map.cs.meta", "repo_id": "ET", "token_count": 95 }
128
fileFormatVersion: 2 guid: 8795299b519a48719a23f048377da2a9 timeCreated: 1681817967
ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Room.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Room.meta", "repo_id": "ET", "token_count": 34 }
129
using System; using System.IO; using MongoDB.Bson; namespace ET.Server { [EntitySystemOf(typeof(MessageLocationSenderOneType))] [FriendOf(typeof(MessageLocationSenderOneType))] [FriendOf(typeof(MessageLocationSender))] public static partial class MessageLocationSenderComponentSystem { [Invoke(TimerInvokeType.MessageLocationSenderChecker)] public class MessageLocationSenderChecker: ATimer<MessageLocationSenderOneType> { protected override void Run(MessageLocationSenderOneType self) { try { self.Check(); } catch (Exception e) { Log.Error($"move timer error: {self.Id}\n{e}"); } } } [EntitySystem] private static void Awake(this MessageLocationSenderOneType self, int locationType) { self.LocationType = locationType; // 每10s扫描一次过期的actorproxy进行回收,过期时间是2分钟 // 可能由于bug或者进程挂掉,导致ActorLocationSender发送的消息没有确认,结果无法自动删除,每一分钟清理一次这种ActorLocationSender self.CheckTimer = self.Root().GetComponent<TimerComponent>().NewRepeatedTimer(10 * 1000, TimerInvokeType.MessageLocationSenderChecker, self); } [EntitySystem] private static void Destroy(this MessageLocationSenderOneType self) { self.Root().GetComponent<TimerComponent>()?.Remove(ref self.CheckTimer); } private static void Check(this MessageLocationSenderOneType self) { using (ListComponent<long> list = ListComponent<long>.Create()) { long timeNow = TimeInfo.Instance.ServerNow(); foreach ((long key, Entity value) in self.Children) { MessageLocationSender messageLocationMessageSender = (MessageLocationSender) value; if (timeNow > messageLocationMessageSender.LastSendOrRecvTime + MessageLocationSenderOneType.TIMEOUT_TIME) { list.Add(key); } } foreach (long id in list) { self.Remove(id); } } } private static MessageLocationSender GetOrCreate(this MessageLocationSenderOneType self, long id) { if (id == 0) { throw new Exception($"actor id is 0"); } if (self.Children.TryGetValue(id, out Entity actorLocationSender)) { return (MessageLocationSender) actorLocationSender; } actorLocationSender = self.AddChildWithId<MessageLocationSender>(id); return (MessageLocationSender) actorLocationSender; } // 有需要主动删除actorMessageSender的需求,比如断线重连,玩家登录了不同的Gate,这时候需要通知map删掉之前的actorMessageSender // 然后重新创建新的,重新请求新的ActorId public static void Remove(this MessageLocationSenderOneType self, long id) { if (!self.Children.TryGetValue(id, out Entity actorMessageSender)) { return; } actorMessageSender.Dispose(); } // 发给不会改变位置的actorlocation用这个,这种actor消息不会阻塞发送队列,性能更高 // 发送过去找不到actor不会重试,用此方法,你得保证actor提前注册好了location public static void Send(this MessageLocationSenderOneType self, long entityId, IMessage message) { self.SendInner(entityId, message).Coroutine(); } private static async ETTask SendInner(this MessageLocationSenderOneType self, long entityId, IMessage message) { MessageLocationSender messageLocationSender = self.GetOrCreate(entityId); Scene root = self.Root(); if (messageLocationSender.ActorId != default) { messageLocationSender.LastSendOrRecvTime = TimeInfo.Instance.ServerNow(); root.GetComponent<MessageSender>().Send(messageLocationSender.ActorId, message); return; } long instanceId = messageLocationSender.InstanceId; int coroutineLockType = (self.LocationType << 16) | CoroutineLockType.MessageLocationSender; using (await root.Root().GetComponent<CoroutineLockComponent>().Wait(coroutineLockType, entityId)) { if (messageLocationSender.InstanceId != instanceId) { throw new RpcException(ErrorCore.ERR_MessageTimeout, $"{message}"); } if (messageLocationSender.ActorId == default) { messageLocationSender.ActorId = await root.GetComponent<LocationProxyComponent>().Get(self.LocationType, messageLocationSender.Id); if (messageLocationSender.InstanceId != instanceId) { throw new RpcException(ErrorCore.ERR_ActorLocationSenderTimeout2, $"{message}"); } } messageLocationSender.LastSendOrRecvTime = TimeInfo.Instance.ServerNow(); root.GetComponent<MessageSender>().Send(messageLocationSender.ActorId, message); } } // 发给不会改变位置的actorlocation用这个,这种actor消息不会阻塞发送队列,性能更高,发送过去找不到actor不会重试 // 发送过去找不到actor不会重试,用此方法,你得保证actor提前注册好了location public static async ETTask<IResponse> Call(this MessageLocationSenderOneType self, long entityId, IRequest request) { MessageLocationSender messageLocationSender = self.GetOrCreate(entityId); Scene root = self.Root(); if (messageLocationSender.ActorId != default) { messageLocationSender.LastSendOrRecvTime = TimeInfo.Instance.ServerNow(); return await root.GetComponent<MessageSender>().Call(messageLocationSender.ActorId, request); } long instanceId = messageLocationSender.InstanceId; int coroutineLockType = (self.LocationType << 16) | CoroutineLockType.MessageLocationSender; using (await root.GetComponent<CoroutineLockComponent>().Wait(coroutineLockType, entityId)) { if (messageLocationSender.InstanceId != instanceId) { throw new RpcException(ErrorCore.ERR_MessageTimeout, $"{request}"); } if (messageLocationSender.ActorId == default) { messageLocationSender.ActorId = await root.GetComponent<LocationProxyComponent>().Get(self.LocationType, messageLocationSender.Id); if (messageLocationSender.InstanceId != instanceId) { throw new RpcException(ErrorCore.ERR_ActorLocationSenderTimeout2, $"{request}"); } } } messageLocationSender.LastSendOrRecvTime = TimeInfo.Instance.ServerNow(); return await root.GetComponent<MessageSender>().Call(messageLocationSender.ActorId, request); } public static void Send(this MessageLocationSenderOneType self, long entityId, ILocationMessage message) { self.Call(entityId, message).Coroutine(); } public static async ETTask<IResponse> Call(this MessageLocationSenderOneType self, long entityId, ILocationRequest iRequest) { MessageLocationSender messageLocationSender = self.GetOrCreate(entityId); Scene root = self.Root(); Type iRequestType = iRequest.GetType(); long actorLocationSenderInstanceId = messageLocationSender.InstanceId; int coroutineLockType = (self.LocationType << 16) | CoroutineLockType.MessageLocationSender; using (await root.GetComponent<CoroutineLockComponent>().Wait(coroutineLockType, entityId)) { if (messageLocationSender.InstanceId != actorLocationSenderInstanceId) { throw new RpcException(ErrorCore.ERR_NotFoundActor, $"{iRequest}"); } try { return await self.CallInner(messageLocationSender, iRequest); } catch (RpcException) { self.Remove(messageLocationSender.Id); throw; } catch (Exception e) { self.Remove(messageLocationSender.Id); throw new Exception($"{iRequestType.FullName}", e); } } } private static async ETTask<IResponse> CallInner(this MessageLocationSenderOneType self, MessageLocationSender messageLocationSender, IRequest iRequest) { int failTimes = 0; long instanceId = messageLocationSender.InstanceId; messageLocationSender.LastSendOrRecvTime = TimeInfo.Instance.ServerNow(); Scene root = self.Root(); Type requestType = iRequest.GetType(); while (true) { if (messageLocationSender.ActorId == default) { messageLocationSender.ActorId = await root.GetComponent<LocationProxyComponent>().Get(self.LocationType, messageLocationSender.Id); if (messageLocationSender.InstanceId != instanceId) { throw new RpcException(ErrorCore.ERR_ActorLocationSenderTimeout2, $"{iRequest}"); } } if (messageLocationSender.ActorId == default) { return MessageHelper.CreateResponse(requestType, 0, ErrorCore.ERR_NotFoundActor); } IResponse response = await root.GetComponent<MessageSender>().Call(messageLocationSender.ActorId, iRequest, needException: false); if (messageLocationSender.InstanceId != instanceId) { throw new RpcException(ErrorCore.ERR_ActorLocationSenderTimeout3, $"{requestType.FullName}"); } switch (response.Error) { case ErrorCore.ERR_NotFoundActor: { // 如果没找到Actor,重试 ++failTimes; if (failTimes > 20) { Log.Debug($"actor send message fail, actorid: {messageLocationSender.Id} {requestType.FullName}"); // 这里删除actor,后面等待发送的消息会判断InstanceId,InstanceId不一致返回ERR_NotFoundActor self.Remove(messageLocationSender.Id); return response; } // 等待0.5s再发送 await root.GetComponent<TimerComponent>().WaitAsync(500); if (messageLocationSender.InstanceId != instanceId) { throw new RpcException(ErrorCore.ERR_ActorLocationSenderTimeout4, $"{requestType.FullName}"); } messageLocationSender.ActorId = default; continue; } case ErrorCore.ERR_MessageTimeout: { throw new RpcException(response.Error, $"{requestType.FullName}"); } } if (ErrorCore.IsRpcNeedThrowException(response.Error)) { throw new RpcException(response.Error, $"Message: {response.Message} Request: {requestType.FullName}"); } return response; } } } [EntitySystemOf(typeof(MessageLocationSenderComponent))] [FriendOf(typeof (MessageLocationSenderComponent))] public static partial class MessageLocationSenderManagerComponentSystem { [EntitySystem] private static void Awake(this MessageLocationSenderComponent self) { for (int i = 0; i < self.messageLocationSenders.Length; ++i) { self.messageLocationSenders[i] = self.AddChild<MessageLocationSenderOneType, int>(i); } } public static MessageLocationSenderOneType Get(this MessageLocationSenderComponent self, int locationType) { return self.messageLocationSenders[locationType]; } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Module/ActorLocation/MessageLocationSenderComponentSystem.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Module/ActorLocation/MessageLocationSenderComponentSystem.cs", "repo_id": "ET", "token_count": 6746 }
130
fileFormatVersion: 2 guid: f19e3330918fd704a90558bf305e8be6 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/Module/DB/DBComponentSystem.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Module/DB/DBComponentSystem.cs.meta", "repo_id": "ET", "token_count": 92 }
131
using System.Net; namespace ET.Server { [Invoke((long)SceneType.NetInner)] public class FiberInit_NetInner: 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>(); StartProcessConfig startProcessConfig = StartProcessConfigCategory.Instance.Get(fiberInit.Fiber.Process); root.AddComponent<ProcessOuterSender, IPEndPoint>(startProcessConfig.IPEndPoint); root.AddComponent<ProcessInnerSender>(); await ETTask.CompletedTask; } } }
ET/Unity/Assets/Scripts/Hotfix/Server/Module/NetInner/FiberInit_NetInner.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Module/NetInner/FiberInit_NetInner.cs", "repo_id": "ET", "token_count": 326 }
132
fileFormatVersion: 2 guid: 337bf31669284174ba505282863741f6 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Server/Plugins.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Plugins.meta", "repo_id": "ET", "token_count": 64 }
133
fileFormatVersion: 2 guid: 3bdd9b39878d7e04685a85d38bc88950 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Share/Module/Console/ConsoleComponentSystem.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Share/Module/Console/ConsoleComponentSystem.cs.meta", "repo_id": "ET", "token_count": 94 }
134
namespace ET { // 分发数值监听 [Event(SceneType.All)] // 服务端Map需要分发, 客户端CurrentScene也要分发 public class NumericChangeEvent_NotifyWatcher: AEvent<Scene, NumbericChange> { protected override async ETTask Run(Scene scene, NumbericChange args) { NumericWatcherComponent.Instance.Run(args.Unit, args); await ETTask.CompletedTask; } } }
ET/Unity/Assets/Scripts/Hotfix/Share/Module/Numeric/NumericChangeEvent_NotifyWatcher.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Share/Module/Numeric/NumericChangeEvent_NotifyWatcher.cs", "repo_id": "ET", "token_count": 161 }
135
fileFormatVersion: 2 guid: 1b03ed498c4dcf04c935c7b7962384da folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Hotfix/Share/Plugins/Example.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Hotfix/Share/Plugins/Example.meta", "repo_id": "ET", "token_count": 70 }
136
namespace ET.Client { [Event(SceneType.Current)] public class AfterCreateCurrentScene_AddComponent: AEvent<Scene, AfterCreateCurrentScene> { protected override async ETTask Run(Scene scene, AfterCreateCurrentScene args) { scene.AddComponent<UIComponent>(); scene.AddComponent<ResourcesLoaderComponent>(); await ETTask.CompletedTask; } } }
ET/Unity/Assets/Scripts/HotfixView/Client/Demo/Scene/AfterCreateCurrentScene_AddComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/Demo/Scene/AfterCreateCurrentScene_AddComponent.cs", "repo_id": "ET", "token_count": 161 }
137
fileFormatVersion: 2 guid: 3fc77077261cf264ca091db1df7f692b MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/HotfixView/Client/Demo/UI/UILobby/UILobbyComponentSystem.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/Demo/UI/UILobby/UILobbyComponentSystem.cs.meta", "repo_id": "ET", "token_count": 92 }
138
fileFormatVersion: 2 guid: 4dbc691573db50443914c3ea71ebdedf MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/HotfixView/Client/Demo/Unit/AnimatorComponentSystem.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/Demo/Unit/AnimatorComponentSystem.cs.meta", "repo_id": "ET", "token_count": 93 }
139
using UnityEngine; namespace ET.Client { [UIEvent(UIType.UILSLobby)] public class UILSLobbyEvent: AUIEvent { public override async ETTask<UI> OnCreate(UIComponent uiComponent, UILayer uiLayer) { string assetsName = $"Assets/Bundles/UI/LockStep/{UIType.UILSLobby}.prefab"; GameObject bundleGameObject = await uiComponent.Scene().GetComponent<ResourcesLoaderComponent>().LoadAssetAsync<GameObject>(assetsName); GameObject gameObject = UnityEngine.Object.Instantiate(bundleGameObject, uiComponent.UIGlobalComponent.GetLayer((int)uiLayer)); UI ui = uiComponent.AddChild<UI, string, GameObject>(UIType.UILSLobby, gameObject); ui.AddComponent<UILSLobbyComponent>(); return ui; } public override void OnRemove(UIComponent uiComponent) { } } }
ET/Unity/Assets/Scripts/HotfixView/Client/LockStep/UI/UILSLobby/UILSLobbyEvent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/LockStep/UI/UILSLobby/UILSLobbyEvent.cs", "repo_id": "ET", "token_count": 369 }
140
fileFormatVersion: 2 guid: e2442d257cf316b4fbd095bc092aacd0 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/HotfixView/Client/Module.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/Module.meta", "repo_id": "ET", "token_count": 70 }
141
using UnityEngine.Networking; namespace ET { public class AcceptAllCertificate : CertificateHandler { protected override bool ValidateCertificate(byte[] certificateData) { return true; } } }
ET/Unity/Assets/Scripts/Loader/Helper/AcceptAllCertificate.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Loader/Helper/AcceptAllCertificate.cs", "repo_id": "ET", "token_count": 96 }
142
fileFormatVersion: 2 guid: 502d8cafd6a5a0447ab1db9a24cdcb10 timeCreated: 1476430105 licenseType: Pro MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Loader/MonoBehaviour/ReferenceCollector.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Loader/MonoBehaviour/ReferenceCollector.cs.meta", "repo_id": "ET", "token_count": 102 }
143
using System; using System.Collections.Generic; using UnityEngine; using YooAsset; namespace ET { /// <summary> /// 远端资源地址查询服务类 /// </summary> public class RemoteServices : IRemoteServices { private readonly string _defaultHostServer; private readonly string _fallbackHostServer; public RemoteServices(string defaultHostServer, string fallbackHostServer) { _defaultHostServer = defaultHostServer; _fallbackHostServer = fallbackHostServer; } string IRemoteServices.GetRemoteMainURL(string fileName) { return $"{_defaultHostServer}/{fileName}"; } string IRemoteServices.GetRemoteFallbackURL(string fileName) { return $"{_fallbackHostServer}/{fileName}"; } } public class ResourcesComponent : Singleton<ResourcesComponent>, ISingletonAwake { public void Awake() { YooAssets.Initialize(); } protected override void Destroy() { YooAssets.Destroy(); } public async ETTask CreatePackageAsync(string packageName, bool isDefault = false) { ResourcePackage package = YooAssets.CreatePackage(packageName); if (isDefault) { YooAssets.SetDefaultPackage(package); } GlobalConfig globalConfig = Resources.Load<GlobalConfig>("GlobalConfig"); EPlayMode ePlayMode = globalConfig.EPlayMode; // 编辑器下的模拟模式 switch (ePlayMode) { case EPlayMode.EditorSimulateMode: { EditorSimulateModeParameters createParameters = new(); createParameters.SimulateManifestFilePath = EditorSimulateModeHelper.SimulateBuild("ScriptableBuildPipeline", packageName); await package.InitializeAsync(createParameters).Task; break; } case EPlayMode.OfflinePlayMode: { OfflinePlayModeParameters createParameters = new(); await package.InitializeAsync(createParameters).Task; break; } case EPlayMode.HostPlayMode: { string defaultHostServer = GetHostServerURL(); string fallbackHostServer = GetHostServerURL(); HostPlayModeParameters createParameters = new(); createParameters.BuildinQueryServices = new GameQueryServices(); createParameters.RemoteServices = new RemoteServices(defaultHostServer, fallbackHostServer); await package.InitializeAsync(createParameters).Task; break; } default: throw new ArgumentOutOfRangeException(); } } static string GetHostServerURL() { //string hostServerIP = "http://10.0.2.2"; //安卓模拟器地址 string hostServerIP = "http://127.0.0.1"; string appVersion = "v1.0"; #if UNITY_EDITOR if (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.Android) { return $"{hostServerIP}/CDN/Android/{appVersion}"; } else if (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.iOS) { return $"{hostServerIP}/CDN/IPhone/{appVersion}"; } else if (UnityEditor.EditorUserBuildSettings.activeBuildTarget == UnityEditor.BuildTarget.WebGL) { return $"{hostServerIP}/CDN/WebGL/{appVersion}"; } return $"{hostServerIP}/CDN/PC/{appVersion}"; #else if (Application.platform == RuntimePlatform.Android) { return $"{hostServerIP}/CDN/Android/{appVersion}"; } else if (Application.platform == RuntimePlatform.IPhonePlayer) { return $"{hostServerIP}/CDN/IPhone/{appVersion}"; } else if (Application.platform == RuntimePlatform.WebGLPlayer) { return $"{hostServerIP}/CDN/WebGL/{appVersion}"; } return $"{hostServerIP}/CDN/PC/{appVersion}"; #endif } public void DestroyPackage(string packageName) { ResourcePackage package = YooAssets.GetPackage(packageName); package.UnloadUnusedAssets(); } /// <summary> /// 主要用来加载dll config aotdll,因为这时候纤程还没创建,无法使用ResourcesLoaderComponent。 /// 游戏中的资源应该使用ResourcesLoaderComponent来加载 /// </summary> public async ETTask<T> LoadAssetAsync<T>(string location) where T : UnityEngine.Object { AssetHandle handle = YooAssets.LoadAssetAsync<T>(location); await handle.Task; T t = (T)handle.AssetObject; handle.Release(); return t; } /// <summary> /// 主要用来加载dll config aotdll,因为这时候纤程还没创建,无法使用ResourcesLoaderComponent。 /// 游戏中的资源应该使用ResourcesLoaderComponent来加载 /// </summary> public async ETTask<Dictionary<string, T>> LoadAllAssetsAsync<T>(string location) where T : UnityEngine.Object { AllAssetsHandle allAssetsOperationHandle = YooAssets.LoadAllAssetsAsync<T>(location); await allAssetsOperationHandle.Task; Dictionary<string, T> dictionary = new Dictionary<string, T>(); foreach (UnityEngine.Object assetObj in allAssetsOperationHandle.AllAssetObjects) { T t = assetObj as T; dictionary.Add(t.name, t); } allAssetsOperationHandle.Release(); return dictionary; } } }
ET/Unity/Assets/Scripts/Loader/Resource/ResourcesComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Loader/Resource/ResourcesComponent.cs", "repo_id": "ET", "token_count": 2971 }
144
fileFormatVersion: 2 guid: 885e50cc17c2b9345bcf5e8bac46ae03 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Client/Demo/AI.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Client/Demo/AI.meta", "repo_id": "ET", "token_count": 71 }
145
fileFormatVersion: 2 guid: 390f281261413d847bd6ceb803f5c38a folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Generate/ClientServer/ConfigPartial.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Generate/ClientServer/ConfigPartial.meta", "repo_id": "ET", "token_count": 69 }
146
fileFormatVersion: 2 guid: 24ce03f1b7723bc47bca791671a977d2 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Generate/Server.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Generate/Server.meta", "repo_id": "ET", "token_count": 70 }
147
fileFormatVersion: 2 guid: d21748fcd16e9ba4490731de6fb475b7 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Generate/Server/ConfigPartial/StartProcessConfig.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Generate/Server/ConfigPartial/StartProcessConfig.cs.meta", "repo_id": "ET", "token_count": 93 }
148
fileFormatVersion: 2 guid: 80ca7b39eee27b6469d966bf15636111 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Server.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server.meta", "repo_id": "ET", "token_count": 68 }
149
using System.Collections.Generic; namespace ET.Server { [ComponentOf(typeof(Scene))] public class RobotManagerComponent: Entity, IAwake, IDestroy { public HashSet<int> robots = new(); } }
ET/Unity/Assets/Scripts/Model/Server/Demo/Robot/RobotManagerComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Demo/Robot/RobotManagerComponent.cs", "repo_id": "ET", "token_count": 80 }
150
fileFormatVersion: 2 guid: d3d85a4b2a3594b9fa6887cc3b574056 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Server/LockStep/Match.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/LockStep/Match.meta", "repo_id": "ET", "token_count": 72 }
151
fileFormatVersion: 2 guid: 9310265e136b6074cac1754f44280871 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Server/Module/ActorLocation.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Module/ActorLocation.meta", "repo_id": "ET", "token_count": 67 }
152
fileFormatVersion: 2 guid: 1be6139db3006b9419935261c3d0414e folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Server/Module/Http.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Module/Http.meta", "repo_id": "ET", "token_count": 68 }
153
fileFormatVersion: 2 guid: 49cfb0bef9f14131b988f817eff4313b timeCreated: 1688535429
ET/Unity/Assets/Scripts/Model/Server/Module/NetInner/A2NetInner_Message.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Server/Module/NetInner/A2NetInner_Message.cs.meta", "repo_id": "ET", "token_count": 37 }
154
using System; using System.Collections.Generic; namespace ET { public interface ILSRollback { } public interface ILSRollbackSystem: ISystemType { void Run(Entity o); } [LSEntitySystem] public abstract class LSRollbackSystem<T>: SystemObject, ILSRollbackSystem where T: Entity, ILSRollback { void ILSRollbackSystem.Run(Entity o) { this.LSRollback((T)o); } Type ISystemType.Type() { return typeof(T); } Type ISystemType.SystemType() { return typeof(ILSRollbackSystem); } int ISystemType.GetInstanceQueueIndex() { return InstanceQueueIndex.None; } protected abstract void LSRollback(T self); } }
ET/Unity/Assets/Scripts/Model/Share/LockStep/ILSRollbackSystem.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/LockStep/ILSRollbackSystem.cs", "repo_id": "ET", "token_count": 385 }
155
using MemoryPack; namespace ET { [ComponentOf(typeof(LSUnit))] [MemoryPackable] public partial class LSInputComponent: LSEntity, ILSUpdate, IAwake, ISerializeToEntity { public LSInput LSInput { get; set; } } }
ET/Unity/Assets/Scripts/Model/Share/LockStep/LSInputComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/LockStep/LSInputComponent.cs", "repo_id": "ET", "token_count": 95 }
156
fileFormatVersion: 2 guid: 4ad8d604046d19e40a023fa31ed2265f folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Share/Module.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Module.meta", "repo_id": "ET", "token_count": 69 }
157
using System; namespace ET { public abstract class MessageSessionHandler<Message>: HandlerObject, IMessageSessionHandler where Message : MessageObject { protected abstract ETTask Run(Session session, Message message); public void Handle(Session session, object msg) { HandleAsync(session, msg).Coroutine(); } private async ETTask HandleAsync(Session session, object message) { if (message == null) { Log.Error($"消息类型转换错误: {message.GetType().FullName} to {typeof (Message).Name}"); return; } if (session.IsDisposed) { Log.Error($"session disconnect {message}"); return; } await this.Run(session, (Message)message); } public Type GetMessageType() { return typeof (Message); } public Type GetResponseType() { return null; } } public abstract class MessageSessionHandler<Request, Response>: HandlerObject, IMessageSessionHandler where Request : MessageObject, IRequest where Response : MessageObject, IResponse { protected abstract ETTask Run(Session session, Request request, Response response); public void Handle(Session session, object message) { HandleAsync(session, message).Coroutine(); } private async ETTask HandleAsync(Session session, object message) { try { Request request = message as Request; if (request == null) { throw new Exception($"消息类型转换错误: {message.GetType().FullName} to {typeof (Request).FullName}"); } int rpcId = request.RpcId; long instanceId = session.InstanceId; // 这里用using很安全,因为后面是session发送出去了 using Response response = ObjectPool.Instance.Fetch<Response>(); try { await this.Run(session, request, response); } catch (RpcException exception) { // 这里不能返回堆栈给客户端 Log.Error(exception.ToString()); response.Error = exception.Error; } catch (Exception exception) { // 这里不能返回堆栈给客户端 Log.Error(exception.ToString()); response.Error = ErrorCore.ERR_RpcFail; } // 等回调回来,session可以已经断开了,所以需要判断session InstanceId是否一样 if (session.InstanceId != instanceId) { return; } response.RpcId = rpcId; // 在这里设置rpcId是为了防止在Run中不小心修改rpcId字段 session.Send(response); } catch (Exception e) { throw new Exception($"解释消息失败: {message.GetType().FullName}", e); } } public Type GetMessageType() { return typeof (Request); } public Type GetResponseType() { return typeof (Response); } } }
ET/Unity/Assets/Scripts/Model/Share/Module/Message/MessageSessionHandler.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Message/MessageSessionHandler.cs", "repo_id": "ET", "token_count": 1886 }
158
fileFormatVersion: 2 guid: 0abfe3cf9ea0c8d41a0afe2920c080bb MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/Model/Share/Module/Move/MoveEventType.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Move/MoveEventType.cs.meta", "repo_id": "ET", "token_count": 95 }
159
using System; using System.Collections.Generic; using DotRecast.Core; using DotRecast.Detour; namespace ET { /// <summary> /// 同一块地图可能有多种寻路数据,玩家可以随时切换,怪物也可能跟玩家的寻路不一样,寻路组件应该挂在Unit上 /// </summary> [ComponentOf(typeof(Unit))] public class PathfindingComponent: Entity, IAwake<string>, IDestroy { public const int MAX_POLYS = 256; public const int FindRandomNavPosMaxRadius = 15000; // 随机找寻路点的最大半径 public RcVec3f extents = new(15, 10, 15); public string Name; public DtNavMesh navMesh; public List<long> polys = new(MAX_POLYS); public IDtQueryFilter filter; public List<StraightPathItem> straightPath = new(); public DtNavMeshQuery query; } }
ET/Unity/Assets/Scripts/Model/Share/Module/Recast/PathfindingComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Recast/PathfindingComponent.cs", "repo_id": "ET", "token_count": 460 }
160
using System; using System.Collections.Generic; using System.Reflection; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Conventions; using TrueSync; using Unity.Mathematics; namespace ET { public static class MongoRegister { private static void RegisterStruct<T>() where T : struct { BsonSerializer.RegisterSerializer(typeof (T), new StructBsonSerialize<T>()); } public static void Init() { // 清理老的数据 MethodInfo createSerializerRegistry = typeof (BsonSerializer).GetMethod("CreateSerializerRegistry", BindingFlags.Static | BindingFlags.NonPublic); createSerializerRegistry.Invoke(null, Array.Empty<object>()); MethodInfo registerIdGenerators = typeof (BsonSerializer).GetMethod("RegisterIdGenerators", BindingFlags.Static | BindingFlags.NonPublic); registerIdGenerators.Invoke(null, Array.Empty<object>()); // 自动注册IgnoreExtraElements ConventionPack conventionPack = new() { new IgnoreExtraElementsConvention(true) }; ConventionRegistry.Register("IgnoreExtraElements", conventionPack, type => true); RegisterStruct<float2>(); RegisterStruct<float3>(); RegisterStruct<float4>(); RegisterStruct<quaternion>(); RegisterStruct<FP>(); RegisterStruct<TSVector>(); RegisterStruct<TSVector2>(); RegisterStruct<TSVector4>(); RegisterStruct<TSQuaternion>(); RegisterStruct<LSInput>(); Dictionary<string, Type> types = CodeTypes.Instance.GetTypes(); foreach (Type type in types.Values) { if (!type.IsSubclassOf(typeof (Object))) { continue; } if (type.IsGenericType) { continue; } BsonClassMap.LookupClassMap(type); } } } }
ET/Unity/Assets/Scripts/Model/Share/MongoRegister.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/Model/Share/MongoRegister.cs", "repo_id": "ET", "token_count": 961 }
161
fileFormatVersion: 2 guid: 137b9a9afa07bc346a600d906e6acf8e folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ModelView/Client/Demo/UI.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ModelView/Client/Demo/UI.meta", "repo_id": "ET", "token_count": 70 }
162
using System.Collections.Generic; using UnityEngine; namespace ET.Client { public enum MotionType { None, Idle, Run, } [ComponentOf] public class AnimatorComponent : Entity, IAwake, IUpdate, IDestroy { public Dictionary<string, AnimationClip> animationClips = new(); public HashSet<string> Parameter = new(); public MotionType MotionType; public float MontionSpeed; public bool isStop; public float stopSpeed; public Animator Animator; } }
ET/Unity/Assets/Scripts/ModelView/Client/Demo/Unit/AnimatorComponent.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ModelView/Client/Demo/Unit/AnimatorComponent.cs", "repo_id": "ET", "token_count": 162 }
163
fileFormatVersion: 2 guid: 8a47a9c1731af4f6b976d8c1c0a5c6b4 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ModelView/Client/LockStep/UI.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ModelView/Client/LockStep/UI.meta", "repo_id": "ET", "token_count": 77 }
164
fileFormatVersion: 2 guid: e856c423a1f6fc94ba8601e52423851d folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ModelView/Client/Module/UI.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ModelView/Client/Module/UI.meta", "repo_id": "ET", "token_count": 69 }
165
fileFormatVersion: 2 guid: 15fc04bfffbb11842979476b0640b506 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ModelView/Client/Plugins/Example.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ModelView/Client/Plugins/Example.meta", "repo_id": "ET", "token_count": 66 }
166
fileFormatVersion: 2 guid: bd8c346f031de6f4198b9739a9078b84 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/FRand.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/FRand.cs.meta", "repo_id": "ET", "token_count": 96 }
167
fileFormatVersion: 2 guid: c622a9076061add4f952ac8e4bd8280b MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcHashCodes.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcHashCodes.cs.meta", "repo_id": "ET", "token_count": 95 }
168
fileFormatVersion: 2 guid: 669ce24ed3ba4a3459c61f811c246bf7 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcSortedQueue.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcSortedQueue.cs.meta", "repo_id": "ET", "token_count": 95 }
169
namespace DotRecast.Detour.Crowd { public enum DtMoveRequestState { DT_CROWDAGENT_TARGET_NONE, DT_CROWDAGENT_TARGET_FAILED, DT_CROWDAGENT_TARGET_VALID, DT_CROWDAGENT_TARGET_REQUESTING, DT_CROWDAGENT_TARGET_WAITING_FOR_QUEUE, DT_CROWDAGENT_TARGET_WAITING_FOR_PATH, DT_CROWDAGENT_TARGET_VELOCITY, }; }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/DtMoveRequestState.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/DtMoveRequestState.cs", "repo_id": "ET", "token_count": 208 }
170
/* 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.Collections.Generic; using DotRecast.Core; namespace DotRecast.Detour.Crowd { public class DtPathQueue { private readonly DtCrowdConfig config; private readonly LinkedList<DtPathQuery> queue = new LinkedList<DtPathQuery>(); public DtPathQueue(DtCrowdConfig config) { this.config = config; } public void Update(DtNavMesh navMesh) { // Update path request until there is nothing to update or up to maxIters pathfinder iterations has been // consumed. int iterCount = config.maxFindPathIterations; while (iterCount > 0) { DtPathQuery q = queue.First?.Value; if (q == null) { break; } queue.RemoveFirst(); // Handle query start. if (q.result.status.IsEmpty()) { q.navQuery = new DtNavMeshQuery(navMesh); q.result.status = q.navQuery.InitSlicedFindPath(q.startRef, q.endRef, q.startPos, q.endPos, q.filter, 0); } // Handle query in progress. if (q.result.status.InProgress()) { q.result.status = q.navQuery.UpdateSlicedFindPath(iterCount, out var iters); iterCount -= iters; } if (q.result.status.Succeeded()) { q.result.status = q.navQuery.FinalizeSlicedFindPath(ref q.result.path); } if (!(q.result.status.Failed() || q.result.status.Succeeded())) { queue.AddFirst(q); } } } public DtPathQueryResult Request(long startRef, long endRef, RcVec3f startPos, RcVec3f endPos, IDtQueryFilter filter) { if (queue.Count >= config.pathQueueSize) { return null; } DtPathQuery q = new DtPathQuery(); q.startPos = startPos; q.startRef = startRef; q.endPos = endPos; q.endRef = endRef; q.filter = filter; queue.AddLast(q); return q.result; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/DtPathQueue.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/DtPathQueue.cs", "repo_id": "ET", "token_count": 1534 }
171
/* 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 System.IO; using DotRecast.Core; using DotRecast.Detour.Io; namespace DotRecast.Detour.Dynamic.Io { public class VoxelFileReader { private readonly IRcCompressor _compressor; public VoxelFileReader(IRcCompressor compressor) { _compressor = compressor; } public VoxelFile Read(BinaryReader stream) { RcByteBuffer buf = IOUtils.ToByteBuffer(stream); VoxelFile file = new VoxelFile(); int magic = buf.GetInt(); if (magic != VoxelFile.MAGIC) { magic = IOUtils.SwapEndianness(magic); if (magic != VoxelFile.MAGIC) { throw new IOException("Invalid magic"); } buf.Order(buf.Order() == RcByteOrder.BIG_ENDIAN ? RcByteOrder.LITTLE_ENDIAN : RcByteOrder.BIG_ENDIAN); } file.version = buf.GetInt(); bool isExportedFromAstar = (file.version & VoxelFile.VERSION_EXPORTER_MASK) == 0; bool compression = (file.version & VoxelFile.VERSION_COMPRESSION_MASK) == VoxelFile.VERSION_COMPRESSION_LZ4; file.walkableRadius = buf.GetFloat(); file.walkableHeight = buf.GetFloat(); file.walkableClimb = buf.GetFloat(); file.walkableSlopeAngle = buf.GetFloat(); file.cellSize = buf.GetFloat(); file.maxSimplificationError = buf.GetFloat(); file.maxEdgeLen = buf.GetFloat(); file.minRegionArea = (int)buf.GetFloat(); if (!isExportedFromAstar) { file.regionMergeArea = buf.GetFloat(); file.vertsPerPoly = buf.GetInt(); file.buildMeshDetail = buf.Get() != 0; file.detailSampleDistance = buf.GetFloat(); file.detailSampleMaxError = buf.GetFloat(); } else { file.regionMergeArea = 6 * file.minRegionArea; file.vertsPerPoly = 6; file.buildMeshDetail = true; file.detailSampleDistance = file.maxEdgeLen * 0.5f; file.detailSampleMaxError = file.maxSimplificationError * 0.8f; } file.useTiles = buf.Get() != 0; file.tileSizeX = buf.GetInt(); file.tileSizeZ = buf.GetInt(); file.rotation.x = buf.GetFloat(); file.rotation.y = buf.GetFloat(); file.rotation.z = buf.GetFloat(); file.bounds[0] = buf.GetFloat(); file.bounds[1] = buf.GetFloat(); file.bounds[2] = buf.GetFloat(); file.bounds[3] = buf.GetFloat(); file.bounds[4] = buf.GetFloat(); file.bounds[5] = buf.GetFloat(); if (isExportedFromAstar) { // bounds are saved as center + size file.bounds[0] -= 0.5f * file.bounds[3]; file.bounds[1] -= 0.5f * file.bounds[4]; file.bounds[2] -= 0.5f * file.bounds[5]; file.bounds[3] += file.bounds[0]; file.bounds[4] += file.bounds[1]; file.bounds[5] += file.bounds[2]; } int tileCount = buf.GetInt(); for (int tile = 0; tile < tileCount; tile++) { int tileX = buf.GetInt(); int tileZ = buf.GetInt(); int width = buf.GetInt(); int depth = buf.GetInt(); int borderSize = buf.GetInt(); RcVec3f boundsMin = new RcVec3f(); boundsMin.x = buf.GetFloat(); boundsMin.y = buf.GetFloat(); boundsMin.z = buf.GetFloat(); RcVec3f boundsMax = new RcVec3f(); boundsMax.x = buf.GetFloat(); boundsMax.y = buf.GetFloat(); boundsMax.z = buf.GetFloat(); if (isExportedFromAstar) { // bounds are local boundsMin.x += file.bounds[0]; boundsMin.y += file.bounds[1]; boundsMin.z += file.bounds[2]; boundsMax.x += file.bounds[0]; boundsMax.y += file.bounds[1]; boundsMax.z += file.bounds[2]; } float cellSize = buf.GetFloat(); float cellHeight = buf.GetFloat(); int voxelSize = buf.GetInt(); int position = buf.Position(); byte[] bytes = buf.ReadBytes(voxelSize).ToArray(); if (compression) { bytes = _compressor.Decompress(bytes); } RcByteBuffer data = new RcByteBuffer(bytes); data.Order(buf.Order()); file.AddTile(new VoxelTile(tileX, tileZ, width, depth, boundsMin, boundsMax, cellSize, cellHeight, borderSize, data)); buf.Position(position + voxelSize); } return file; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Dynamic/Io/VoxelFileReader.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Dynamic/Io/VoxelFileReader.cs", "repo_id": "ET", "token_count": 3012 }
172
using System; using DotRecast.Core; namespace DotRecast.Detour.Extras.Jumplink { public class ClimbTrajectory : Trajectory { public override RcVec3f Apply(RcVec3f start, RcVec3f end, float u) { return new RcVec3f() { x = Lerp(start.x, end.x, Math.Min(2f * u, 1f)), y = Lerp(start.y, end.y, Math.Max(0f, 2f * u - 1f)), z = Lerp(start.z, end.z, Math.Min(2f * u, 1f)) }; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/ClimbTrajectory.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/ClimbTrajectory.cs", "repo_id": "ET", "token_count": 286 }
173
namespace DotRecast.Detour.Extras.Jumplink { public class JumpLink { public const int MAX_SPINE = 8; public readonly int nspine = MAX_SPINE; public readonly float[] spine0 = new float[MAX_SPINE * 3]; public readonly float[] spine1 = new float[MAX_SPINE * 3]; public GroundSample[] startSamples; public GroundSample[] endSamples; public GroundSegment start; public GroundSegment end; public Trajectory trajectory; } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/JumpLink.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/JumpLink.cs", "repo_id": "ET", "token_count": 203 }
174
using System; namespace DotRecast.Detour.Extras.Jumplink { public class PolyQueryInvoker : IDtPolyQuery { public readonly Action<DtMeshTile, DtPoly, long> _callback; public PolyQueryInvoker(Action<DtMeshTile, DtPoly, long> callback) { _callback = callback; } public void Process(DtMeshTile tile, DtPoly poly, long refs) { _callback?.Invoke(tile, poly, refs); } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/PolyQueryInvoker.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/PolyQueryInvoker.cs", "repo_id": "ET", "token_count": 215 }
175
fileFormatVersion: 2 guid: 2b1412777b3ec4a4d9dda49849cf8783 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.TileCache/DtLayerSweepSpan.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.TileCache/DtLayerSweepSpan.cs.meta", "repo_id": "ET", "token_count": 95 }
176
fileFormatVersion: 2 guid: 1b74942eb8d1c0a44800d08731c3aa02 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.TileCache/Io/Compress.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.TileCache/Io/Compress.meta", "repo_id": "ET", "token_count": 72 }
177
fileFormatVersion: 2 guid: ca29cd0f3be4d1e44a831c0e2378e037 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.TileCache/Io/DtTileCacheWriter.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.TileCache/Io/DtTileCacheWriter.cs.meta", "repo_id": "ET", "token_count": 98 }
178
/* 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 System; using DotRecast.Core; namespace DotRecast.Detour { /** * Convex-convex intersection based on "Computational Geometry in C" by Joseph O'Rourke */ public static class ConvexConvexIntersection { private static readonly float EPSILON = 0.0001f; public static float[] Intersect(float[] p, float[] q) { int n = p.Length / 3; int m = q.Length / 3; float[] inters = new float[Math.Max(m, n) * 3 * 3]; int ii = 0; /* Initialize variables. */ RcVec3f a = new RcVec3f(); RcVec3f b = new RcVec3f(); RcVec3f a1 = new RcVec3f(); RcVec3f b1 = new RcVec3f(); int aa = 0; int ba = 0; int ai = 0; int bi = 0; InFlag f = InFlag.Unknown; bool FirstPoint = true; RcVec3f ip = new RcVec3f(); RcVec3f iq = new RcVec3f(); do { a.Set(p, 3 * (ai % n)); b.Set(q, 3 * (bi % m)); a1.Set(p, 3 * ((ai + n - 1) % n)); // prev a b1.Set(q, 3 * ((bi + m - 1) % m)); // prev b RcVec3f A = a.Subtract(a1); RcVec3f B = b.Subtract(b1); float cross = B.x * A.z - A.x * B.z; // TriArea2D({0, 0}, A, B); float aHB = DtUtils.TriArea2D(b1, b, a); float bHA = DtUtils.TriArea2D(a1, a, b); if (Math.Abs(cross) < EPSILON) { cross = 0f; } bool parallel = cross == 0f; Intersection code = parallel ? ParallelInt(a1, a, b1, b, ref ip, ref iq) : SegSegInt(a1, a, b1, b, ref ip, ref iq); if (code == Intersection.Single) { if (FirstPoint) { FirstPoint = false; aa = ba = 0; } ii = AddVertex(inters, ii, ip); f = InOut(f, aHB, bHA); } /*-----Advance rules-----*/ /* Special case: A & B overlap and oppositely oriented. */ if (code == Intersection.Overlap && A.Dot2D(B) < 0) { ii = AddVertex(inters, ii, ip); ii = AddVertex(inters, ii, iq); break; } /* Special case: A & B parallel and separated. */ if (parallel && aHB < 0f && bHA < 0f) { return null; } /* Special case: A & B collinear. */ else if (parallel && Math.Abs(aHB) < EPSILON && Math.Abs(bHA) < EPSILON) { /* Advance but do not output point. */ if (f == InFlag.Pin) { ba++; bi++; } else { aa++; ai++; } } /* Generic cases. */ else if (cross >= 0) { if (bHA > 0) { if (f == InFlag.Pin) { ii = AddVertex(inters, ii, a); } aa++; ai++; } else { if (f == InFlag.Qin) { ii = AddVertex(inters, ii, b); } ba++; bi++; } } else { if (aHB > 0) { if (f == InFlag.Qin) { ii = AddVertex(inters, ii, b); } ba++; bi++; } else { if (f == InFlag.Pin) { ii = AddVertex(inters, ii, a); } aa++; ai++; } } /* Quit when both adv. indices have cycled, or one has cycled twice. */ } while ((aa < n || ba < m) && aa < 2 * n && ba < 2 * m); /* Deal with special cases: not implemented. */ if (f == InFlag.Unknown) { return null; } float[] copied = new float[ii]; Array.Copy(inters, copied, ii); return copied; } private static int AddVertex(float[] inters, int ii, float[] p) { if (ii > 0) { if (inters[ii - 3] == p[0] && inters[ii - 2] == p[1] && inters[ii - 1] == p[2]) { return ii; } if (inters[0] == p[0] && inters[1] == p[1] && inters[2] == p[2]) { return ii; } } inters[ii] = p[0]; inters[ii + 1] = p[1]; inters[ii + 2] = p[2]; return ii + 3; } private static int AddVertex(float[] inters, int ii, RcVec3f p) { if (ii > 0) { if (inters[ii - 3] == p.x && inters[ii - 2] == p.y && inters[ii - 1] == p.z) { return ii; } if (inters[0] == p.x && inters[1] == p.y && inters[2] == p.z) { return ii; } } inters[ii] = p.x; inters[ii + 1] = p.y; inters[ii + 2] = p.z; return ii + 3; } private static InFlag InOut(InFlag inflag, float aHB, float bHA) { if (aHB > 0) { return InFlag.Pin; } else if (bHA > 0) { return InFlag.Qin; } return inflag; } private static Intersection SegSegInt(RcVec3f a, RcVec3f b, RcVec3f c, RcVec3f d, ref RcVec3f p, ref RcVec3f q) { if (DtUtils.IntersectSegSeg2D(a, b, c, d, out var s, out var t)) { if (s >= 0.0f && s <= 1.0f && t >= 0.0f && t <= 1.0f) { p.x = a.x + (b.x - a.x) * s; p.y = a.y + (b.y - a.y) * s; p.z = a.z + (b.z - a.z) * s; return Intersection.Single; } } return Intersection.None; } private static Intersection ParallelInt(RcVec3f a, RcVec3f b, RcVec3f c, RcVec3f d, ref RcVec3f p, ref RcVec3f q) { if (Between(a, b, c) && Between(a, b, d)) { p = c; q = d; return Intersection.Overlap; } if (Between(c, d, a) && Between(c, d, b)) { p = a; q = b; return Intersection.Overlap; } if (Between(a, b, c) && Between(c, d, b)) { p = c; q = b; return Intersection.Overlap; } if (Between(a, b, c) && Between(c, d, a)) { p = c; q = a; return Intersection.Overlap; } if (Between(a, b, d) && Between(c, d, b)) { p = d; q = b; return Intersection.Overlap; } if (Between(a, b, d) && Between(c, d, a)) { p = d; q = a; return Intersection.Overlap; } return Intersection.None; } private static bool Between(RcVec3f a, RcVec3f b, RcVec3f c) { if (Math.Abs(a.x - b.x) > Math.Abs(a.z - b.z)) { return ((a.x <= c.x) && (c.x <= b.x)) || ((a.x >= c.x) && (c.x >= b.x)); } else { return ((a.z <= c.z) && (c.z <= b.z)) || ((a.z >= c.z) && (c.z >= b.z)); } } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/ConvexConvexIntersection.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/ConvexConvexIntersection.cs", "repo_id": "ET", "token_count": 6043 }
179
/* 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 { /** * Simple helper to find an intersection between a ray and a nav mesh */ public static class DtNavMeshRaycast { public static bool Raycast(DtNavMesh mesh, RcVec3f src, RcVec3f dst, out float hitTime) { hitTime = 0.0f; for (int t = 0; t < mesh.GetMaxTiles(); ++t) { DtMeshTile tile = mesh.GetTile(t); if (tile != null && tile.data != null) { if (Raycast(tile, src, dst, out hitTime)) { return true; } } } return false; } private static bool Raycast(DtMeshTile tile, RcVec3f sp, RcVec3f sq, out float hitTime) { hitTime = 0.0f; for (int i = 0; i < tile.data.header.polyCount; ++i) { DtPoly p = tile.data.polys[i]; if (p.GetPolyType() == DtPoly.DT_POLYTYPE_OFFMESH_CONNECTION) { continue; } DtPolyDetail pd = tile.data.detailMeshes[i]; if (pd != null) { RcVec3f[] verts = new RcVec3f[3]; for (int j = 0; j < pd.triCount; ++j) { int t = (pd.triBase + j) * 4; for (int k = 0; k < 3; ++k) { int v = tile.data.detailTris[t + k]; if (v < p.vertCount) { verts[k].x = tile.data.verts[p.verts[v] * 3]; verts[k].y = tile.data.verts[p.verts[v] * 3 + 1]; verts[k].z = tile.data.verts[p.verts[v] * 3 + 2]; } else { verts[k].x = tile.data.detailVerts[(pd.vertBase + v - p.vertCount) * 3]; verts[k].y = tile.data.detailVerts[(pd.vertBase + v - p.vertCount) * 3 + 1]; verts[k].z = tile.data.detailVerts[(pd.vertBase + v - p.vertCount) * 3 + 2]; } } if (Intersections.IntersectSegmentTriangle(sp, sq, verts[0], verts[1], verts[2], out hitTime)) { return true; } } } else { // FIXME: Use Poly if PolyDetail is unavailable } } return false; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtNavMeshRaycast.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtNavMeshRaycast.cs", "repo_id": "ET", "token_count": 2069 }
180
using DotRecast.Core; namespace DotRecast.Detour { public readonly struct DtPolyPoint { public readonly long refs; public readonly RcVec3f pt; public DtPolyPoint(long polyRefs, RcVec3f polyPt) { refs = polyRefs; pt = polyPt; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtPolyPoint.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtPolyPoint.cs", "repo_id": "ET", "token_count": 164 }
181
using DotRecast.Core; namespace DotRecast.Detour { public class DtStraightPathOption { public static readonly DtStraightPathOption None = new DtStraightPathOption(0, "None"); public static readonly DtStraightPathOption AreaCrossings = new DtStraightPathOption(DtNavMeshQuery.DT_STRAIGHTPATH_AREA_CROSSINGS, "Area"); public static readonly DtStraightPathOption AllCrossings = new DtStraightPathOption(DtNavMeshQuery.DT_STRAIGHTPATH_ALL_CROSSINGS, "All"); public static readonly RcImmutableArray<DtStraightPathOption> Values = RcImmutableArray.Create( None, AreaCrossings, AllCrossings ); public readonly int Value; public readonly string Label; private DtStraightPathOption(int value, string label) { Value = value; Label = label; } } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtStraightPathOption.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtStraightPathOption.cs", "repo_id": "ET", "token_count": 349 }
182
namespace DotRecast.Detour { public enum Intersection { None, Single, Overlap, } }
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/Intersection.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/Intersection.cs", "repo_id": "ET", "token_count": 64 }
183
fileFormatVersion: 2 guid: 9c9a131c03c797a43b20259a251adb7a MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcConfig.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcConfig.cs.meta", "repo_id": "ET", "token_count": 95 }
184
fileFormatVersion: 2 guid: 42ee7b70d14a6b240a234ddd7beabd3d MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcHeightPatch.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcHeightPatch.cs.meta", "repo_id": "ET", "token_count": 96 }
185
fileFormatVersion: 2 guid: 05192641e17049343b6696240e00a95d MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcPolyMeshDetail.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcPolyMeshDetail.cs.meta", "repo_id": "ET", "token_count": 92 }
186
fileFormatVersion: 2 guid: de4eebd712f13a3408584d9f3619c9a9 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RecastArea.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RecastArea.cs.meta", "repo_id": "ET", "token_count": 95 }
187
fileFormatVersion: 2 guid: eec597a8f8d458142be9eed7240f48c4 MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RecastFilter.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RecastFilter.cs.meta", "repo_id": "ET", "token_count": 94 }
188
using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Security; namespace ET { public struct ETAsyncTaskMethodBuilder { private IStateMachineWrap iStateMachineWrap; private ETTask tcs; // 1. Static Create method. [DebuggerHidden] public static ETAsyncTaskMethodBuilder Create() { ETAsyncTaskMethodBuilder builder = new() { tcs = ETTask.Create(true) }; return builder; } // 2. TaskLike Task property. [DebuggerHidden] public ETTask Task => this.tcs; // 3. SetException [DebuggerHidden] public void SetException(Exception exception) { if (this.iStateMachineWrap != null) { this.iStateMachineWrap.Recycle(); this.iStateMachineWrap = null; } this.tcs.SetException(exception); } // 4. SetResult [DebuggerHidden] public void SetResult() { if (this.iStateMachineWrap != null) { this.iStateMachineWrap.Recycle(); this.iStateMachineWrap = null; } this.tcs.SetResult(); } // 5. AwaitOnCompleted [DebuggerHidden] public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { this.iStateMachineWrap ??= StateMachineWrap<TStateMachine>.Fetch(ref stateMachine); awaiter.OnCompleted(this.iStateMachineWrap.MoveNext); } // 6. AwaitUnsafeOnCompleted [DebuggerHidden] [SecuritySafeCritical] public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { this.iStateMachineWrap ??= StateMachineWrap<TStateMachine>.Fetch(ref stateMachine); awaiter.UnsafeOnCompleted(this.iStateMachineWrap.MoveNext); } // 7. Start [DebuggerHidden] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { stateMachine.MoveNext(); } // 8. SetStateMachine [DebuggerHidden] public void SetStateMachine(IAsyncStateMachine stateMachine) { } } public struct ETAsyncTaskMethodBuilder<T> { private IStateMachineWrap iStateMachineWrap; private ETTask<T> tcs; // 1. Static Create method. [DebuggerHidden] public static ETAsyncTaskMethodBuilder<T> Create() { ETAsyncTaskMethodBuilder<T> builder = new ETAsyncTaskMethodBuilder<T>() { tcs = ETTask<T>.Create(true) }; return builder; } // 2. TaskLike Task property. [DebuggerHidden] public ETTask<T> Task => this.tcs; // 3. SetException [DebuggerHidden] public void SetException(Exception exception) { if (this.iStateMachineWrap != null) { this.iStateMachineWrap.Recycle(); this.iStateMachineWrap = null; } this.tcs.SetException(exception); } // 4. SetResult [DebuggerHidden] public void SetResult(T ret) { if (this.iStateMachineWrap != null) { this.iStateMachineWrap.Recycle(); this.iStateMachineWrap = null; } this.tcs.SetResult(ret); } // 5. AwaitOnCompleted [DebuggerHidden] public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { this.iStateMachineWrap ??= StateMachineWrap<TStateMachine>.Fetch(ref stateMachine); awaiter.OnCompleted(this.iStateMachineWrap.MoveNext); } // 6. AwaitUnsafeOnCompleted [DebuggerHidden] [SecuritySafeCritical] public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { this.iStateMachineWrap ??= StateMachineWrap<TStateMachine>.Fetch(ref stateMachine); awaiter.UnsafeOnCompleted(this.iStateMachineWrap.MoveNext); } // 7. Start [DebuggerHidden] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { stateMachine.MoveNext(); } // 8. SetStateMachine [DebuggerHidden] public void SetStateMachine(IAsyncStateMachine stateMachine) { } } }
ET/Unity/Assets/Scripts/ThirdParty/ETTask/AsyncETTaskMethodBuilder.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/ETTask/AsyncETTaskMethodBuilder.cs", "repo_id": "ET", "token_count": 2275 }
189
using System; using System.Collections.Concurrent; using System.Runtime.CompilerServices; namespace ET { public interface IStateMachineWrap { Action MoveNext { get; } void Recycle(); } public class StateMachineWrap<T>: IStateMachineWrap where T: IAsyncStateMachine { private static readonly ConcurrentQueue<StateMachineWrap<T>> queue = new(); public static StateMachineWrap<T> Fetch(ref T stateMachine) { if (!queue.TryDequeue(out var stateMachineWrap)) { stateMachineWrap = new StateMachineWrap<T>(); } stateMachineWrap.StateMachine = stateMachine; return stateMachineWrap; } public void Recycle() { if (queue.Count > 1000) { return; } queue.Enqueue(this); } private readonly Action moveNext; public Action MoveNext { get { return this.moveNext; } } private T StateMachine; private StateMachineWrap() { this.moveNext = this.Run; } private void Run() { this.StateMachine.MoveNext(); } } }
ET/Unity/Assets/Scripts/ThirdParty/ETTask/StateMachineWrap.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/ETTask/StateMachineWrap.cs", "repo_id": "ET", "token_count": 662 }
190
fileFormatVersion: 2 guid: 28fd7d4bb9a824847b548d99ccf75eea MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/FixedSizeMemoryPool/FixedSizeMemoryPool.cs.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/FixedSizeMemoryPool/FixedSizeMemoryPool.cs.meta", "repo_id": "ET", "token_count": 95 }
191
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text; namespace NativeCollection.UnsafeType { public unsafe struct List<T> : ICollection<T>, IDisposable, IPool where T : unmanaged, IEquatable<T> { private List<T>* self; private int _arrayLength; private T* _items; private const int _defaultCapacity = 4; public static List<T>* Create(int initialCapacity = _defaultCapacity) { if (initialCapacity < 0) ThrowHelper.ListInitialCapacityException(); var list = (List<T>*)NativeMemoryHelper.Alloc((UIntPtr)Unsafe.SizeOf<List<T>>()); if (initialCapacity < _defaultCapacity) initialCapacity = _defaultCapacity; // Simplify doubling logic in Push. list->_items = (T*)NativeMemoryHelper.Alloc((UIntPtr)initialCapacity, (UIntPtr)Unsafe.SizeOf<T>()); list->_arrayLength = initialCapacity; list->Count = 0; list->self = list; return list; } public static List<T>* AllocFromMemoryPool(FixedSizeMemoryPool* memoryPool,int initialCapacity = _defaultCapacity) { if (initialCapacity < 0) ThrowHelper.ListInitialCapacityException(); var list = (List<T>*)memoryPool->Alloc(); if (initialCapacity < _defaultCapacity) initialCapacity = _defaultCapacity; // Simplify doubling logic in Push. list->_items = (T*)NativeMemoryHelper.Alloc((UIntPtr)initialCapacity, (UIntPtr)Unsafe.SizeOf<T>()); list->_arrayLength = initialCapacity; list->Count = 0; list->self = list; return list; } public ref T this[int index] { get { if (index>=Count) { ThrowHelper.IndexMustBeLessException(); } return ref *(_items + index); } } public int Capacity { get => _arrayLength; set { if (value < Count) ThrowHelper.ListSmallCapacity(); if (value != _arrayLength) { if (value > 0) { var newArray = (T*)NativeMemoryHelper.Alloc((UIntPtr)value, (UIntPtr)Unsafe.SizeOf<T>()); if (Count > 0) Unsafe.CopyBlockUnaligned(newArray, _items, (uint)(_arrayLength * Unsafe.SizeOf<T>())); NativeMemoryHelper.Free(_items); NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<T>() * _arrayLength); _items = newArray; _arrayLength = value; } else { ThrowHelper.ListSmallCapacity(); } } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(T value) { AddRef(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AddRef(T value) { var array = _items; var size = Count; if ((uint)size < (uint)_arrayLength) { Count = size + 1; array[size] = value; } else { AddWithResize(value); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(T[] array, int arrayIndex) { throw new NotImplementedException(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Remove(T item) { return RemoveRef(item); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool RemoveRef(in T item) { var index = IndexOf(item); //Console.WriteLine($"index: {index}"); if (index >= 0) { RemoveAt(index); return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int IndexOf(in T item) { return new Span<T>(_items, Count).IndexOf(item); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void RemoveAt(int index) { if ((uint)index >= (uint)Count) ThrowHelper.IndexMustBeLessException(); Count--; if (index < Count) Unsafe.CopyBlockUnaligned(_items + index, _items + index + 1, (uint)((Count - index) * Unsafe.SizeOf<T>())); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { Count = 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Contains(T item) { return IndexOf(item) >= 0; } public void Insert(int index, T item) { // Note that insertions at the end are legal. if ((uint)index > (uint)Count) { ThrowHelper.IndexMustBeLessException(); } if (Count == _arrayLength) Grow(Count + 1); if (index < Count) { Unsafe.CopyBlockUnaligned(_items+index+1,_items+index,(uint)(Count-index)); } _items[index] = item; Count++; } public void AddRange(Span<T> collection) { InsertRange(Count, collection); } public void InsertRange(int index, Span<T> collection) { if ((uint)index > (uint)Count) { ThrowHelper.ListIndexOutOfRange(); } int count = collection.Length; if (count > 0) { if (_arrayLength - Count < count) { Grow(Count + count); } if (index < Count) { Unsafe.CopyBlockUnaligned(_items+index+count,_items+index,(uint)(Count-index)); } collection.CopyTo(new Span<T>(_items,index)); Count += count; } } public void RemoveRange(int index, int count) { if (index < 0) { ThrowHelper.ListIndexOutOfRange(); } if (count < 0) { ThrowHelper.ListIndexOutOfRange(); } if (Count - index < count) ThrowHelper.ListIndexOutOfRange(); if (count > 0) { Count -= count; if (index < Count) { Unsafe.CopyBlockUnaligned(_items+index,_items+index+count,(uint)(Count-index)); } } } public void FillDefaultValue() { for (int i = 0; i < _arrayLength; i++) { _items[i] = default; } Count = _arrayLength; } public void ResizeWithDefaultValue(int newSize) { var size = _arrayLength; Capacity = newSize; for (int i = size; i < _arrayLength; i++) { _items[i] = default; } } public int Count { get; private set; } public bool IsReadOnly => false; [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AddWithResize(in T item) { var size = Count; Grow(size + 1); Count = size + 1; _items[size] = item; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void Grow(int capacity) { Debug.Assert(_arrayLength < capacity); var newcapacity = _arrayLength == 0 ? _defaultCapacity : 2 * Count; // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow. // Note that this check works even when _items.Length overflowed thanks to the (uint) cast if ((uint)newcapacity > 0X7FFFFFC7) newcapacity = 0X7FFFFFC7; // If the computed capacity is still less than specified, set to the original argument. // Capacities exceeding Array.MaxLength will be surfaced as OutOfMemoryException by Array.Resize. if (newcapacity < capacity) newcapacity = capacity; Capacity = newcapacity; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> WrittenSpan() { return new Span<T>(_items, Count); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> TotalSpan() { return new Span<T>(_items, _arrayLength); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { NativeMemoryHelper.Free(_items); NativeMemoryHelper.RemoveNativeMemoryByte(_arrayLength * Unsafe.SizeOf<T>()); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Enumerator GetEnumerator() { return new Enumerator(self); } public override string ToString() { var sb = new StringBuilder(); foreach (var item in *self) sb.Append($"{item} "); return sb.ToString(); } public struct Enumerator : IEnumerator<T> { object IEnumerator.Current => Current; private int CurrentIndex; private T CurrentItem; private readonly List<T>* Items; internal Enumerator(List<T>* items) { Items = items; CurrentIndex = 0; CurrentItem = default; } private void Initialize() { CurrentIndex = 0; CurrentItem = default; } public bool MoveNext() { if (CurrentIndex == Items->Count) return false; CurrentItem = Items->_items[CurrentIndex]; CurrentIndex++; return true; } public void Reset() { Initialize(); } public T Current => CurrentItem; public void Dispose() { } } public void OnReturnToPool() { Clear(); } public void OnGetFromPool() { } } }
ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/List.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/List.cs", "repo_id": "ET", "token_count": 4599 }
192
fileFormatVersion: 2 guid: dd839f2e7f753f745a43cfc988a39246 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/SortedSet.meta/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/SortedSet.meta", "repo_id": "ET", "token_count": 70 }
193
#region License /* MIT License Copyright © 2006 The Mono.Xna Team All rights reserved. Authors * Alan McGovern Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion License using System; namespace TrueSync { [Serializable] public struct TSVector2 : IEquatable<TSVector2> { #region Private Fields private static TSVector2 zeroVector = new TSVector2(0, 0); private static TSVector2 oneVector = new TSVector2(1, 1); private static TSVector2 rightVector = new TSVector2(1, 0); private static TSVector2 leftVector = new TSVector2(-1, 0); private static TSVector2 upVector = new TSVector2(0, 1); private static TSVector2 downVector = new TSVector2(0, -1); #endregion Private Fields #region Public Fields public FP x; public FP y; #endregion Public Fields #region Properties public static TSVector2 zero { get { return zeroVector; } } public static TSVector2 one { get { return oneVector; } } public static TSVector2 right { get { return rightVector; } } public static TSVector2 left { get { return leftVector; } } public static TSVector2 up { get { return upVector; } } public static TSVector2 down { get { return downVector; } } #endregion Properties #region Constructors /// <summary> /// Constructor foe standard 2D vector. /// </summary> /// <param name="x"> /// A <see cref="System.Single"/> /// </param> /// <param name="y"> /// A <see cref="System.Single"/> /// </param> public TSVector2(FP x, FP y) { this.x = x; this.y = y; } /// <summary> /// Constructor for "square" vector. /// </summary> /// <param name="value"> /// A <see cref="System.Single"/> /// </param> public TSVector2(FP value) { x = value; y = value; } public void Set(FP x, FP y) { this.x = x; this.y = y; } #endregion Constructors #region Public Methods public static void Reflect(ref TSVector2 vector, ref TSVector2 normal, out TSVector2 result) { FP dot = Dot(vector, normal); result.x = vector.x - ((2f*dot)*normal.x); result.y = vector.y - ((2f*dot)*normal.y); } public static TSVector2 Reflect(TSVector2 vector, TSVector2 normal) { TSVector2 result; Reflect(ref vector, ref normal, out result); return result; } public static TSVector2 Add(TSVector2 value1, TSVector2 value2) { value1.x += value2.x; value1.y += value2.y; return value1; } public static void Add(ref TSVector2 value1, ref TSVector2 value2, out TSVector2 result) { result.x = value1.x + value2.x; result.y = value1.y + value2.y; } public static TSVector2 Barycentric(TSVector2 value1, TSVector2 value2, TSVector2 value3, FP amount1, FP amount2) { return new TSVector2( TSMath.Barycentric(value1.x, value2.x, value3.x, amount1, amount2), TSMath.Barycentric(value1.y, value2.y, value3.y, amount1, amount2)); } public static void Barycentric(ref TSVector2 value1, ref TSVector2 value2, ref TSVector2 value3, FP amount1, FP amount2, out TSVector2 result) { result = new TSVector2( TSMath.Barycentric(value1.x, value2.x, value3.x, amount1, amount2), TSMath.Barycentric(value1.y, value2.y, value3.y, amount1, amount2)); } public static TSVector2 CatmullRom(TSVector2 value1, TSVector2 value2, TSVector2 value3, TSVector2 value4, FP amount) { return new TSVector2( TSMath.CatmullRom(value1.x, value2.x, value3.x, value4.x, amount), TSMath.CatmullRom(value1.y, value2.y, value3.y, value4.y, amount)); } public static void CatmullRom(ref TSVector2 value1, ref TSVector2 value2, ref TSVector2 value3, ref TSVector2 value4, FP amount, out TSVector2 result) { result = new TSVector2( TSMath.CatmullRom(value1.x, value2.x, value3.x, value4.x, amount), TSMath.CatmullRom(value1.y, value2.y, value3.y, value4.y, amount)); } public static TSVector2 Clamp(TSVector2 value1, TSVector2 min, TSVector2 max) { return new TSVector2( TSMath.Clamp(value1.x, min.x, max.x), TSMath.Clamp(value1.y, min.y, max.y)); } public static void Clamp(ref TSVector2 value1, ref TSVector2 min, ref TSVector2 max, out TSVector2 result) { result = new TSVector2( TSMath.Clamp(value1.x, min.x, max.x), TSMath.Clamp(value1.y, min.y, max.y)); } /// <summary> /// Returns FP precison distanve between two vectors /// </summary> /// <param name="value1"> /// A <see cref="TSVector2"/> /// </param> /// <param name="value2"> /// A <see cref="TSVector2"/> /// </param> /// <returns> /// A <see cref="System.Single"/> /// </returns> public static FP Distance(TSVector2 value1, TSVector2 value2) { FP result; DistanceSquared(ref value1, ref value2, out result); return (FP) FP.Sqrt(result); } public static void Distance(ref TSVector2 value1, ref TSVector2 value2, out FP result) { DistanceSquared(ref value1, ref value2, out result); result = (FP) FP.Sqrt(result); } public static FP DistanceSquared(TSVector2 value1, TSVector2 value2) { FP result; DistanceSquared(ref value1, ref value2, out result); return result; } public static void DistanceSquared(ref TSVector2 value1, ref TSVector2 value2, out FP result) { result = (value1.x - value2.x)*(value1.x - value2.x) + (value1.y - value2.y)*(value1.y - value2.y); } /// <summary> /// Devide first vector with the secund vector /// </summary> /// <param name="value1"> /// A <see cref="TSVector2"/> /// </param> /// <param name="value2"> /// A <see cref="TSVector2"/> /// </param> /// <returns> /// A <see cref="TSVector2"/> /// </returns> public static TSVector2 Divide(TSVector2 value1, TSVector2 value2) { value1.x /= value2.x; value1.y /= value2.y; return value1; } public static void Divide(ref TSVector2 value1, ref TSVector2 value2, out TSVector2 result) { result.x = value1.x/value2.x; result.y = value1.y/value2.y; } public static TSVector2 Divide(TSVector2 value1, FP divider) { FP factor = 1/divider; value1.x *= factor; value1.y *= factor; return value1; } public static void Divide(ref TSVector2 value1, FP divider, out TSVector2 result) { FP factor = 1/divider; result.x = value1.x*factor; result.y = value1.y*factor; } public static FP Dot(TSVector2 value1, TSVector2 value2) { return value1.x*value2.x + value1.y*value2.y; } public static void Dot(ref TSVector2 value1, ref TSVector2 value2, out FP result) { result = value1.x*value2.x + value1.y*value2.y; } public override bool Equals(object obj) { return (obj is TSVector2) ? this == ((TSVector2) obj) : false; } public bool Equals(TSVector2 other) { return this == other; } public override int GetHashCode() { return (int) (x + y); } public static TSVector2 Hermite(TSVector2 value1, TSVector2 tangent1, TSVector2 value2, TSVector2 tangent2, FP amount) { TSVector2 result = new TSVector2(); Hermite(ref value1, ref tangent1, ref value2, ref tangent2, amount, out result); return result; } public static void Hermite(ref TSVector2 value1, ref TSVector2 tangent1, ref TSVector2 value2, ref TSVector2 tangent2, FP amount, out TSVector2 result) { result.x = TSMath.Hermite(value1.x, tangent1.x, value2.x, tangent2.x, amount); result.y = TSMath.Hermite(value1.y, tangent1.y, value2.y, tangent2.y, amount); } public FP magnitude { get { FP result; DistanceSquared(ref this, ref zeroVector, out result); return FP.Sqrt(result); } } public static TSVector2 ClampMagnitude(TSVector2 vector, FP maxLength) { return Normalize(vector) * maxLength; } public FP LengthSquared() { FP result; DistanceSquared(ref this, ref zeroVector, out result); return result; } public static TSVector2 Lerp(TSVector2 value1, TSVector2 value2, FP amount) { amount = TSMath.Clamp(amount, 0, 1); return new TSVector2( TSMath.Lerp(value1.x, value2.x, amount), TSMath.Lerp(value1.y, value2.y, amount)); } public static TSVector2 LerpUnclamped(TSVector2 value1, TSVector2 value2, FP amount) { return new TSVector2( TSMath.Lerp(value1.x, value2.x, amount), TSMath.Lerp(value1.y, value2.y, amount)); } public static void LerpUnclamped(ref TSVector2 value1, ref TSVector2 value2, FP amount, out TSVector2 result) { result = new TSVector2( TSMath.Lerp(value1.x, value2.x, amount), TSMath.Lerp(value1.y, value2.y, amount)); } public static TSVector2 Max(TSVector2 value1, TSVector2 value2) { return new TSVector2( TSMath.Max(value1.x, value2.x), TSMath.Max(value1.y, value2.y)); } public static void Max(ref TSVector2 value1, ref TSVector2 value2, out TSVector2 result) { result.x = TSMath.Max(value1.x, value2.x); result.y = TSMath.Max(value1.y, value2.y); } public static TSVector2 Min(TSVector2 value1, TSVector2 value2) { return new TSVector2( TSMath.Min(value1.x, value2.x), TSMath.Min(value1.y, value2.y)); } public static void Min(ref TSVector2 value1, ref TSVector2 value2, out TSVector2 result) { result.x = TSMath.Min(value1.x, value2.x); result.y = TSMath.Min(value1.y, value2.y); } public void Scale(TSVector2 other) { this.x = x * other.x; this.y = y * other.y; } public static TSVector2 Scale(TSVector2 value1, TSVector2 value2) { TSVector2 result; result.x = value1.x * value2.x; result.y = value1.y * value2.y; return result; } public static TSVector2 Multiply(TSVector2 value1, TSVector2 value2) { value1.x *= value2.x; value1.y *= value2.y; return value1; } public static TSVector2 Multiply(TSVector2 value1, FP scaleFactor) { value1.x *= scaleFactor; value1.y *= scaleFactor; return value1; } public static void Multiply(ref TSVector2 value1, FP scaleFactor, out TSVector2 result) { result.x = value1.x*scaleFactor; result.y = value1.y*scaleFactor; } public static void Multiply(ref TSVector2 value1, ref TSVector2 value2, out TSVector2 result) { result.x = value1.x*value2.x; result.y = value1.y*value2.y; } public static TSVector2 Negate(TSVector2 value) { value.x = -value.x; value.y = -value.y; return value; } public static void Negate(ref TSVector2 value, out TSVector2 result) { result.x = -value.x; result.y = -value.y; } public void Normalize() { Normalize(ref this, out this); } public static TSVector2 Normalize(TSVector2 value) { Normalize(ref value, out value); return value; } public TSVector2 normalized { get { TSVector2 result; TSVector2.Normalize(ref this, out result); return result; } } public static void Normalize(ref TSVector2 value, out TSVector2 result) { FP factor; DistanceSquared(ref value, ref zeroVector, out factor); factor = 1f/(FP) FP.Sqrt(factor); result.x = value.x*factor; result.y = value.y*factor; } public static TSVector2 SmoothStep(TSVector2 value1, TSVector2 value2, FP amount) { return new TSVector2( TSMath.SmoothStep(value1.x, value2.x, amount), TSMath.SmoothStep(value1.y, value2.y, amount)); } public static void SmoothStep(ref TSVector2 value1, ref TSVector2 value2, FP amount, out TSVector2 result) { result = new TSVector2( TSMath.SmoothStep(value1.x, value2.x, amount), TSMath.SmoothStep(value1.y, value2.y, amount)); } public static TSVector2 Subtract(TSVector2 value1, TSVector2 value2) { value1.x -= value2.x; value1.y -= value2.y; return value1; } public static void Subtract(ref TSVector2 value1, ref TSVector2 value2, out TSVector2 result) { result.x = value1.x - value2.x; result.y = value1.y - value2.y; } public static FP Angle(TSVector2 a, TSVector2 b) { return FP.Acos(a.normalized * b.normalized) * FP.Rad2Deg; } public TSVector ToTSVector() { return new TSVector(this.x, this.y, 0); } public override string ToString() { return string.Format("({0:f1}, {1:f1})", x.AsFloat(), y.AsFloat()); } #endregion Public Methods #region Operators public static TSVector2 operator -(TSVector2 value) { value.x = -value.x; value.y = -value.y; return value; } public static bool operator ==(TSVector2 value1, TSVector2 value2) { return value1.x == value2.x && value1.y == value2.y; } public static bool operator !=(TSVector2 value1, TSVector2 value2) { return value1.x != value2.x || value1.y != value2.y; } public static TSVector2 operator +(TSVector2 value1, TSVector2 value2) { value1.x += value2.x; value1.y += value2.y; return value1; } public static TSVector2 operator -(TSVector2 value1, TSVector2 value2) { value1.x -= value2.x; value1.y -= value2.y; return value1; } public static FP operator *(TSVector2 value1, TSVector2 value2) { return TSVector2.Dot(value1, value2); } public static TSVector2 operator *(TSVector2 value, FP scaleFactor) { value.x *= scaleFactor; value.y *= scaleFactor; return value; } public static TSVector2 operator *(FP scaleFactor, TSVector2 value) { value.x *= scaleFactor; value.y *= scaleFactor; return value; } public static TSVector2 operator /(TSVector2 value1, TSVector2 value2) { value1.x /= value2.x; value1.y /= value2.y; return value1; } public static TSVector2 operator /(TSVector2 value1, FP divider) { FP factor = 1/divider; value1.x *= factor; value1.y *= factor; return value1; } #endregion Operators } }
ET/Unity/Assets/Scripts/ThirdParty/TrueSync/TSVector2.cs/0
{ "file_path": "ET/Unity/Assets/Scripts/ThirdParty/TrueSync/TSVector2.cs", "repo_id": "ET", "token_count": 8820 }
194
fileFormatVersion: 2 guid: 067516e3052a2af4eb641d1ffc59a8de DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
ET/Unity/Assets/Settings/IgnoreAsmdef/Model/Generate/Client/Ignore.asmdef.DISABLED.meta/0
{ "file_path": "ET/Unity/Assets/Settings/IgnoreAsmdef/Model/Generate/Client/Ignore.asmdef.DISABLED.meta", "repo_id": "ET", "token_count": 65 }
195
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!114 &11400000 MonoBehaviour: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 0} m_Enabled: 1 m_EditorHideFlags: 0 m_Script: {fileID: 11500000, guid: 2ec995e51a6e251468d2a3fd8a686257, type: 3} m_Name: UniversalRenderPipelineGlobalSettings m_EditorClassIdentifier: k_AssetVersion: 3 m_RenderingLayerNames: - Light Layer default - Light Layer 1 - Light Layer 2 - Light Layer 3 - Light Layer 4 - Light Layer 5 - Light Layer 6 - Light Layer 7 m_ValidRenderingLayers: 255 lightLayerName0: Light Layer default lightLayerName1: Light Layer 1 lightLayerName2: Light Layer 2 lightLayerName3: Light Layer 3 lightLayerName4: Light Layer 4 lightLayerName5: Light Layer 5 lightLayerName6: Light Layer 6 lightLayerName7: Light Layer 7 m_StripDebugVariants: 1 m_StripUnusedPostProcessingVariants: 0 m_StripUnusedVariants: 1 m_StripUnusedLODCrossFadeVariants: 1 m_StripScreenCoordOverrideVariants: 1 supportRuntimeDebugDisplay: 0 m_ShaderVariantLogLevel: 0 m_ExportShaderVariants: 1
ET/Unity/Assets/Settings/UniversalRenderPipelineGlobalSettings.asset/0
{ "file_path": "ET/Unity/Assets/Settings/UniversalRenderPipelineGlobalSettings.asset", "repo_id": "ET", "token_count": 443 }
196
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!1045 &1 EditorBuildSettings: m_ObjectHideFlags: 0 serializedVersion: 2 m_Scenes: - enabled: 1 path: Assets/Scenes/Init.unity guid: e0d691ac8c1d0454ba07089ea820e18a m_configObjects: com.unity.addressableassets: {fileID: 11400000, guid: f989b2ba24890344e858b377390e01f5, type: 2}
ET/Unity/ProjectSettings/EditorBuildSettings.asset/0
{ "file_path": "ET/Unity/ProjectSettings/EditorBuildSettings.asset", "repo_id": "ET", "token_count": 166 }
197
/* Copyright (c) 2015 Ki Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.TypeSystem; using Metadata = ICSharpCode.Decompiler.Metadata; namespace ICSharpCode.BamlDecompiler.Baml { internal class BamlContext { public IDecompilerTypeSystem TypeSystem { get; } public KnownThings KnownThings { get; } Dictionary<ushort, (string FullAssemblyName, IModule Assembly)> assemblyMap = new Dictionary<ushort, (string FullAssemblyName, IModule Assembly)>(); public Dictionary<ushort, AssemblyInfoRecord> AssemblyIdMap { get; } public Dictionary<ushort, AttributeInfoRecord> AttributeIdMap { get; } public Dictionary<ushort, StringInfoRecord> StringIdMap { get; } public Dictionary<ushort, TypeInfoRecord> TypeIdMap { get; } BamlContext(IDecompilerTypeSystem typeSystem) { this.TypeSystem = typeSystem; KnownThings = new KnownThings(typeSystem); AssemblyIdMap = new Dictionary<ushort, AssemblyInfoRecord>(); AttributeIdMap = new Dictionary<ushort, AttributeInfoRecord>(); StringIdMap = new Dictionary<ushort, StringInfoRecord>(); TypeIdMap = new Dictionary<ushort, TypeInfoRecord>(); } public static BamlContext ConstructContext(IDecompilerTypeSystem typeSystem, BamlDocument document, CancellationToken token) { var ctx = new BamlContext(typeSystem); foreach (var record in document) { token.ThrowIfCancellationRequested(); if (record is AssemblyInfoRecord assemblyInfo) { if (assemblyInfo.AssemblyId == ctx.AssemblyIdMap.Count) ctx.AssemblyIdMap.Add(assemblyInfo.AssemblyId, assemblyInfo); } else if (record is AttributeInfoRecord attrInfo) { if (attrInfo.AttributeId == ctx.AttributeIdMap.Count) ctx.AttributeIdMap.Add(attrInfo.AttributeId, attrInfo); } else if (record is StringInfoRecord strInfo) { if (strInfo.StringId == ctx.StringIdMap.Count) ctx.StringIdMap.Add(strInfo.StringId, strInfo); } else if (record is TypeInfoRecord typeInfo) { if (typeInfo.TypeId == ctx.TypeIdMap.Count) ctx.TypeIdMap.Add(typeInfo.TypeId, typeInfo); } } return ctx; } public (string FullAssemblyName, IModule Assembly) ResolveAssembly(ushort id) { id &= 0xfff; if (!assemblyMap.TryGetValue(id, out var assembly)) { if (AssemblyIdMap.TryGetValue(id, out var assemblyRec)) { var assemblyName = Metadata.AssemblyNameReference.Parse(assemblyRec.AssemblyFullName); if (assemblyName.Name == TypeSystem.MainModule.AssemblyName) { assembly = (assemblyRec.AssemblyFullName, TypeSystem.MainModule); } else { assembly = (assemblyRec.AssemblyFullName, FindMatchingReference(assemblyName)); } } else assembly = (null, null); assemblyMap[id] = assembly; } return assembly; } private IModule FindMatchingReference(AssemblyNameReference name) { IModule bestMatch = null; foreach (var module in TypeSystem.ReferencedModules) { if (module.AssemblyName == name.Name) { // using highest version as criterion if (bestMatch == null || bestMatch.AssemblyVersion <= module.AssemblyVersion) { bestMatch = module; } } } return bestMatch; } } }
ILSpy/ICSharpCode.BamlDecompiler/Baml/BamlContext.cs/0
{ "file_path": "ILSpy/ICSharpCode.BamlDecompiler/Baml/BamlContext.cs", "repo_id": "ILSpy", "token_count": 1509 }
198
/* Copyright (c) 2015 Ki Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Xml; using System.Xml.Linq; using ICSharpCode.Decompiler.TypeSystem; namespace ICSharpCode.BamlDecompiler.Xaml { internal class XamlType { /// <summary> /// Assembly that contains the type defintion. Can be null. /// </summary> public IModule Assembly { get; } public string FullAssemblyName { get; } public string TypeNamespace { get; } public string TypeName { get; } public XNamespace Namespace { get; private set; } public IType ResolvedType { get; set; } public XamlType(IModule assembly, string fullAssemblyName, string ns, string name) : this(assembly, fullAssemblyName, ns, name, null) { } public XamlType(IModule assembly, string fullAssemblyName, string ns, string name, XNamespace xmlns) { Assembly = assembly; FullAssemblyName = fullAssemblyName; TypeNamespace = ns; TypeName = name; Namespace = xmlns; } public void ResolveNamespace(XElement elem, XamlContext ctx) { if (Namespace != null) return; // Since XmlnsProperty records are inside the element, // the namespace is resolved after processing the element body. string xmlNs = null; if (elem.Annotation<XmlnsScope>() != null) xmlNs = elem.Annotation<XmlnsScope>().LookupXmlns(FullAssemblyName, TypeNamespace); if (xmlNs == null) xmlNs = ctx.XmlNs.LookupXmlns(FullAssemblyName, TypeNamespace); // Sometimes there's no reference to System.Xaml even if x:Type is used if (xmlNs == null) xmlNs = ctx.TryGetXmlNamespace(Assembly, TypeNamespace); if (xmlNs == null) { if (FullAssemblyName == ctx.TypeSystem.MainModule.FullAssemblyName) xmlNs = $"clr-namespace:{TypeNamespace}"; else { var name = ICSharpCode.Decompiler.Metadata.AssemblyNameReference.Parse(FullAssemblyName); xmlNs = $"clr-namespace:{TypeNamespace};assembly={name.Name}"; } var nsSeg = TypeNamespace.Split('.'); var prefix = nsSeg[nsSeg.Length - 1].ToLowerInvariant(); if (string.IsNullOrEmpty(prefix)) { if (string.IsNullOrEmpty(TypeNamespace)) prefix = "global"; else prefix = "empty"; } int count = 0; var truePrefix = prefix; XNamespace prefixNs, ns = ctx.GetXmlNamespace(xmlNs); while ((prefixNs = elem.GetNamespaceOfPrefix(truePrefix)) != null && prefixNs != ns) { count++; truePrefix = prefix + count; } if (prefixNs == null) { elem.Add(new XAttribute(XNamespace.Xmlns + XmlConvert.EncodeLocalName(truePrefix), ns)); if (string.IsNullOrEmpty(TypeNamespace)) elem.AddBeforeSelf(new XComment(string.Format("'{0}' is prefix for the global namespace", truePrefix))); } } Namespace = ctx.GetXmlNamespace(xmlNs); } public XName ToXName(XamlContext ctx) { if (Namespace == null) return XmlConvert.EncodeLocalName(TypeName); return Namespace + XmlConvert.EncodeLocalName(TypeName); } public override string ToString() => TypeName; } }
ILSpy/ICSharpCode.BamlDecompiler/Xaml/XamlType.cs/0
{ "file_path": "ILSpy/ICSharpCode.BamlDecompiler/Xaml/XamlType.cs", "repo_id": "ILSpy", "token_count": 1440 }
199
@{ # Script module or binary module file associated with this manifest. RootModule = 'ICSharpCode.Decompiler.PowerShell.dll' # Version number of this module. ModuleVersion = '8.0.0.0' # Supported PSEditions # CompatiblePSEditions = @() # ID used to uniquely identify this module GUID = '198b4312-cbe7-417e-81a7-1aaff467ef06' # Author of this module Author = 'ILSpy Contributors' # Company or vendor of this module CompanyName = 'ic#code' # Copyright statement for this module Copyright = 'Copyright 2011-2023 AlphaSierraPapa' # Description of the functionality provided by this module Description = 'PowerShell front-end for ILSpy' # Minimum version of the PowerShell engine required by this module # PowerShellVersion = '' # Name of the PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # ClrVersion = '' # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module # RequiredModules = @() # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = @() # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @( 'Get-DecompiledProject', 'Get-DecompiledSource', 'Get-DecompiledTypes', 'Get-Decompiler', 'Get-DecompilerVersion' ) # Variables to export from this module VariablesToExport = '*' # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = @() # DSC resources to export from this module # DscResourcesToExport = @() # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module # FileList = @() # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. # Tags = @() # A URL to the license for this module. # LicenseUri = '' # A URL to the main website for this project. ProjectUri = 'https://github.com/icsharpcode/ILSpy' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module # ReleaseNotes = '' # Prerelease string of this module # Prerelease = '' # Flag to indicate whether the module requires explicit user acceptance for install/update/save # RequireLicenseAcceptance = $false # External dependent modules of this module # ExternalModuleDependencies = @() } # End of PSData hashtable } # End of PrivateData hashtable # HelpInfo URI of this module # HelpInfoURI = '' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' }
ILSpy/ICSharpCode.Decompiler.PowerShell/manifest.psd1/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.PowerShell/manifest.psd1", "repo_id": "ILSpy", "token_count": 1261 }
200
using System; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; using System.Text; using System.Xml.Linq; using ICSharpCode.Decompiler.CSharp; using ICSharpCode.Decompiler.DebugInfo; using ICSharpCode.Decompiler.Metadata; using ICSharpCode.Decompiler.Tests.Helpers; using Microsoft.DiaSymReader.Tools; using NUnit.Framework; namespace ICSharpCode.Decompiler.Tests { [TestFixture, Parallelizable(ParallelScope.All)] public class PdbGenerationTestRunner { static readonly string TestCasePath = Tester.TestCasePath + "/PdbGen"; [Test] public void HelloWorld() { TestGeneratePdb(); } [Test] [Ignore("Missing nested local scopes for loops, differences in IL ranges")] public void ForLoopTests() { TestGeneratePdb(); } [Test] [Ignore("Differences in IL ranges")] public void LambdaCapturing() { TestGeneratePdb(); } [Test] [Ignore("Duplicate sequence points for local function")] public void Members() { TestGeneratePdb(); } [Test] public void CustomPdbId() { // Generate a PDB for an assembly using a randomly-generated ID, then validate that the PDB uses the specified ID (string peFileName, string pdbFileName) = CompileTestCase(nameof(CustomPdbId)); var moduleDefinition = new PEFile(peFileName); var resolver = new UniversalAssemblyResolver(peFileName, false, moduleDefinition.Metadata.DetectTargetFrameworkId(), null, PEStreamOptions.PrefetchEntireImage); var decompiler = new CSharpDecompiler(moduleDefinition, resolver, new DecompilerSettings()); var expectedPdbId = new BlobContentId(Guid.NewGuid(), (uint)Random.Shared.Next()); using (FileStream pdbStream = File.Open(Path.Combine(TestCasePath, nameof(CustomPdbId) + ".pdb"), FileMode.OpenOrCreate, FileAccess.ReadWrite)) { pdbStream.SetLength(0); PortablePdbWriter.WritePdb(moduleDefinition, decompiler, new DecompilerSettings(), pdbStream, noLogo: true, pdbId: expectedPdbId); pdbStream.Position = 0; var metadataReader = MetadataReaderProvider.FromPortablePdbStream(pdbStream).GetMetadataReader(); var generatedPdbId = new BlobContentId(metadataReader.DebugMetadataHeader.Id); Assert.That(generatedPdbId.Guid, Is.EqualTo(expectedPdbId.Guid)); Assert.That(generatedPdbId.Stamp, Is.EqualTo(expectedPdbId.Stamp)); } } [Test] public void ProgressReporting() { // Generate a PDB for an assembly and validate that the progress reporter is called with reasonable values (string peFileName, string pdbFileName) = CompileTestCase(nameof(ProgressReporting)); var moduleDefinition = new PEFile(peFileName); var resolver = new UniversalAssemblyResolver(peFileName, false, moduleDefinition.Metadata.DetectTargetFrameworkId(), null, PEStreamOptions.PrefetchEntireImage); var decompiler = new CSharpDecompiler(moduleDefinition, resolver, new DecompilerSettings()); var lastFilesWritten = 0; var totalFiles = -1; Action<DecompilationProgress> reportFunc = progress => { if (totalFiles == -1) { // Initialize value on first call totalFiles = progress.TotalUnits; } Assert.That(totalFiles, Is.EqualTo(progress.TotalUnits)); Assert.That(lastFilesWritten + 1, Is.EqualTo(progress.UnitsCompleted)); lastFilesWritten = progress.UnitsCompleted; }; using (FileStream pdbStream = File.Open(Path.Combine(TestCasePath, nameof(ProgressReporting) + ".pdb"), FileMode.OpenOrCreate, FileAccess.ReadWrite)) { pdbStream.SetLength(0); PortablePdbWriter.WritePdb(moduleDefinition, decompiler, new DecompilerSettings(), pdbStream, noLogo: true, progress: new TestProgressReporter(reportFunc)); pdbStream.Position = 0; var metadataReader = MetadataReaderProvider.FromPortablePdbStream(pdbStream).GetMetadataReader(); var generatedPdbId = new BlobContentId(metadataReader.DebugMetadataHeader.Id); } Assert.That(lastFilesWritten, Is.EqualTo(totalFiles)); } private class TestProgressReporter : IProgress<DecompilationProgress> { private Action<DecompilationProgress> reportFunc; public TestProgressReporter(Action<DecompilationProgress> reportFunc) { this.reportFunc = reportFunc; } public void Report(DecompilationProgress value) { reportFunc(value); } } private void TestGeneratePdb([CallerMemberName] string testName = null) { const PdbToXmlOptions options = PdbToXmlOptions.IncludeEmbeddedSources | PdbToXmlOptions.ThrowOnError | PdbToXmlOptions.IncludeTokens | PdbToXmlOptions.ResolveTokens | PdbToXmlOptions.IncludeMethodSpans; string xmlFile = Path.Combine(TestCasePath, testName + ".xml"); (string peFileName, string pdbFileName) = CompileTestCase(testName); var moduleDefinition = new PEFile(peFileName); var resolver = new UniversalAssemblyResolver(peFileName, false, moduleDefinition.Metadata.DetectTargetFrameworkId(), null, PEStreamOptions.PrefetchEntireImage); var decompiler = new CSharpDecompiler(moduleDefinition, resolver, new DecompilerSettings()); using (FileStream pdbStream = File.Open(Path.Combine(TestCasePath, testName + ".pdb"), FileMode.OpenOrCreate, FileAccess.ReadWrite)) { pdbStream.SetLength(0); PortablePdbWriter.WritePdb(moduleDefinition, decompiler, new DecompilerSettings(), pdbStream, noLogo: true); pdbStream.Position = 0; using (Stream peStream = File.OpenRead(peFileName)) using (Stream expectedPdbStream = File.OpenRead(pdbFileName)) { using (StreamWriter writer = new StreamWriter(Path.ChangeExtension(pdbFileName, ".xml"), false, Encoding.UTF8)) { PdbToXmlConverter.ToXml(writer, expectedPdbStream, peStream, options); } peStream.Position = 0; using (StreamWriter writer = new StreamWriter(Path.ChangeExtension(xmlFile, ".generated.xml"), false, Encoding.UTF8)) { PdbToXmlConverter.ToXml(writer, pdbStream, peStream, options); } } } string expectedFileName = Path.ChangeExtension(xmlFile, ".expected.xml"); ProcessXmlFile(expectedFileName); string generatedFileName = Path.ChangeExtension(xmlFile, ".generated.xml"); ProcessXmlFile(generatedFileName); CodeAssert.AreEqual(Normalize(expectedFileName), Normalize(generatedFileName)); } private (string peFileName, string pdbFileName) CompileTestCase(string testName) { string xmlFile = Path.Combine(TestCasePath, testName + ".xml"); string xmlContent = File.ReadAllText(xmlFile); XDocument document = XDocument.Parse(xmlContent); var files = document.Descendants("file").ToDictionary(f => f.Attribute("name").Value, f => f.Value); Tester.CompileCSharpWithPdb(Path.Combine(TestCasePath, testName + ".expected"), files); string peFileName = Path.Combine(TestCasePath, testName + ".expected.dll"); string pdbFileName = Path.Combine(TestCasePath, testName + ".expected.pdb"); return (peFileName, pdbFileName); } private void ProcessXmlFile(string fileName) { var document = XDocument.Load(fileName); foreach (var file in document.Descendants("file")) { file.Attribute("checksum").Remove(); file.Attribute("embeddedSourceLength")?.Remove(); file.ReplaceNodes(new XCData(file.Value.Replace("\uFEFF", ""))); } document.Save(fileName, SaveOptions.None); } private string Normalize(string inputFileName) { return File.ReadAllText(inputFileName).Replace("\r\n", "\n").Replace("\r", "\n"); } } class StringWriterWithEncoding : StringWriter { readonly Encoding encoding; public StringWriterWithEncoding(Encoding encoding) { this.encoding = encoding ?? throw new ArgumentNullException("encoding"); } public override Encoding Encoding => encoding; } }
ILSpy/ICSharpCode.Decompiler.Tests/PdbGenerationTestRunner.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/PdbGenerationTestRunner.cs", "repo_id": "ILSpy", "token_count": 2718 }
201
// Copyright (c) 2016 Daniel Grunwald // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "../../../ICSharpCode.Decompiler/Util/CSharpPrimitiveCast.cs" using System; using ICSharpCode.Decompiler.Util; namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness { public class Conversions { static readonly TypeCode[] targetTypes = { TypeCode.Char, TypeCode.SByte, TypeCode.Byte, TypeCode.Int16, TypeCode.UInt16, TypeCode.Int32, TypeCode.UInt32, TypeCode.Int64, TypeCode.UInt64, TypeCode.Single, TypeCode.Double, TypeCode.Decimal }; static object[] inputValues = { '\0', 'a', '\uFFFE', sbyte.MinValue, sbyte.MaxValue, (sbyte)-1, (sbyte)1, byte.MinValue, byte.MaxValue, (byte)1, short.MinValue, short.MaxValue, (short)-1, (short)1, ushort.MinValue, ushort.MaxValue, (ushort)1, int.MinValue, int.MaxValue, (int)-1, (int)1, uint.MinValue, uint.MaxValue, (uint)1, long.MinValue, long.MaxValue, (long)-1, (long)1, ulong.MinValue, ulong.MaxValue, (ulong)1, -1.1f, 1.1f, float.MinValue, float.MaxValue, float.NegativeInfinity, float.PositiveInfinity, float.NaN, -1.1, 1.1, double.MinValue, double.MaxValue, double.NegativeInfinity, double.PositiveInfinity, double.NaN, decimal.MinValue, decimal.MaxValue, decimal.MinusOne, decimal.One }; static void Main(string[] args) { RunTest(checkForOverflow: false); RunTest(checkForOverflow: true); Console.WriteLine(ReadZeroTerminatedString("Hello World!".Length)); C1.Test(); } static void RunTest(bool checkForOverflow) { string mode = checkForOverflow ? "checked" : "unchecked"; foreach (object input in inputValues) { string inputType = input.GetType().Name; foreach (var targetType in targetTypes) { try { object result = CSharpPrimitiveCast.Cast(targetType, input, checkForOverflow); Console.WriteLine("{0} ({1})({2}){3} = ({4}){5}", mode, targetType, inputType, input, result.GetType().Name, result); } catch (Exception ex) { Console.WriteLine("{0} ({1})({2}){3} = {4}", mode, targetType, inputType, input, ex.GetType().Name); } } } } static object MM(sbyte c) { checked { return (UInt64)c; } } static string ReadZeroTerminatedString(int length) { int read = 0; var buffer = new char[length]; var bytes = ReadBytes(length); while (read < length) { var current = bytes[read]; if (current == 0) break; buffer[read++] = (char)current; } return new string(buffer, 0, read); } static byte[] ReadBytes(int length) { return System.Text.Encoding.ASCII.GetBytes("Hello World!"); } } class C1 { public static implicit operator Type(C1 c) { return c.GetType(); } public static void Test() { Console.WriteLine("op_Implicit tests"); ExplicitUseOfImplicitConversion(new C1()); Console.WriteLine(ChainedImplicitConversions(new C2()).Name); } static void ExplicitUseOfImplicitConversion(C1 c) { Console.WriteLine(((Type)c).Name); } static Type ChainedImplicitConversions(C2 c) { return (C1)c; } } class C2 { public static implicit operator C1(C2 c) { return new C1(); } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/Conversions.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/Conversions.cs", "repo_id": "ILSpy", "token_count": 1815 }
202
// Copyright (c) 2016 Daniel Grunwald // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness { static class OverloadResolution { static void Main() { CallOverloadedMethod(); TestBoxing(); TestIssue180(); TestExtensionMethod(); TestParamsMethod(); Generics(); ConstructorTest(); TestIndexer(); Issue1281(); Issue1747(); CallAmbiguousOutParam(); CallWithInParam(); #if CS90 NativeIntTests(new IntPtr(1), 2); #endif Issue2444.M2(); Issue2741.B.Test(new Issue2741.C()); } #region ConstructorTest static void ConstructorTest() { new CtorTestObj(1); new CtorTestObj((short)2); new CtorTestObj(3, null); new CtorTestObj(4, null, null); } class CtorTestObj { public CtorTestObj(int i) { Console.WriteLine("CtorTestObj(int = " + i + ")"); } public CtorTestObj(short s) { Console.WriteLine("CtorTestObj(short = " + s + ")"); } public CtorTestObj(int i, object item1, object item2) : this(i, new object[] { item1, item2 }) { Console.WriteLine("CtorTestObj(int = " + i + ", item1 = " + item1 + ", item2 = " + item2); } public CtorTestObj(int i, params object[] items) { Console.WriteLine("CtorTestObj(int = " + i + ", items = " + (items == null ? "null" : items.Length.ToString()) + ")"); } } #endregion #region params with nulls static void TestParamsMethod() { TestCall(1, null, (NullReferenceException)null); TestCall(2, null, (AccessViolationException)null); TestCall(3, null); TestCall(3, null, null, null); } static void TestCall(int v, Type p1, NullReferenceException p2) { Console.WriteLine("TestCall without params"); } static void TestCall(int v, params AccessViolationException[] p2) { Console.WriteLine("TestCall with params: " + (p2 == null ? "null" : p2.Length.ToString())); } static void Issue1281() { var arg = new object[0]; TestCallIssue1281(arg); TestCallIssue1281((object)arg); TestCallIssue1281(new[] { arg }); } static void TestCallIssue1281(params object[] args) { Console.Write("TestCallIssue1281: count = " + args.Length + ": "); foreach (var arg in args) { Console.Write(arg); Console.Write(", "); } Console.WriteLine(); } #endregion #region Simple Overloaded Method static void CallOverloadedMethod() { OverloadedMethod("(string)"); OverloadedMethod((object)"(object)"); OverloadedMethod(5); OverloadedMethod((object)5); OverloadedMethod(5L); OverloadedMethod((object)null); OverloadedMethod((string)null); OverloadedMethod((int?)null); } static void OverloadedMethod(object a) { Console.WriteLine("OverloadedMethod(object={0}, object.GetType()={1})", a, a != null ? a.GetType().Name : "null"); } static void OverloadedMethod(int? a) { Console.WriteLine("OverloadedMethod(int?={0})", a); } static void OverloadedMethod(string a) { Console.WriteLine("OverloadedMethod(string={0})", a); } #endregion #region Boxing static void TestBoxing() { Print(1); Print((ushort)1); Print(null); } static void Print(object obj) { if (obj == null) Console.WriteLine("null"); else Console.WriteLine("{0}: {1}", obj.GetType().Name, obj); } #endregion #region #180 static void TestIssue180() { Issue180(null); Issue180(new object[1]); Issue180((object)new object[1]); } static void Issue180(object obj) { Console.WriteLine("#180: object"); } static void Issue180(params object[] objs) { Console.WriteLine("#180: params object[]"); } #endregion #region Extension Method static void TestExtensionMethod() { new object().ExtensionMethod(); ExtensionMethod(null); // issue #167 } public static void ExtensionMethod(this object obj) { Console.WriteLine("ExtensionMethod(obj)"); } #endregion #region Generics static void Generics() { GenericsTest<int>(null); GenericsTest<long>((object)null); } static void GenericsTest<T>(string x) where T : struct { Console.WriteLine("GenericsTest<" + typeof(T).Name + ">(string: " + x + ");"); } static void GenericsTest<T>(object x) where T : struct { Console.WriteLine("GenericsTest<" + typeof(T).Name + ">(object: " + x + ");"); } #endregion #region NullableValueTypes private static void Issue1747() { Console.WriteLine("Issue1747:"); M1747(null); M1747(true); M1747(false); M1747((bool?)true); M1747((bool?)false); Console.WriteLine("Issue1747, non-constant:"); bool b = Get<bool>(); M1747(b); M1747((bool?)b); } private static void M1747(bool b) { Console.WriteLine("bool=" + b); } private static void M1747(bool? b) { Console.WriteLine("bool?=" + b); } static T Get<T>() { return default(T); } #endregion #region IndexerTests static void TestIndexer() { var obj = new IndexerTests(); Console.WriteLine(obj[(object)5]); obj[(object)5] = null; Console.WriteLine(obj[5]); obj[5] = null; } #endregion #region Out Parameter static void AmbiguousOutParam(out string a) { a = null; Console.WriteLine("AmbiguousOutParam(out string)"); } static void AmbiguousOutParam(out int b) { b = 1; Console.WriteLine("AmbiguousOutParam(out int)"); } static void CallAmbiguousOutParam() { Console.WriteLine("CallAmbiguousOutParam:"); string a; int b; AmbiguousOutParam(out a); AmbiguousOutParam(out b); } #endregion #region In Parameter static void CallWithInParam() { #if CS72 Console.WriteLine("OverloadSetWithInParam:"); OverloadSetWithInParam(1); OverloadSetWithInParam(2L); int i = 3; OverloadSetWithInParam(in i); OverloadSetWithInParam((long)4); Console.WriteLine("OverloadSetWithInParam2:"); OverloadSetWithInParam2(1); OverloadSetWithInParam2((object)1); Console.WriteLine("OverloadSetWithInParam3:"); OverloadSetWithInParam3(1); OverloadSetWithInParam3<int>(2); OverloadSetWithInParam3((object)3); Console.WriteLine("InVsRegularParam:"); InVsRegularParam(1); i = 2; InVsRegularParam(in i); #endif } #if CS72 static void OverloadSetWithInParam(in int i) { Console.WriteLine("in int " + i); } static void OverloadSetWithInParam(long l) { Console.WriteLine("long " + l); } static void OverloadSetWithInParam2(in long i) { Console.WriteLine("in long " + i); } static void OverloadSetWithInParam2(object o) { Console.WriteLine("object " + o); } static void OverloadSetWithInParam3(in int i) { Console.WriteLine("in int " + i); } static void OverloadSetWithInParam3<T>(T a) { Console.WriteLine("T " + a); } static void InVsRegularParam(in int i) { Console.WriteLine("in int " + i); } static void InVsRegularParam(int i) { Console.WriteLine("int " + i); } #endif #endregion #if CS90 static void NativeIntTests(IntPtr i1, nint i2) { Console.WriteLine("NativeIntTests(i1):"); ObjectOrLong((object)i1); ObjectOrLong((long)i1); Console.WriteLine("NativeIntTests(i2):"); ObjectOrLong((object)i2); ObjectOrLong((long)i2); Console.WriteLine("NativeIntTests(new IntPtr):"); ObjectOrLong((object)new IntPtr(3)); ObjectOrLong((long)new IntPtr(3)); Console.WriteLine("NativeIntTests(IntPtr.Zero):"); ObjectOrLong((object)IntPtr.Zero); ObjectOrLong((long)IntPtr.Zero); } static void ObjectOrLong(object o) { Console.WriteLine("object " + o); } static void ObjectOrLong(long l) { Console.WriteLine("long " + l); } #endif #region #2444 public struct Issue2444 { public class X { } public class Y { } public static implicit operator Issue2444(X x) { Console.WriteLine("#2444: op_Implicit(X)"); return new Issue2444(); } public static implicit operator Issue2444(Y y) { Console.WriteLine("#2444: op_Implicit(Y)"); return new Issue2444(); } public static void M1(Issue2444 z) { Console.WriteLine(string.Format("#2444: M1({0})", z)); } public static void M2() { Console.WriteLine("#2444: before M1"); M1((X)null); Console.WriteLine("#2444: after M1"); } } public class Issue2741 { public class B { private void M() { Console.WriteLine("B::M"); } protected void M2() { Console.WriteLine("B::M2"); } protected void M3() { Console.WriteLine("B::M3"); } protected void M4() { Console.WriteLine("B::M4"); } public static void Test(C c) { ((B)c).M(); ((B)c).M2(); c.Test(); } } public class C : B { public void M() { Console.WriteLine("C::M"); } public new void M2() { Console.WriteLine("C::M2"); } public new void M3() { Console.WriteLine("C::M3"); } public void Test() { M3(); base.M3(); M4(); } } } #endregion } class IndexerTests { public object this[object key] { get { Console.WriteLine("IndexerTests.get_Item(object key)"); return new object(); } set { Console.WriteLine("IndexerTests.set_Item(object key, object value)"); } } public object this[int key] { get { Console.WriteLine("IndexerTests.get_Item(int key)"); return new object(); } set { Console.WriteLine("IndexerTests.set_Item(int key, object value)"); } } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/OverloadResolution.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/OverloadResolution.cs", "repo_id": "ILSpy", "token_count": 4377 }
203
using System; using System.Runtime.InteropServices; internal class EvalOrder { private SimpleStruct field; public static void Test(EvalOrder p) { // ldflda (and potential NRE) before MyStruct ctor call ref SimpleStruct reference = ref p.field; reference = new SimpleStruct(1); } } [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct SimpleStruct { public SimpleStruct(int val) { Console.WriteLine(val); } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/EvalOrder.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/EvalOrder.cs", "repo_id": "ILSpy", "token_count": 140 }
204
namespace ICSharpCode.Decompiler.Tests.TestCases.ILPretty { public class Issue1047 { private static bool dummy; private void ProblemMethod() { while (!dummy) { } } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1047.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1047.cs", "repo_id": "ILSpy", "token_count": 82 }
205
.assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly Issue1454 { .hash algorithm 0x00008004 .ver 1:0:4059:39717 } .module Issue1454.dll .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000003 // ILONLY 32BITREQUIRED .class public auto ansi beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue1454 extends [mscorlib]System.Object { .method public hidebysig static int32 GetCardinality ( class [mscorlib]System.Collections.BitArray bitArray ) cil managed { .maxstack 5 .locals init ( [0] int32[], [1] int32, [2] int32, [3] int32 ) IL_0000: ldarg.0 IL_0001: callvirt instance int32 [mscorlib]System.Collections.BitArray::get_Count() IL_0006: ldc.i4.5 IL_0007: shr IL_0008: ldc.i4.1 IL_0009: add IL_000a: newarr [mscorlib]System.Int32 IL_000f: stloc.0 IL_0010: ldarg.0 IL_0011: ldloc.0 IL_0012: ldc.i4.0 IL_0013: callvirt instance void [mscorlib]System.Collections.BitArray::CopyTo(class [mscorlib]System.Array, int32) IL_0018: ldc.i4.0 IL_0019: stloc.1 IL_001a: ldloc.0 IL_001b: ldloc.0 IL_001c: ldlen IL_001d: conv.i4 IL_001e: ldc.i4.1 IL_001f: sub IL_0020: ldelema [mscorlib]System.Int32 IL_0025: dup IL_0026: ldind.i4 IL_0027: ldc.i4.m1 IL_0028: ldarg.0 IL_0029: callvirt instance int32 [mscorlib]System.Collections.BitArray::get_Count() IL_002e: ldc.i4.s 32 IL_0030: rem IL_0031: ldc.i4.s 31 IL_0033: and IL_0034: shl IL_0035: not IL_0036: and IL_0037: stind.i4 IL_0038: ldc.i4.0 IL_0039: stloc.2 IL_003a: br.s IL_007b // loop start (head: IL_007b) IL_003c: ldloc.0 IL_003d: ldloc.2 IL_003e: ldelem.i4 IL_003f: stloc.3 IL_0040: ldloc.3 IL_0041: ldloc.3 IL_0042: ldc.i4.1 IL_0043: shr IL_0044: ldc.i4 1431655765 IL_0049: and IL_004a: sub IL_004b: stloc.3 IL_004c: ldloc.3 IL_004d: ldc.i4 858993459 IL_0052: and IL_0053: ldloc.3 IL_0054: ldc.i4.2 IL_0055: shr IL_0056: ldc.i4 858993459 IL_005b: and IL_005c: add IL_005d: stloc.3 IL_005e: ldloc.3 IL_005f: ldloc.3 IL_0060: ldc.i4.4 IL_0061: shr IL_0062: add IL_0063: ldc.i4 252645135 IL_0068: and IL_0069: ldc.i4 16843009 IL_006e: mul IL_006f: ldc.i4.s 24 IL_0071: shr IL_0072: stloc.3 IL_0073: ldloc.1 IL_0074: ldloc.3 IL_0075: add IL_0076: stloc.1 IL_0077: ldloc.2 IL_0078: ldc.i4.1 IL_0079: add IL_007a: stloc.2 IL_007b: ldloc.2 IL_007c: ldloc.0 IL_007d: ldlen IL_007e: conv.i4 IL_007f: blt.s IL_003c // end loop IL_0081: ldloc.1 IL_0082: ret } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1454.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1454.il", "repo_id": "ILSpy", "token_count": 1419 }
206
// Metadata version: v4.0.30319 .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly extern System { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly extern Microsoft.VisualBasic { .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) // .?_....: .ver 10:0:0:0 } .assembly ConsoleApp11 { .ver 1:0:0:0 } .module ConsoleApp11.exe // MVID: {B973FCD6-A9C4-48A9-8291-26DDC248E208} .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00020003 // ILONLY 32BITPREFERRED // Image base: 0x000001C4B6C90000 .class private auto ansi sealed ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue646 extends [mscorlib]System.Object { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = ( 01 00 00 00 ) // Methods .method public static void Main () cil managed { .custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 ) // Method begins at RVA 0x21b4 // Code size 61 (0x3d) .maxstack 1 .entrypoint .locals init ( [0] class [mscorlib]System.Collections.Generic.List`1<string>, [1] valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<string>, [2] string, [3] bool ) IL_0000: nop IL_0001: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor() IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: callvirt instance valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<!0> class [mscorlib]System.Collections.Generic.List`1<string>::GetEnumerator() IL_000d: stloc.1 IL_000e: br.s IL_0020 // loop start (head: IL_0020) IL_0010: ldloca.s 1 IL_0012: call instance !0 valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<string>::get_Current() IL_0017: stloc.2 IL_0018: ldloc.2 IL_0019: call void [System]System.Diagnostics.Debug::WriteLine(string) IL_001e: nop IL_001f: nop IL_0020: ldloca.s 1 IL_0022: call instance bool valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<string>::MoveNext() IL_0027: stloc.3 IL_0028: ldloc.3 IL_0029: brtrue.s IL_0010 // end loop IL_002b: leave.s IL_003c } // end .try finally { IL_002d: ldloca.s 1 IL_002f: constrained. valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<string> IL_0035: callvirt instance void [mscorlib]System.IDisposable::Dispose() IL_003a: nop IL_003b: endfinally } // end handler IL_003c: ret } // end of method Module1::Main } // end of class ConsoleApp11.Module1
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue646.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue646.il", "repo_id": "ILSpy", "token_count": 1278 }
207
// Metadata version: v4.0.30319 .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly BoolEnum { .ver 1:0:0:0 } .module BoolEnum.exe .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00020003 // ILONLY 32BITPREFERRED // Image base: 0x000001C4B6C90000 .class public auto ansi sealed TestEnum.BooleanEnum extends [mscorlib]System.Enum { .field public specialname rtspecialname bool value__ .field public static literal valuetype TestEnum.BooleanEnum Min = bool(false) .field public static literal valuetype TestEnum.BooleanEnum Zero = bool(false) .field public static literal valuetype TestEnum.BooleanEnum One = bool(true) .field public static literal valuetype TestEnum.BooleanEnum Max = uint8(255) } .class public auto ansi sealed TestEnum.NativeIntEnum extends [mscorlib]System.Enum { .field public specialname rtspecialname native int value__ .field public static literal valuetype TestEnum.NativeIntEnum Zero = int64(0) .field public static literal valuetype TestEnum.NativeIntEnum One = int64(1) .field public static literal valuetype TestEnum.NativeIntEnum FortyTwo = int64(42) } .class nested public auto ansi sealed TestEnum.EnumWithNestedClass extends [System.Runtime]System.Enum { // Nested Types .class nested public auto ansi beforefieldinit NestedClass extends [mscorlib]System.Object { // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x206c // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method TestEnum.NestedClass::.ctor } // end of class NestedClass // Fields .field public specialname rtspecialname int32 value__ .field public static literal valuetype TestEnum.EnumWithNestedClass Zero = int32(0) .field public static literal valuetype TestEnum.EnumWithNestedClass One = int32(1) } // end of class EnumWithNestedClass
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/WeirdEnums.il/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/WeirdEnums.il", "repo_id": "ILSpy", "token_count": 923 }
208
using System; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { internal class AutoProperties { #if CS110 public required int RequiredField; #endif public int A { get; } = 1; public int B { get; set; } = 2; public static int C { get; } = 3; public static int D { get; set; } = 4; public string value { get; set; } [Obsolete("Property")] #if CS70 [field: Obsolete("Field")] #endif public int PropertyWithAttributeOnBackingField { get; set; } public int issue1319 { get; } #if CS110 public required int RequiredProperty { get; set; } #endif public AutoProperties(int issue1319) { this.issue1319 = issue1319; #if CS110 RequiredProperty = 42; RequiredField = 42; #endif } } #if !NET70 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] internal sealed class RequiredMemberAttribute : Attribute { } #endif }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/AutoProperties.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/AutoProperties.cs", "repo_id": "ILSpy", "token_count": 348 }
209
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Threading; #if CS100 using System.Threading.Tasks; #endif namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty.DelegateConstruction { public static class DelegateConstruction { private class InstanceTests { public struct SomeData { public string Value; } private int x; public Action CaptureOfThis() { return delegate { CaptureOfThis(); }; } public Action CaptureOfThisAndParameter(int a) { return delegate { CaptureOfThisAndParameter(a); }; } public Action CaptureOfThisAndParameterInForEach(int a) { foreach (int item in Enumerable.Empty<int>()) { if (item > 0) { return delegate { CaptureOfThisAndParameter(item + a); }; } } return null; } public Action CaptureOfThisAndParameterInForEachWithItemCopy(int a) { foreach (int item in Enumerable.Empty<int>()) { int copyOfItem = item; if (item > 0) { return delegate { CaptureOfThisAndParameter(item + a + copyOfItem); }; } } return null; } public void LambdaInForLoop() { for (int i = 0; i < 100000; i++) { Bar(() => Foo()); } } public int Foo() { return 0; } public void Bar(Func<int> f) { } private void Bug955() { new Thread((ThreadStart)delegate { }); } public void Bug951(int amount) { DoAction(delegate { if (amount < 0) { amount = 0; } DoAction(delegate { NoOp(amount); }); }); } public void Bug951b() { int amount = Foo(); DoAction(delegate { if (amount < 0) { amount = 0; } DoAction(delegate { NoOp(amount); }); }); } public void Bug951c(SomeData data) { DoAction(delegate { DoAction(delegate { DoSomething(data.Value); }); }); } public Func<int, int> Issue2143() { return (int x) => this.x; } public Action<object> Bug971_DelegateWithoutParameterList() { return delegate { }; } private void DoAction(Action action) { } private void NoOp(int a) { } private void DoSomething(string text) { } } public interface IM3 { void M3(); } public class BaseClass : IM3 { protected virtual void M1() { } protected virtual void M2() { } public virtual void M3() { } public static void StaticMethod() { } } public class SubClass : BaseClass { protected override void M2() { } public new void M3() { } public void Test() { Noop("M1.base", base.M1); Noop("M1", M1); Noop("M2.base", base.M2); Noop("M2", M2); Noop("M3.base", base.M3); Noop("M3.base_virt", ((BaseClass)this).M3); Noop("M3.base_interface", ((IM3)this).M3); #if CS70 Noop("M3", this.M3); Noop("M3", M3); #if CS80 static void M3() #else void M3() #endif { } #else Noop("M3", M3); #endif } public void Test2() { Noop("M3.new", new BaseClass().M3); Noop("M3.new", new SubClass().M3); } private void Noop(string name, Action _) { } } public class GenericTest<TNonCaptured, TCaptured> { public Func<TCaptured> GetFunc(Func<TNonCaptured, TCaptured> f) { TCaptured captured = f(default(TNonCaptured)); return delegate { Console.WriteLine(captured.GetType().FullName); return captured; }; } public Func<TNonCaptured, TNonCapturedMP, TCaptured> GetFunc<TNonCapturedMP>(Func<TCaptured> f) { TCaptured captured = f(); return delegate (TNonCaptured a, TNonCapturedMP d) { Console.WriteLine(a.GetHashCode()); Console.WriteLine(captured.GetType().FullName); return captured; }; } } private delegate void GenericDelegate<T>(); public delegate void RefRecursiveDelegate(ref RefRecursiveDelegate d); public static Func<string, string, bool> test0 = (string a, string b) => string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b); public static Func<string, string, bool> test1 = (string a, string b) => string.IsNullOrEmpty(a) || !string.IsNullOrEmpty(b); public static Func<string, string, bool> test2 = (string a, string b) => !string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b); public static Func<string, string, bool> test3 = (string a, string b) => !string.IsNullOrEmpty(a) || !string.IsNullOrEmpty(b); public static Func<string, string, bool> test4 = (string a, string b) => string.IsNullOrEmpty(a) && string.IsNullOrEmpty(b); public static Func<string, string, bool> test5 = (string a, string b) => string.IsNullOrEmpty(a) && !string.IsNullOrEmpty(b); public static Func<string, string, bool> test6 = (string a, string b) => !string.IsNullOrEmpty(a) && string.IsNullOrEmpty(b); public static Func<string, string, bool> test7 = (string a, string b) => !string.IsNullOrEmpty(a) && !string.IsNullOrEmpty(b); public static void Test(this string a) { } public static Predicate<T> And<T>(this Predicate<T> filter1, Predicate<T> filter2) { if (filter1 == null) { return filter2; } if (filter2 == null) { return filter1; } return (T m) => filter1(m) && filter2(m); } public static Action<string> ExtensionMethodUnbound() { return Test; } public static Action ExtensionMethodBound() { return "abc".Test; } public static Action ExtensionMethodBoundOnNull() { return ((string)null).Test; } public static Predicate<int> NoExtensionMethodOnLambda() { return And((int x) => x >= 0, (int x) => x <= 100); } public static object StaticMethod() { return new Func<Action>(ExtensionMethodBound); } public static object InstanceMethod() { return new Func<string>("hello".ToUpper); } public static object InstanceMethodOnNull() { return new Func<string>(((string)null).ToUpper); } public static List<Action<int>> AnonymousMethodStoreWithinLoop() { List<Action<int>> list = new List<Action<int>>(); for (int i = 0; i < 10; i++) { int counter; list.Add(delegate (int x) { counter = x; }); } return list; } public static List<Action<int>> AnonymousMethodStoreOutsideLoop() { List<Action<int>> list = new List<Action<int>>(); int counter; for (int i = 0; i < 10; i++) { list.Add(delegate (int x) { counter = x; }); } return list; } public static Action StaticAnonymousMethodNoClosure() { return delegate { Console.WriteLine(); }; } public static void NameConflict() { // i is captured variable, // j is parameter in anonymous method // l is local in anonymous method, // k is local in main method // Ensure that the decompiler doesn't introduce name conflicts List<Action<int>> list = new List<Action<int>>(); for (int k = 0; k < 10; k++) { int i; for (i = 0; i < 10; i++) { list.Add(delegate (int j) { for (int l = 0; l < i; l += j) { Console.WriteLine(); } }); } } } public static void NameConflict2(int j) { List<Action<int>> list = new List<Action<int>>(); for (int k = 0; k < 10; k++) { list.Add(delegate (int i) { Console.WriteLine(i); }); } } public static Action<int> NameConflict3(int i) { return delegate (int j) { for (int k = 0; k < j; k++) { Console.WriteLine(k); } }; } public static Func<int, Func<int, int>> CurriedAddition(int a) { return (int b) => (int c) => a + b + c; } public static Func<int, Func<int, Func<int, int>>> CurriedAddition2(int a) { return (int b) => (int c) => (int d) => a + b + c + d; } public static Func<TCaptured> CapturedTypeParameter1<TNonCaptured, TCaptured>(TNonCaptured a, Func<TNonCaptured, TCaptured> f) { TCaptured captured = f(a); return delegate { Console.WriteLine(captured.GetType().FullName); return captured; }; } public static Func<TCaptured> CapturedTypeParameter2<TNonCaptured, TCaptured>(TNonCaptured a, Func<TNonCaptured, List<TCaptured>> f) { List<TCaptured> captured = f(a); return delegate { Console.WriteLine(captured.GetType().FullName); return captured.FirstOrDefault(); }; } public static Func<int> Issue1773(short data) { int integerData = data; return () => integerData; } #if !MCS // does not compile with mcs... public static Func<int> Issue1773b(object data) { #if ROSLYN dynamic dynamicData = data; return () => dynamicData.DynamicCall(); #else // This is a bug in the old csc: captured dynamic local variables did not have the [DynamicAttribute] // on the display-class field. return () => ((dynamic)data).DynamicCall(); #endif } public static Func<int> Issue1773c(object data) { #if ROSLYN dynamic dynamicData = data; return () => dynamicData; #else return () => (dynamic)data; #endif } #endif #if CS70 public static Func<string> Issue1773d((int Integer, string String) data) { (int Integer, string RenamedString) valueTuple = data; return () => valueTuple.RenamedString; } #endif public static Func<T, T> Identity<T>() { return (T _) => _; } private static void Use(Action a) { } private static void Use2(Func<Func<int, int>, IEnumerable<int>> a) { } private static void Use2<T>(GenericDelegate<T> a) { } private static void Use3<T>(Func<Func<T, T>> a) { } public static void SimpleDelegateReference() { Use(SimpleDelegateReference); #if !MCS2 Use3(Identity<int>); #endif } public static void DelegateReferenceWithStaticTarget() { Use(NameConflict); Use(BaseClass.StaticMethod); } public static void ExtensionDelegateReference(IEnumerable<int> ints) { Use2(ints.Select<int, int>); } #if CS70 public static void LocalFunctionDelegateReference() { Use(LocalFunction); Use2<int>(LocalFunction1<int>); #if CS80 static void LocalFunction() #else void LocalFunction() #endif { } #if CS80 static void LocalFunction1<T>() #else void LocalFunction1<T>() #endif { } } #endif #if CS90 public static Func<int, int, int, int> LambdaParameterDiscard() { return (int _, int _, int _) => 0; } #endif #if CS100 public static Func<int> LambdaWithAttribute0() { return [My] () => 0; } public static Func<int, int> LambdaWithAttribute1() { return [My] (int x) => 0; } public static Func<int, int> LambdaWithAttributeOnParam() { return ([My] int x) => 0; } public static Func<Task<int>> AsyncLambdaWithAttribute0() { return [My] async () => 0; } public static Action StatementLambdaWithAttribute0() { return [My] () => { }; } public static Action<int> StatementLambdaWithAttribute1() { return [return: My] (int x) => { Console.WriteLine(x); }; } public static Action<int> StatementLambdaWithAttribute2() { return ([My] int x) => { Console.WriteLine(x); }; } #endif public static void CallRecursiveDelegate(ref RefRecursiveDelegate d) { d(ref d); } } public class Issue1867 { private int value; public Func<bool> TestLambda(Issue1867 x) { Issue1867 m1; Issue1867 m2; if (x.value > value) { m1 = this; m2 = x; } else { m1 = x; m2 = this; } return () => m1.value + 1 == 4 && m2.value > 5; } } internal class Issue2791 { public void M() { Run(delegate (object o) { try { List<int> list = o as List<int>; Action action = delegate { list.Select((int x) => x * 2); }; #if OPT && ROSLYN Action obj = delegate { #else Action action2 = delegate { #endif list.Select((int x) => x * 2); }; Console.WriteLine(); action(); Console.WriteLine(); #if OPT && ROSLYN obj(); #else action2(); #endif } catch (Exception) { Console.WriteLine("catch"); } finally { Console.WriteLine("finally"); } }, null); } private void Run(ParameterizedThreadStart del, object x) { del(x); } } [AttributeUsage(AttributeTargets.All)] internal class MyAttribute : Attribute { } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/DelegateConstruction.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/DelegateConstruction.cs", "repo_id": "ILSpy", "token_count": 5721 }
210
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Runtime.InteropServices; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { public static class T00_LiftedOperators { // C# uses 4 different patterns of IL for lifted operators: bool, other primitive types, decimal, other structs. // Different patterns are used depending on whether both of the operands are nullable or only the left/right operand is nullable. // Negation must not be pushed through such comparisons because it would change the semantics (except for equality/inequality). // A comparison used in a condition differs somewhat from a comparison used as a simple value. public static void BoolBasic(bool? a, bool? b) { if (a == b) { Console.WriteLine(); } if (a != b) { Console.WriteLine(); } } public static void BoolComplex(bool? a, Func<bool> x) { if (a == x()) { Console.WriteLine(); } if (a != x()) { Console.WriteLine(); } if (x() == a) { Console.WriteLine(); } if (x() != a) { Console.WriteLine(); } if (a ?? x()) { Console.WriteLine(); } } public static void BoolConst(bool? a) { if (a == true) { Console.WriteLine(); } if (a != true) { Console.WriteLine(); } if (a == false) { Console.WriteLine(); } if (a != false) { Console.WriteLine(); } if (a ?? true) { Console.WriteLine(); } #if !ROSLYN // Roslyn 3 (VS2019) started optimizing this to "a.GetValueOrDefault()" if (a ?? false) { Console.WriteLine(); } #endif } public static void BoolValueBasic(bool? a, bool? b) { Console.WriteLine(a == b); Console.WriteLine(a != b); Console.WriteLine(a & b); Console.WriteLine(a | b); Console.WriteLine(a ^ b); Console.WriteLine(a ?? b); Console.WriteLine(!a); a &= b; a |= b; a ^= b; } public static void BoolValueComplex(bool? a, Func<bool> x) { Console.WriteLine(a == x()); Console.WriteLine(a != x()); Console.WriteLine(x() == a); Console.WriteLine(x() != a); //Console.WriteLine(a & x()); // we currently can't tell the order //Console.WriteLine(a | x()); // of the operands in bool [&|] bool? Console.WriteLine(a ^ x()); Console.WriteLine(a ?? x()); //a &= x(); -- also affected by order of operand problem //a |= x(); a ^= x(); Console.WriteLine(x() & a); Console.WriteLine(x() | a); Console.WriteLine(x() ^ a); (new bool?[0])[0] ^= x(); (new bool?[0])[0] ^= a; } public static void BoolValueConst(bool? a) { Console.WriteLine(a == true); Console.WriteLine(a != true); Console.WriteLine(a == false); Console.WriteLine(a != false); Console.WriteLine(a ?? true); #if !ROSLYN // Roslyn 3 (VS2019) started optimizing this to "a.GetValueOrDefault()" Console.WriteLine(a ?? false); #endif } public static void IntBasic(int? a, int? b) { if (a == b) { Console.WriteLine(); } if (a != b) { Console.WriteLine(); } if (a > b) { Console.WriteLine(); } if (a < b) { Console.WriteLine(); } if (a >= b) { Console.WriteLine(); } if (a <= b) { Console.WriteLine(); } if (!(a > b)) { Console.WriteLine(); } if (!(a <= b)) { Console.WriteLine(); } } public static void IntComplex(int? a, Func<int> x) { if (a == x()) { Console.WriteLine(); } if (a != x()) { Console.WriteLine(); } if (a > x()) { Console.WriteLine(); } if (x() == a) { Console.WriteLine(); } if (x() != a) { Console.WriteLine(); } if (x() > a) { Console.WriteLine(); } if (!(a > x())) { Console.WriteLine(); } if (!(a <= x())) { Console.WriteLine(); } } public static void IntConst(int? a) { if (a == 2) { Console.WriteLine(); } if (a != 2) { Console.WriteLine(); } if (a > 2) { Console.WriteLine(); } if (2 == a) { Console.WriteLine(); } if (2 != a) { Console.WriteLine(); } if (2 > a) { Console.WriteLine(); } } public static void IntValueBasic(int? a, int? b) { Console.WriteLine(a == b); Console.WriteLine(a != b); Console.WriteLine(a > b); Console.WriteLine(!(a > b)); Console.WriteLine(!(a >= b)); Console.WriteLine(a + b); Console.WriteLine(a - b); Console.WriteLine(a * b); Console.WriteLine(a / b); Console.WriteLine(a % b); Console.WriteLine(a & b); Console.WriteLine(a | b); Console.WriteLine(a ^ b); Console.WriteLine(a << b); Console.WriteLine(a >> b); Console.WriteLine(a ?? b); Console.WriteLine(-a); Console.WriteLine(~a); // TODO: //Console.WriteLine(a++); //Console.WriteLine(a--); Console.WriteLine(++a); Console.WriteLine(--a); a += b; a -= b; a *= b; a /= b; a %= b; a &= b; a |= b; a ^= b; a <<= b; a >>= b; } public static void IntValueComplex(int? a, Func<int> x) { Console.WriteLine(a == x()); Console.WriteLine(a != x()); Console.WriteLine(a > x()); Console.WriteLine(x() == a); Console.WriteLine(x() != a); Console.WriteLine(x() > a); Console.WriteLine(a + x()); Console.WriteLine(a - x()); Console.WriteLine(a * x()); Console.WriteLine(a / x()); Console.WriteLine(a % x()); Console.WriteLine(a & x()); Console.WriteLine(a | x()); Console.WriteLine(a ^ x()); Console.WriteLine(a << x()); Console.WriteLine(a >> x()); Console.WriteLine(a ?? x()); a += x(); a -= x(); a *= x(); a /= x(); a %= x(); a &= x(); a |= x(); a ^= x(); a <<= x(); a >>= x(); Console.WriteLine(x() + a); (new int?[0])[0] += x(); } public static void IntValueConst(int? a) { Console.WriteLine(a == 2); Console.WriteLine(a != 2); Console.WriteLine(a > 2); Console.WriteLine(2 == a); Console.WriteLine(2 != a); Console.WriteLine(2 > a); Console.WriteLine(a + 2); Console.WriteLine(a - 2); Console.WriteLine(a * 2); Console.WriteLine(a / 2); Console.WriteLine(a % 2); Console.WriteLine(a & 2); Console.WriteLine(a | 2); Console.WriteLine(a ^ 2); Console.WriteLine(a << 2); Console.WriteLine(a >> 2); Console.WriteLine(a ?? 2); a += 2; a -= 2; a *= 2; a /= 2; a %= 2; a &= 2; a |= 2; a ^= 2; a <<= 2; a >>= 2; Console.WriteLine(2 + a); } public static void NumberBasic(decimal? a, decimal? b) { if (a == b) { Console.WriteLine(); } #if ROSLYN2 // Roslyn 2.9 started invoking op_Equality even if the source code says 'a != b' if (!(a == b)) { Console.WriteLine(); } #else if (a != b) { Console.WriteLine(); } #endif if (a > b) { Console.WriteLine(); } if (a < b) { Console.WriteLine(); } if (a >= b) { Console.WriteLine(); } if (a <= b) { Console.WriteLine(); } if (!(a > b)) { Console.WriteLine(); } if (!(a < b)) { Console.WriteLine(); } } public static void NumberComplex(decimal? a, Func<decimal> x) { // Tests deactivated because we insert redundant casts; // TODO: revisit after decision has been made regarding the type system. //if (a == x()) { // Console.WriteLine(); //} //if (a != x()) { // Console.WriteLine(); //} //if (a > x()) { // Console.WriteLine(); //} //if (x() == a) { // Console.WriteLine(); //} //if (x() != a) { // Console.WriteLine(); //} //if (x() > a) { // Console.WriteLine(); //} } public static void NumberConst(decimal? a) { // Tests deactivated because we insert redundant casts; // TODO: revisit after decision has been made regarding the type system. //if (a == 2m) { // Console.WriteLine(); //} //if (a != 2m) { // Console.WriteLine(); //} //if (a > 2m) { // Console.WriteLine(); //} //if (2m == a) { // Console.WriteLine(); //} //if (2m != a) { // Console.WriteLine(); //} //if (2m > a) { // Console.WriteLine(); //} } public static void NumberValueBasic(decimal? a, decimal? b) { Console.WriteLine(a == b); #if ROSLYN // Roslyn 2.9 started invoking op_Equality even if the source code says 'a != b' Console.WriteLine(!(a == b)); #else Console.WriteLine(a != b); #endif Console.WriteLine(a > b); Console.WriteLine(!(a > b)); Console.WriteLine(!(a <= b)); Console.WriteLine(a + b); Console.WriteLine(a - b); Console.WriteLine(a * b); Console.WriteLine(a / b); Console.WriteLine(a % b); Console.WriteLine(a ?? b); Console.WriteLine(-a); // TODO: //Console.WriteLine(a++); //Console.WriteLine(a--); //Console.WriteLine(++a); //Console.WriteLine(--a); a += b; a -= b; a *= b; a /= b; a %= b; } public static void NumberValueComplex(decimal? a, Func<decimal> x) { // Tests deactivated because we insert redundant casts; // TODO: revisit after decision has been made regarding the type system. //Console.WriteLine(a == x()); //Console.WriteLine(a != x()); //Console.WriteLine(a > x()); //Console.WriteLine(x() == a); //Console.WriteLine(x() != a); //Console.WriteLine(x() > a); //Console.WriteLine(a + x()); //Console.WriteLine(a - x()); //Console.WriteLine(a * x()); //Console.WriteLine(a / x()); //Console.WriteLine(a % x()); //Console.WriteLine(a ?? x()); //a += x(); //a -= x(); //a *= x(); //a /= x(); //a %= x(); //Console.WriteLine(x() + a); //(new decimal?[0])[0] += x(); } public static void NumberValueConst(decimal? a) { // Tests deactivated because we insert redundant casts; // TODO: revisit after decision has been made regarding the type system. //Console.WriteLine(a == 2m); //Console.WriteLine(a != 2m); //Console.WriteLine(a > 2m); //Console.WriteLine(2m == a); //Console.WriteLine(2m != a); //Console.WriteLine(2m > a); //Console.WriteLine(a + 2m); //Console.WriteLine(a - 2m); //Console.WriteLine(a * 2m); //Console.WriteLine(a / 2m); //Console.WriteLine(a % 2m); //Console.WriteLine(a ?? 2m); //a += 2m; //a -= 2m; //a *= 2m; //a /= 2m; //a %= 2m; //Console.WriteLine(2m + a); } public static void CompareWithImplictCast(int? a, long? b) { if (a < b) { Console.WriteLine(); } if (a == b) { Console.WriteLine(); } // TODO: unnecessary cast //if (a < 10L) { // Console.WriteLine(); //} //if (a == 10L) { // Console.WriteLine(); //} } public static void CompareWithSignChange(int? a, int? b) { if ((uint?)a < (uint?)b) { Console.WriteLine(); } // TODO: unnecessary cast //if ((uint?)a < 10) { // Console.WriteLine(); //} } public static void StructBasic(TS? a, TS? b) { if (a == b) { Console.WriteLine(); } if (a != b) { Console.WriteLine(); } if (a > b) { Console.WriteLine(); } if (a < b) { Console.WriteLine(); } if (a >= b) { Console.WriteLine(); } if (a <= b) { Console.WriteLine(); } if (!(a == b)) { Console.WriteLine(); } if (!(a != b)) { Console.WriteLine(); } if (!(a > b)) { Console.WriteLine(); } } public static void StructComplex(TS? a, Func<TS> x) { // Tests deactivated because we insert redundant casts; // TODO: revisit after decision has been made regarding the type system. //if (a == x()) { // Console.WriteLine(); //} //if (a != x()) { // Console.WriteLine(); //} //if (a > x()) { // Console.WriteLine(); //} //if (x() == a) { // Console.WriteLine(); //} //if (x() != a) { // Console.WriteLine(); //} //if (x() > a) { // Console.WriteLine(); //} } public static void StructValueBasic(TS? a, TS? b, int? i) { Console.WriteLine(a == b); Console.WriteLine(a != b); Console.WriteLine(a > b); Console.WriteLine(!(a == b)); Console.WriteLine(!(a != b)); Console.WriteLine(!(a > b)); Console.WriteLine(a + b); Console.WriteLine(a - b); Console.WriteLine(a * b); Console.WriteLine(a / b); Console.WriteLine(a % b); Console.WriteLine(a & b); Console.WriteLine(a | b); Console.WriteLine(a ^ b); Console.WriteLine(a << i); Console.WriteLine(a >> i); Console.WriteLine(a ?? b); Console.WriteLine(+a); Console.WriteLine(-a); Console.WriteLine(!a); Console.WriteLine(~a); // TODO: //Console.WriteLine(a++); //Console.WriteLine(a--); //Console.WriteLine(++a); //Console.WriteLine(--a); //Console.WriteLine((int?)a); a += b; a -= b; a *= b; a /= b; a %= b; a &= b; a |= b; a ^= b; a <<= i; a >>= i; } public static void StructValueComplex(TS? a, Func<TS> x, Func<int> i) { // Tests deactivated because we insert redundant casts; // TODO: revisit after decision has been made regarding the type system. //Console.WriteLine(a == x()); //Console.WriteLine(a != x()); //Console.WriteLine(a > x()); //Console.WriteLine(x() == a); //Console.WriteLine(x() != a); //Console.WriteLine(x() > a); //Console.WriteLine(a + x()); //Console.WriteLine(a - x()); //Console.WriteLine(a * x()); //Console.WriteLine(a / x()); //Console.WriteLine(a % x()); //Console.WriteLine(a & x()); //Console.WriteLine(a | x()); //Console.WriteLine(a ^ x()); //Console.WriteLine(a << i()); //Console.WriteLine(a >> i()); //Console.WriteLine(a ?? x()); //a += x(); //a -= x(); //a *= x(); //a /= x(); //a %= x(); //a &= x(); //a |= x(); //a ^= x(); //a <<= i(); //a >>= i(); //Console.WriteLine(x() + a); //(new TS?[0])[0] += x(); } public static bool RetEq(int? a, int? b) { return a == b; } public static bool RetEqConv(long? a, int? b) { return a == b; } public static bool RetEqConst(long? a) { return a == 10; } public static bool RetIneqConst(long? a) { return a != 10; } public static bool RetLt(int? a, int? b) { return a < b; } public static bool RetLtConst(int? a) { return a < 10; } public static bool RetLtConv(long? a, int? b) { return a < b; } public static bool RetNotLt(int? a, int? b) { return !(a < b); } } internal class T01_LiftedImplicitConversions { public int? ExtendI4(byte? b) { return b; } public int? ExtendToI4(sbyte? b) { return b; } public long? ExtendI8(byte? b) { return b; } public long? ExtendToI8(sbyte? b) { return b; } public long? ExtendI8(int? b) { return b; } public long? ExtendToI8(uint? b) { return b; } // TODO: unnecessary cast //public double? ToFloat(int? b) //{ // return b; //} //public long? InArithmetic(uint? b) //{ // return 100L + b; //} public long? AfterArithmetic(uint? b) { return 100 + b; } // TODO: unnecessary cast //public static double? InArithmetic2(float? nf, double? nd, float f) //{ // return nf + nd + f; //} public static long? InArithmetic3(int? a, long? b, int? c, long d) { return a + b + c + d; } } internal class T02_LiftedExplicitConversions { private static void Print<T>(T? x) where T : struct { Console.WriteLine(x); } public static void UncheckedCasts(int? i4, long? i8, float? f) { Print((byte?)i4); Print((short?)i4); Print((uint?)i4); Print((uint?)i8); Print((uint?)f); } public static void CheckedCasts(int? i4, long? i8, float? f) { checked { Print((byte?)i4); Print((short?)i4); Print((uint?)i4); Print((uint?)i8); //Print((uint?)f); TODO } } } internal class T03_NullCoalescingTests { private static void Print<T>(T x) { Console.WriteLine(x); } public static void Objects(object a, object b) { Print(a ?? b); } public static void Nullables(int? a, int? b) { Print(a ?? b); } public static void NullableWithNonNullableFallback(int? a, int b) { Print(a ?? b); } public static void NullableWithImplicitConversion(short? a, int? b) { Print(a ?? b); } public static void NullableWithImplicitConversionAndNonNullableFallback(short? a, int b) { // TODO: unnecessary cast //Print(a ?? b); } public static void Chain(int? a, int? b, int? c, int d) { Print(a ?? b ?? c ?? d); } public static void ChainWithImplicitConversions(int? a, short? b, long? c, byte d) { // TODO: unnecessary casts //Print(a ?? b ?? c ?? d); } public static void ChainWithComputation(int? a, short? b, long? c, byte d) { // TODO: unnecessary casts //Print((a + 1) ?? (b + 2) ?? (c + 3) ?? (d + 4)); } public static object ReturnObjects(object a, object b) { return a ?? b; } public static int? ReturnNullables(int? a, int? b) { return a ?? b; } public static int ReturnNullableWithNonNullableFallback(int? a, int b) { return a ?? b; } public static int ReturnChain(int? a, int? b, int? c, int d) { return a ?? b ?? c ?? d; } public static long ReturnChainWithImplicitConversions(int? a, short? b, long? c, byte d) { //TODO: unnecessary casts //return a ?? b ?? c ?? d; return 0L; } public static long ReturnChainWithComputation(int? a, short? b, long? c, byte d) { //TODO: unnecessary casts //return (a + 1) ?? (b + 2) ?? (c + 3) ?? (d + 4); return 0L; } } // dummy structure for testing custom operators [StructLayout(LayoutKind.Sequential, Size = 1)] public struct TS { // unary public static TS operator +(TS a) { throw null; } public static TS operator -(TS a) { throw null; } public static TS operator !(TS a) { throw null; } public static TS operator ~(TS a) { throw null; } public static TS operator ++(TS a) { throw null; } public static TS operator --(TS a) { throw null; } public static explicit operator int(TS a) { throw null; } // binary public static TS operator +(TS a, TS b) { throw null; } public static TS operator -(TS a, TS b) { throw null; } public static TS operator *(TS a, TS b) { throw null; } public static TS operator /(TS a, TS b) { throw null; } public static TS operator %(TS a, TS b) { throw null; } public static TS operator &(TS a, TS b) { throw null; } public static TS operator |(TS a, TS b) { throw null; } public static TS operator ^(TS a, TS b) { throw null; } public static TS operator <<(TS a, int b) { throw null; } public static TS operator >>(TS a, int b) { throw null; } // comparisons public static bool operator ==(TS a, TS b) { throw null; } public static bool operator !=(TS a, TS b) { throw null; } public static bool operator <(TS a, TS b) { throw null; } public static bool operator <=(TS a, TS b) { throw null; } public static bool operator >(TS a, TS b) { throw null; } public static bool operator >=(TS a, TS b) { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/LiftedOperators.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/LiftedOperators.cs", "repo_id": "ILSpy", "token_count": 9324 }
211
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Text; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { internal class PropertiesAndEvents { private interface IBase { int GetterOnly { get; } int SetterOnly { set; } int Test { get; set; } event Action Event; } private abstract class BaseClass { public abstract event EventHandler ThisIsAnAbstractEvent; } private class OtherClass : BaseClass { public override event EventHandler ThisIsAnAbstractEvent; } private class ExplicitImpl : IBase { int IBase.Test { get { throw new NotImplementedException(); } set { } } int IBase.GetterOnly { get { throw new NotImplementedException(); } } int IBase.SetterOnly { set { throw new NotImplementedException(); } } event Action IBase.Event { add { } remove { } } } private class Impl : IBase { public int GetterOnly { get { throw new NotImplementedException(); } } public int SetterOnly { set { throw new NotImplementedException(); } } public int Test { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public event Action Event; } private interface IChange { int Property { get; set; } event EventHandler Changed; } private class Change : IChange { private EventHandler Changed; int IChange.Property { get; set; } event EventHandler IChange.Changed { add { Changed = (EventHandler)Delegate.Combine(Changed, value); } remove { Changed = (EventHandler)Delegate.Remove(Changed, value); } } } [NonSerialized] private int someField; private object issue1221; public int Value { get; private set; } public int AutomaticProperty { get; set; } public int CustomProperty { get { return AutomaticProperty; } set { AutomaticProperty = value; } } private object Issue1221 { set { issue1221 = value; } } public object Item { get { return null; } set { } } #if ROSLYN public int NotAnAutoProperty => someField; #else public int NotAnAutoProperty { get { return someField; } } #endif public event EventHandler AutomaticEvent; [field: NonSerialized] public event EventHandler AutomaticEventWithInitializer = delegate { }; #if ROSLYN // Legacy csc has a bug where EventHandler<dynamic> is only used for the backing field public event EventHandler<dynamic> DynamicAutoEvent; #endif #if CS73 public event EventHandler<(int A, string B)> AutoEventWithTuple; #endif #if CS80 public event EventHandler<(int a, dynamic? b)> ComplexAutoEvent; #endif public event EventHandler CustomEvent { add { AutomaticEvent += value; } remove { AutomaticEvent -= value; } } public int Getter(StringBuilder b) { return b.Length; } public void Setter(StringBuilder b) { b.Capacity = 100; } public char IndexerGetter(StringBuilder b) { return b[50]; } public void IndexerSetter(StringBuilder b) { b[42] = 'b'; } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/PropertiesAndEvents.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/PropertiesAndEvents.cs", "repo_id": "ILSpy", "token_count": 1575 }
212
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Reflection; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { public class TypeAnalysisTests { private class @_ { } private byte[] byteArray; private ulong uint64Field; public int Issue1796a { get { return (int)(uint64Field & 0x7FFFFFFF); } set { uint64Field = (uint64Field & 0xFFFFFFFF80000000uL) | (ulong)value; } } public ushort Issue1796b { get { return (ushort)((uint64Field & 0xFFFF000000000000uL) >> 48); } set { uint64Field = (uint64Field & 0xFFFFFFFFFFFFuL) | ((ulong)value << 48); } } public byte SubtractFrom256(byte b) { return (byte)(256 - b); } #region Shift public int LShiftInteger(int num1, int num2) { return num1 << num2; } public uint LShiftUnsignedInteger(uint num1, uint num2) { return num1 << (int)num2; } public long LShiftLong(long num1, long num2) { return num1 << (int)num2; } public ulong LShiftUnsignedLong(ulong num1, ulong num2) { return num1 << (int)num2; } public int RShiftInteger(int num1, int num2) { return num1 >> num2; } public uint RShiftUnsignedInteger(uint num1, int num2) { return num1 >> num2; } public long RShiftLong(long num1, long num2) { return num1 >> (int)num2; } public ulong RShiftUnsignedLong(ulong num1, ulong num2) { return num1 >> (int)num2; } public int ShiftByte(byte num) { return num << 8; } public int RShiftByte(byte num) { return num >> 8; } public uint RShiftByteWithZeroExtension(byte num) { // zero extend -> cast to unsigned -> unsigned shift return (uint)num >> 8; } public int RShiftByteWithZeroExtensionReturnAsSigned(byte num) { #if CS110 // zero extend -> unsigned shift return num >>> 8; #else // zero extend -> cast to unsigned -> unsigned shift -> cast to signed return (int)((uint)num >> 8); #endif } public int RShiftByteAsSByte(byte num) { return (sbyte)num >> 8; } public int RShiftSByte(sbyte num) { return num >> 8; } public uint RShiftSByteWithZeroExtension(sbyte num) { return (uint)((byte)num >> 4); } public uint RShiftSByteWithSignExtension(sbyte num) { // sign extend -> cast to unsigned -> unsigned shift return (uint)num >> 4; } public int RShiftSByteWithSignExtensionReturnAsSigned(sbyte num) { #if CS110 // sign extend -> unsigned shift return num >>> 4; #else // sign extend -> cast to unsigned -> unsigned shift -> cast to signed return (int)((uint)num >> 4); #endif } public int RShiftSByteAsByte(sbyte num) { return (byte)num >> 8; } #endregion public int GetHashCode(long num) { return (int)num ^ (int)(num >> 32); } public void TernaryOp(Random a, Random b, bool c) { if ((c ? a : b) == null) { Console.WriteLine(); } } public void OperatorIs(object o) { Console.WriteLine(o is Random); Console.WriteLine(!(o is Random)); // If we didn't escape the '_' identifier here, this would look like a discard pattern Console.WriteLine(o is @_); } public byte[] CreateArrayWithInt(int length) { return new byte[length]; } public byte[] CreateArrayWithLong(long length) { return new byte[length]; } public byte[] CreateArrayWithUInt(uint length) { return new byte[length]; } public byte[] CreateArrayWithULong(ulong length) { return new byte[length]; } public byte[] CreateArrayWithShort(short length) { return new byte[length]; } public byte[] CreateArrayWithUShort(ushort length) { return new byte[length]; } public byte UseArrayWithInt(int i) { return byteArray[i]; } public byte UseArrayWithUInt(uint i) { return byteArray[i]; } public byte UseArrayWithLong(long i) { return byteArray[i]; } public byte UseArrayWithULong(ulong i) { return byteArray[i]; } public byte UseArrayWithShort(short i) { return byteArray[i]; } public byte UseArrayWithUShort(ushort i) { return byteArray[i]; } public byte UseArrayWithCastToUShort(int i) { // Unchecked cast = truncate to 16 bits return byteArray[(ushort)i]; } public StringComparison EnumDiffNumber(StringComparison data) { return data - 1; } public int EnumDiff(StringComparison a, StringComparison b) { return Math.Abs(a - b); } public bool CompareDelegatesByValue(Action a, Action b) { return a == b; } public bool CompareDelegatesByReference(Action a, Action b) { return (object)a == b; } public bool CompareDelegateWithNull(Action a) { return a == null; } public bool CompareStringsByValue(string a, string b) { return a == b; } public bool CompareStringsByReference(string a, string b) { return (object)a == b; } public bool CompareStringWithNull(string a) { return a == null; } public bool CompareType(Type a, Type b) { return a == b; } public bool CompareTypeByReference(Type a, Type b) { return (object)a == b; } public bool CompareTypeWithNull(Type t) { return t == null; } public Attribute CallExtensionMethodViaBaseClass(Type type) { return type.GetCustomAttribute<AttributeUsageAttribute>(); } public decimal ImplicitConversionToDecimal(byte v) { return v; } public decimal ImplicitConversionToDecimal(ulong v) { return v; } public bool EnumInConditionalOperator(bool b) { return string.Equals("", "", b ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase); } public bool MethodCallOnEnumConstant() { return AttributeTargets.All.HasFlag(AttributeTargets.Assembly); } public static string ImpossibleCast1(int i) { return (string)(object)i; } public static string ImpossibleCast2(Action a) { return (string)(object)a; } public static bool CompareLast32Bits(long a, long b) { return (int)a == (int)b; } public static bool Last32BitsAreZero(long a) { return (int)a == 0; } } }
ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/TypeAnalysisTests.cs/0
{ "file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/TypeAnalysisTests.cs", "repo_id": "ILSpy", "token_count": 2750 }
213