text stringlengths 7 35.3M | id stringlengths 11 185 | metadata dict | __index_level_0__ int64 0 2.14k |
|---|---|---|---|
using System;
using UnityEditor;
namespace ET
{
[TypeDrawer]
public class FloatTypeDrawer: ITypeDrawer
{
public bool HandlesType(Type type)
{
return type == typeof (float);
}
public object DrawAndGetNewValue(Type memberType, string memberName, object value, object target)
{
return EditorGUILayout.FloatField(memberName, (float) value);
}
}
} | ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/FloatTypeDrawer.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/FloatTypeDrawer.cs",
"repo_id": "ET",
"token_count": 184
} | 109 |
using System;
using UnityEditor;
using UnityEngine;
namespace ET
{
[TypeDrawer]
public class Vector2TypeDrawer: ITypeDrawer
{
public bool HandlesType(Type type)
{
return type == typeof (Vector2);
}
public object DrawAndGetNewValue(Type memberType, string memberName, object value, object target)
{
return EditorGUILayout.Vector2Field(memberName, (Vector2) value);
}
}
} | ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/Vector2TypeDrawer.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Editor/ComponentViewEditor/TypeDrawer/Vector2TypeDrawer.cs",
"repo_id": "ET",
"token_count": 193
} | 110 |
using System.Collections.Generic;
using System.IO;
namespace ET
{
public class EditorResHelper
{
/// <summary>
/// 获取文件夹内所有的预制跟场景路径
/// </summary>
/// <param name="srcPath">源文件夹</param>
/// <param name="subDire">是否获取子文件夹</param>
/// <returns></returns>
public static List<string> GetPrefabsAndScenes(string srcPath)
{
List<string> paths = new List<string>();
FileHelper.GetAllFiles(paths, srcPath);
List<string> files = new List<string>();
foreach (string str in paths)
{
if (str.EndsWith(".prefab") || str.EndsWith(".unity"))
{
files.Add(str);
}
}
return files;
}
/// <summary>
/// 获取文件夹内所有资源路径
/// </summary>
/// <param name="srcPath">源文件夹</param>
/// <param name="subDire">是否获取子文件夹</param>
/// <returns></returns>
public static List<string> GetAllResourcePath(string srcPath, bool subDire)
{
List<string> paths = new List<string>();
string[] files = Directory.GetFiles(srcPath);
foreach (string str in files)
{
if (str.EndsWith(".meta"))
{
continue;
}
paths.Add(str);
}
if (subDire)
{
foreach (string subPath in Directory.GetDirectories(srcPath))
{
List<string> subFiles = GetAllResourcePath(subPath, true);
paths.AddRange(subFiles);
}
}
return paths;
}
}
}
| ET/Unity/Assets/Scripts/Editor/Helper/EditorResHelper.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Editor/Helper/EditorResHelper.cs",
"repo_id": "ET",
"token_count": 1066
} | 111 |
fileFormatVersion: 2
guid: daf158bc563a309438e4f90016ac2761
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/Editor/RecastNavDataExporter.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/Editor/RecastNavDataExporter.meta",
"repo_id": "ET",
"token_count": 67
} | 112 |
fileFormatVersion: 2
guid: 4cb05eea2613caf458483a4ce7afbf94
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/Hotfix/Client/Demo.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Demo.meta",
"repo_id": "ET",
"token_count": 68
} | 113 |
namespace ET.Client
{
public static class LoginHelper
{
public static async ETTask Login(Scene root, string account, string password)
{
root.RemoveComponent<ClientSenderComponent>();
ClientSenderComponent clientSenderComponent = root.AddComponent<ClientSenderComponent>();
long playerId = await clientSenderComponent.LoginAsync(account, password);
root.GetComponent<PlayerComponent>().MyId = playerId;
await EventSystem.Instance.PublishAsync(root, new LoginFinish());
}
}
} | ET/Unity/Assets/Scripts/Hotfix/Client/Demo/NetClient/LoginHelper.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Demo/NetClient/LoginHelper.cs",
"repo_id": "ET",
"token_count": 248
} | 114 |
using System;
using System.Net;
namespace ET.Client
{
public static partial class RouterHelper
{
// 注册router
public static async ETTask<Session> CreateRouterSession(this NetComponent netComponent, IPEndPoint address, string account, string password)
{
uint localConn = (uint)(account.GetLongHashCode() ^ password.GetLongHashCode() ^ RandomGenerator.RandUInt32());
(uint recvLocalConn, IPEndPoint routerAddress) = await GetRouterAddress(netComponent, address, localConn, 0);
if (recvLocalConn == 0)
{
throw new Exception($"get router fail: {netComponent.Root().Id} {address}");
}
Log.Info($"get router: {recvLocalConn} {routerAddress}");
Session routerSession = netComponent.Create(routerAddress, address, recvLocalConn);
routerSession.AddComponent<PingComponent>();
routerSession.AddComponent<RouterCheckComponent>();
return routerSession;
}
public static async ETTask<(uint, IPEndPoint)> GetRouterAddress(this NetComponent netComponent, IPEndPoint address, uint localConn, uint remoteConn)
{
Log.Info($"start get router address: {netComponent.Root().Id} {address} {localConn} {remoteConn}");
//return (RandomHelper.RandUInt32(), address);
RouterAddressComponent routerAddressComponent = netComponent.Root().GetComponent<RouterAddressComponent>();
IPEndPoint routerInfo = routerAddressComponent.GetAddress();
uint recvLocalConn = await netComponent.Connect(routerInfo, address, localConn, remoteConn);
Log.Info($"finish get router address: {netComponent.Root().Id} {address} {localConn} {remoteConn} {recvLocalConn} {routerInfo}");
return (recvLocalConn, routerInfo);
}
// 向router申请
private static async ETTask<uint> Connect(this NetComponent netComponent, IPEndPoint routerAddress, IPEndPoint realAddress, uint localConn, uint remoteConn)
{
uint synFlag = remoteConn == 0? KcpProtocalType.RouterSYN : KcpProtocalType.RouterReconnectSYN;
// 注意,session也以localConn作为id,所以这里不能用localConn作为id
long id = (long)(((ulong)localConn << 32) | remoteConn);
using RouterConnector routerConnector = netComponent.AddChildWithId<RouterConnector>(id);
int count = 20;
byte[] sendCache = new byte[512];
uint connectId = RandomGenerator.RandUInt32();
sendCache.WriteTo(0, synFlag);
sendCache.WriteTo(1, localConn);
sendCache.WriteTo(5, remoteConn);
sendCache.WriteTo(9, connectId);
byte[] addressBytes = realAddress.ToString().ToByteArray();
Array.Copy(addressBytes, 0, sendCache, 13, addressBytes.Length);
TimerComponent timerComponent = netComponent.Root().GetComponent<TimerComponent>();
Log.Info($"router connect: {localConn} {remoteConn} {routerAddress} {realAddress}");
long lastSendTimer = 0;
while (true)
{
long timeNow = TimeInfo.Instance.ClientFrameTime();
if (timeNow - lastSendTimer > 300)
{
if (--count < 0)
{
Log.Error($"router connect timeout fail! {localConn} {remoteConn} {routerAddress} {realAddress}");
return 0;
}
lastSendTimer = timeNow;
// 发送
routerConnector.Connect(sendCache, 0, addressBytes.Length + 13, routerAddress);
}
await timerComponent.WaitFrameAsync();
if (routerConnector.Flag == 0)
{
continue;
}
return localConn;
}
}
}
} | ET/Unity/Assets/Scripts/Hotfix/Client/Demo/NetClient/Router/RouterHelper.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Hotfix/Client/Demo/NetClient/Router/RouterHelper.cs",
"repo_id": "ET",
"token_count": 1848
} | 115 |
fileFormatVersion: 2
guid: 3f400407796607144bf9eebf438b4c70
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/Hotfix/Server/Benchmark/NetComponentOnReadInvoker_BenchmarkServer.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Benchmark/NetComponentOnReadInvoker_BenchmarkServer.cs.meta",
"repo_id": "ET",
"token_count": 92
} | 116 |
namespace ET.Server
{
[FriendOf(typeof(GateSessionKeyComponent))]
public static partial class GateSessionKeyComponentSystem
{
public static void Add(this GateSessionKeyComponent self, long key, string account)
{
self.sessionKey.Add(key, account);
self.TimeoutRemoveKey(key).Coroutine();
}
public static string Get(this GateSessionKeyComponent self, long key)
{
string account = null;
self.sessionKey.TryGetValue(key, out account);
return account;
}
public static void Remove(this GateSessionKeyComponent self, long key)
{
self.sessionKey.Remove(key);
}
private static async ETTask TimeoutRemoveKey(this GateSessionKeyComponent self, long key)
{
await self.Root().GetComponent<TimerComponent>().WaitAsync(20000);
self.sessionKey.Remove(key);
}
}
} | ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Gate/GateSessionKeyComponentSystem.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Gate/GateSessionKeyComponentSystem.cs",
"repo_id": "ET",
"token_count": 400
} | 117 |
fileFormatVersion: 2
guid: 0beef288928e88b4d8cad09b6a39c25d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Map.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Map.meta",
"repo_id": "ET",
"token_count": 72
} | 118 |
fileFormatVersion: 2
guid: 10a2365c686050546995d6a3897b9038
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Map/Unit/UnitLeaveSightRange_NotifyClient.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Demo/Map/Unit/UnitLeaveSightRange_NotifyClient.cs.meta",
"repo_id": "ET",
"token_count": 93
} | 119 |
namespace ET.Server
{
[MessageSessionHandler(SceneType.Gate)]
public class C2G_MatchHandler : MessageSessionHandler<C2G_Match, G2C_Match>
{
protected override async ETTask Run(Session session, C2G_Match request, G2C_Match response)
{
Player player = session.GetComponent<SessionPlayerComponent>().Player;
StartSceneConfig startSceneConfig = StartSceneConfigCategory.Instance.Match;
G2Match_Match g2MatchMatch = G2Match_Match.Create();
g2MatchMatch.Id = player.Id;
await session.Root().GetComponent<MessageSender>().Call(startSceneConfig.ActorId, g2MatchMatch);
}
}
} | ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Gate/C2G_MatchHandler.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Gate/C2G_MatchHandler.cs",
"repo_id": "ET",
"token_count": 200
} | 120 |
fileFormatVersion: 2
guid: 6d671f754d680422caba612a77dfdb63
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Map/RoomServerComponentSystem.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Map/RoomServerComponentSystem.cs.meta",
"repo_id": "ET",
"token_count": 92
} | 121 |
fileFormatVersion: 2
guid: 524fc1d8fab854147a900bad52d3b28f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Room/LSServerUpdaterSystem.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/LockStep/Room/LSServerUpdaterSystem.cs.meta",
"repo_id": "ET",
"token_count": 94
} | 122 |
using System.Net;
namespace ET.Server
{
[Invoke((long)SceneType.Location)]
public class FiberInit_Location: AInvokeHandler<FiberInit, ETTask>
{
public override async ETTask Handle(FiberInit fiberInit)
{
Scene root = fiberInit.Fiber.Root;
root.AddComponent<MailBoxComponent, MailBoxType>(MailBoxType.UnOrderedMessage);
root.AddComponent<TimerComponent>();
root.AddComponent<CoroutineLockComponent>();
root.AddComponent<ProcessInnerSender>();
root.AddComponent<MessageSender>();
root.AddComponent<LocationManagerComoponent>();
await ETTask.CompletedTask;
}
}
} | ET/Unity/Assets/Scripts/Hotfix/Server/Module/ActorLocation/FiberInit_Location.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Module/ActorLocation/FiberInit_Location.cs",
"repo_id": "ET",
"token_count": 296
} | 123 |
using System;
namespace ET.Server
{
[MessageHandler(SceneType.Location)]
public class ObjectLockRequestHandler: MessageHandler<Scene, ObjectLockRequest, ObjectLockResponse>
{
protected override async ETTask Run(Scene scene, ObjectLockRequest request, ObjectLockResponse response)
{
await scene.GetComponent<LocationManagerComoponent>().Get(request.Type).Lock(request.Key, request.ActorId, request.Time);
}
}
} | ET/Unity/Assets/Scripts/Hotfix/Server/Module/ActorLocation/ObjectLockRequestHandler.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Module/ActorLocation/ObjectLockRequestHandler.cs",
"repo_id": "ET",
"token_count": 156
} | 124 |
using System.Net;
namespace ET.Server
{
[Invoke((long)SceneType.Router)]
public class FiberInit_Router: AInvokeHandler<FiberInit, ETTask>
{
public override async ETTask Handle(FiberInit fiberInit)
{
Scene root = fiberInit.Fiber.Root;
StartSceneConfig startSceneConfig = StartSceneConfigCategory.Instance.Get((int)root.Id);
// 开发期间使用OuterIPPort,云服务器因为本机没有OuterIP,所以要改成InnerIPPort,然后在云防火墙中端口映射到InnerIPPort
root.AddComponent<RouterComponent, IPEndPoint, string>(startSceneConfig.OuterIPPort, startSceneConfig.StartProcessConfig.InnerIP);
Log.Console($"Router create: {root.Fiber.Id}");
await ETTask.CompletedTask;
}
}
} | ET/Unity/Assets/Scripts/Hotfix/Server/Module/Router/FiberInit_Router.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Hotfix/Server/Module/Router/FiberInit_Router.cs",
"repo_id": "ET",
"token_count": 384
} | 125 |
namespace ET
{
[Event(SceneType.Main)]
public class EntryEvent1_InitShare: AEvent<Scene, EntryEvent1>
{
protected override async ETTask Run(Scene root, EntryEvent1 args)
{
root.AddComponent<TimerComponent>();
root.AddComponent<CoroutineLockComponent>();
root.AddComponent<ObjectWait>();
root.AddComponent<MailBoxComponent, MailBoxType>(MailBoxType.UnOrderedMessage);
root.AddComponent<ProcessInnerSender>();
await ETTask.CompletedTask;
}
}
} | ET/Unity/Assets/Scripts/Hotfix/Share/Demo/EntryEvent1_InitShare.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Hotfix/Share/Demo/EntryEvent1_InitShare.cs",
"repo_id": "ET",
"token_count": 247
} | 126 |
namespace ET
{
[Invoke((long)MailBoxType.OrderedMessage)]
public class MailBoxType_OrderedMessageHandler: AInvokeHandler<MailBoxInvoker>
{
public override void Handle(MailBoxInvoker args)
{
HandleInner(args).Coroutine();
}
private static async ETTask HandleInner(MailBoxInvoker args)
{
MailBoxComponent mailBoxComponent = args.MailBoxComponent;
MessageObject messageObject = args.MessageObject;
Fiber fiber = mailBoxComponent.Fiber();
if (fiber.IsDisposed)
{
return;
}
long instanceId = mailBoxComponent.InstanceId;
using (await fiber.Root.GetComponent<CoroutineLockComponent>().Wait(CoroutineLockType.Mailbox, mailBoxComponent.ParentInstanceId))
{
if (mailBoxComponent.InstanceId != instanceId)
{
if (messageObject is IRequest request)
{
IResponse resp = MessageHelper.CreateResponse(request.GetType(), request.RpcId, ErrorCore.ERR_NotFoundActor);
mailBoxComponent.Root().GetComponent<ProcessInnerSender>().Reply(args.FromAddress, resp);
}
return;
}
await MessageDispatcher.Instance.Handle(mailBoxComponent.Parent, args.FromAddress, messageObject);
}
}
}
} | ET/Unity/Assets/Scripts/Hotfix/Share/Module/Actor/MailBoxType_OrderedMessageHandler.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Hotfix/Share/Module/Actor/MailBoxType_OrderedMessageHandler.cs",
"repo_id": "ET",
"token_count": 704
} | 127 |
using System;
namespace ET
{
[EntitySystemOf(typeof(SessionAcceptTimeoutComponent))]
[FriendOf(typeof(SessionAcceptTimeoutComponent))]
public static partial class SessionAcceptTimeoutComponentHelper
{
[Invoke(TimerInvokeType.SessionAcceptTimeout)]
public class SessionAcceptTimeout: ATimer<SessionAcceptTimeoutComponent>
{
protected override void Run(SessionAcceptTimeoutComponent self)
{
try
{
self.Parent.Dispose();
}
catch (Exception e)
{
Log.Error($"move timer error: {self.Id}\n{e}");
}
}
}
[EntitySystem]
private static void Awake(this SessionAcceptTimeoutComponent self)
{
self.Timer = self.Root().GetComponent<TimerComponent>().NewOnceTimer(TimeInfo.Instance.ServerNow() + 5000, TimerInvokeType.SessionAcceptTimeout, self);
}
[EntitySystem]
private static void Destroy(this SessionAcceptTimeoutComponent self)
{
self.Root().GetComponent<TimerComponent>()?.Remove(ref self.Timer);
}
}
} | ET/Unity/Assets/Scripts/Hotfix/Share/Module/Message/SessionAcceptTimeoutComponentSystem.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Hotfix/Share/Module/Message/SessionAcceptTimeoutComponentSystem.cs",
"repo_id": "ET",
"token_count": 579
} | 128 |
using System;
namespace ET
{
public static partial class CurrentScenesComponentSystem
{
public static Scene CurrentScene(this Scene root)
{
return root.GetComponent<CurrentScenesComponent>()?.Scene;
}
}
} | ET/Unity/Assets/Scripts/Hotfix/Share/Module/Scene/CurrentScenesComponentSystem.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Hotfix/Share/Module/Scene/CurrentScenesComponentSystem.cs",
"repo_id": "ET",
"token_count": 102
} | 129 |
using System;
using System.Collections.Generic;
using System.IO;
namespace ET.Client
{
[Event(SceneType.Main)]
public class EntryEvent3_InitClient: AEvent<Scene, EntryEvent3>
{
protected override async ETTask Run(Scene root, EntryEvent3 args)
{
GlobalComponent globalComponent = root.AddComponent<GlobalComponent>();
root.AddComponent<UIGlobalComponent>();
root.AddComponent<UIComponent>();
root.AddComponent<ResourcesLoaderComponent>();
root.AddComponent<PlayerComponent>();
root.AddComponent<CurrentScenesComponent>();
// 根据配置修改掉Main Fiber的SceneType
SceneType sceneType = EnumHelper.FromString<SceneType>(globalComponent.GlobalConfig.AppType.ToString());
root.SceneType = sceneType;
await EventSystem.Instance.PublishAsync(root, new AppStartInitFinish());
}
}
} | ET/Unity/Assets/Scripts/HotfixView/Client/Demo/EntryEvent3_InitClient.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/Demo/EntryEvent3_InitClient.cs",
"repo_id": "ET",
"token_count": 406
} | 130 |
using System;
using UnityEngine;
namespace ET.Client
{
[UIEvent(UIType.UIHelp)]
public class UIHelpEvent: AUIEvent
{
public override async ETTask<UI> OnCreate(UIComponent uiComponent, UILayer uiLayer)
{
try
{
string assetsName = $"Assets/Bundles/UI/Demo/{UIType.UIHelp}.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.UIHelp, gameObject);
ui.AddComponent<UIHelpComponent>();
return ui;
}
catch (Exception e)
{
Log.Error(e);
return null;
}
}
public override void OnRemove(UIComponent uiComponent)
{
}
}
} | ET/Unity/Assets/Scripts/HotfixView/Client/Demo/UI/UIHelp/UIHelpEvent.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/Demo/UI/UIHelp/UIHelpEvent.cs",
"repo_id": "ET",
"token_count": 426
} | 131 |
using UnityEngine;
using UnityEngine.UI;
namespace ET.Client
{
[EntitySystemOf(typeof(UILoginComponent))]
[FriendOf(typeof(UILoginComponent))]
public static partial class UILoginComponentSystem
{
[EntitySystem]
private static void Awake(this UILoginComponent self)
{
ReferenceCollector rc = self.GetParent<UI>().GameObject.GetComponent<ReferenceCollector>();
self.loginBtn = rc.Get<GameObject>("LoginBtn");
self.loginBtn.GetComponent<Button>().onClick.AddListener(()=> { self.OnLogin(); });
self.account = rc.Get<GameObject>("Account");
self.password = rc.Get<GameObject>("Password");
}
public static void OnLogin(this UILoginComponent self)
{
LoginHelper.Login(
self.Root(),
self.account.GetComponent<InputField>().text,
self.password.GetComponent<InputField>().text).Coroutine();
}
}
}
| ET/Unity/Assets/Scripts/HotfixView/Client/Demo/UI/UILogin/UILoginComponentSystem.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/Demo/UI/UILogin/UILoginComponentSystem.cs",
"repo_id": "ET",
"token_count": 317
} | 132 |
fileFormatVersion: 2
guid: 5d6a8394e7b3248f08588960a9dab4d0
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/HotfixView/Client/LockStep/Camera.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/LockStep/Camera.meta",
"repo_id": "ET",
"token_count": 73
} | 133 |
namespace ET.Client
{
[Event(SceneType.LockStep)]
public class AfterCreateClientScene_LSAddComponent: AEvent<Scene, AfterCreateClientScene>
{
protected override async ETTask Run(Scene scene, AfterCreateClientScene args)
{
scene.AddComponent<UIComponent>();
scene.AddComponent<ResourcesLoaderComponent>();
await ETTask.CompletedTask;
}
}
} | ET/Unity/Assets/Scripts/HotfixView/Client/LockStep/Scene/AfterCreateClientScene_LSAddComponent.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/LockStep/Scene/AfterCreateClientScene_LSAddComponent.cs",
"repo_id": "ET",
"token_count": 164
} | 134 |
using System.Collections.Generic;
namespace ET.Client
{
/// <summary>
/// 管理Scene上的UI
/// </summary>
[EntitySystemOf(typeof(UIComponent))]
[FriendOf(typeof(UIComponent))]
public static partial class UIComponentSystem
{
[EntitySystem]
private static void Awake(this UIComponent self)
{
self.UIGlobalComponent = self.Root().GetComponent<UIGlobalComponent>();
}
public static async ETTask<UI> Create(this UIComponent self, string uiType, UILayer uiLayer)
{
UI ui = await self.UIGlobalComponent.OnCreate(self, uiType, uiLayer);
self.UIs.Add(uiType, ui);
return ui;
}
public static void Remove(this UIComponent self, string uiType)
{
if (!self.UIs.TryGetValue(uiType, out EntityRef<UI> uiRef))
{
return;
}
self.UIGlobalComponent.OnRemove(self, uiType);
self.UIs.Remove(uiType);
UI ui = uiRef;
ui?.Dispose();
}
public static UI Get(this UIComponent self, string name)
{
self.UIs.TryGetValue(name, out EntityRef<UI> uiRef);
return uiRef;
}
}
} | ET/Unity/Assets/Scripts/HotfixView/Client/Module/UI/UIComponentSystem.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/HotfixView/Client/Module/UI/UIComponentSystem.cs",
"repo_id": "ET",
"token_count": 447
} | 135 |
fileFormatVersion: 2
guid: 8347f75bbf20473292de676504ad7398
timeCreated: 1504162087 | ET/Unity/Assets/Scripts/Loader/MonoBehaviour/CanvasConfig.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/Loader/MonoBehaviour/CanvasConfig.cs.meta",
"repo_id": "ET",
"token_count": 36
} | 136 |
fileFormatVersion: 2
guid: 861f8500341e54e80be11c1ab1812f99
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/Loader/Plugins/HybridCLR/Generated.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/Loader/Plugins/HybridCLR/Generated.meta",
"repo_id": "ET",
"token_count": 69
} | 137 |
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
namespace ET.Client
{
[ComponentOf(typeof(Scene))]
public class RouterAddressComponent: Entity, IAwake<string, int>
{
public IPAddress RouterManagerIPAddress { get; set; }
public string RouterManagerHost;
public int RouterManagerPort;
public HttpGetRouterResponse Info;
public int RouterIndex;
}
} | ET/Unity/Assets/Scripts/Model/Client/Demo/NetClient/Router/RouterAddressComponent.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Model/Client/Demo/NetClient/Router/RouterAddressComponent.cs",
"repo_id": "ET",
"token_count": 158
} | 138 |
namespace ET.Client
{
namespace WaitType
{
public struct Wait_Room2C_Start: IWaitType
{
public int Error { get; set; }
public Room2C_Start Message;
}
}
} | ET/Unity/Assets/Scripts/Model/Client/LockStep/WaitType.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Model/Client/LockStep/WaitType.cs",
"repo_id": "ET",
"token_count": 106
} | 139 |
fileFormatVersion: 2
guid: 3faeca7fdc230f44d84aca572973ad02
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/Model/Generate/Client/Config/UnitConfig.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/Model/Generate/Client/Config/UnitConfig.cs.meta",
"repo_id": "ET",
"token_count": 92
} | 140 |
using MemoryPack;
using System.Collections.Generic;
namespace ET
{
[MemoryPackable]
[Message(InnerMessage.ObjectQueryRequest)]
[ResponseType(nameof(ObjectQueryResponse))]
public partial class ObjectQueryRequest : MessageObject, IRequest
{
public static ObjectQueryRequest Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(ObjectQueryRequest), isFromPool) as ObjectQueryRequest;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public long Key { get; set; }
[MemoryPackOrder(2)]
public long InstanceId { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Key = default;
this.InstanceId = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.M2A_Reload)]
[ResponseType(nameof(A2M_Reload))]
public partial class M2A_Reload : MessageObject, IRequest
{
public static M2A_Reload Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(M2A_Reload), isFromPool) as M2A_Reload;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.A2M_Reload)]
public partial class A2M_Reload : MessageObject, IResponse
{
public static A2M_Reload Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(A2M_Reload), isFromPool) as A2M_Reload;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public int Error { get; set; }
[MemoryPackOrder(2)]
public string Message { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Error = default;
this.Message = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.G2G_LockRequest)]
[ResponseType(nameof(G2G_LockResponse))]
public partial class G2G_LockRequest : MessageObject, IRequest
{
public static G2G_LockRequest Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(G2G_LockRequest), isFromPool) as G2G_LockRequest;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public long Id { get; set; }
[MemoryPackOrder(2)]
public string Address { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Id = default;
this.Address = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.G2G_LockResponse)]
public partial class G2G_LockResponse : MessageObject, IResponse
{
public static G2G_LockResponse Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(G2G_LockResponse), isFromPool) as G2G_LockResponse;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public int Error { get; set; }
[MemoryPackOrder(2)]
public string Message { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Error = default;
this.Message = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.G2G_LockReleaseRequest)]
[ResponseType(nameof(G2G_LockReleaseResponse))]
public partial class G2G_LockReleaseRequest : MessageObject, IRequest
{
public static G2G_LockReleaseRequest Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(G2G_LockReleaseRequest), isFromPool) as G2G_LockReleaseRequest;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public long Id { get; set; }
[MemoryPackOrder(2)]
public string Address { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Id = default;
this.Address = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.G2G_LockReleaseResponse)]
public partial class G2G_LockReleaseResponse : MessageObject, IResponse
{
public static G2G_LockReleaseResponse Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(G2G_LockReleaseResponse), isFromPool) as G2G_LockReleaseResponse;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public int Error { get; set; }
[MemoryPackOrder(2)]
public string Message { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Error = default;
this.Message = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.ObjectAddRequest)]
[ResponseType(nameof(ObjectAddResponse))]
public partial class ObjectAddRequest : MessageObject, IRequest
{
public static ObjectAddRequest Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(ObjectAddRequest), isFromPool) as ObjectAddRequest;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public int Type { get; set; }
[MemoryPackOrder(2)]
public long Key { get; set; }
[MemoryPackOrder(3)]
public ActorId ActorId { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Type = default;
this.Key = default;
this.ActorId = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.ObjectAddResponse)]
public partial class ObjectAddResponse : MessageObject, IResponse
{
public static ObjectAddResponse Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(ObjectAddResponse), isFromPool) as ObjectAddResponse;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public int Error { get; set; }
[MemoryPackOrder(2)]
public string Message { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Error = default;
this.Message = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.ObjectLockRequest)]
[ResponseType(nameof(ObjectLockResponse))]
public partial class ObjectLockRequest : MessageObject, IRequest
{
public static ObjectLockRequest Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(ObjectLockRequest), isFromPool) as ObjectLockRequest;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public int Type { get; set; }
[MemoryPackOrder(2)]
public long Key { get; set; }
[MemoryPackOrder(3)]
public ActorId ActorId { get; set; }
[MemoryPackOrder(4)]
public int Time { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Type = default;
this.Key = default;
this.ActorId = default;
this.Time = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.ObjectLockResponse)]
public partial class ObjectLockResponse : MessageObject, IResponse
{
public static ObjectLockResponse Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(ObjectLockResponse), isFromPool) as ObjectLockResponse;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public int Error { get; set; }
[MemoryPackOrder(2)]
public string Message { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Error = default;
this.Message = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.ObjectUnLockRequest)]
[ResponseType(nameof(ObjectUnLockResponse))]
public partial class ObjectUnLockRequest : MessageObject, IRequest
{
public static ObjectUnLockRequest Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(ObjectUnLockRequest), isFromPool) as ObjectUnLockRequest;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public int Type { get; set; }
[MemoryPackOrder(2)]
public long Key { get; set; }
[MemoryPackOrder(3)]
public ActorId OldActorId { get; set; }
[MemoryPackOrder(4)]
public ActorId NewActorId { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Type = default;
this.Key = default;
this.OldActorId = default;
this.NewActorId = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.ObjectUnLockResponse)]
public partial class ObjectUnLockResponse : MessageObject, IResponse
{
public static ObjectUnLockResponse Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(ObjectUnLockResponse), isFromPool) as ObjectUnLockResponse;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public int Error { get; set; }
[MemoryPackOrder(2)]
public string Message { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Error = default;
this.Message = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.ObjectRemoveRequest)]
[ResponseType(nameof(ObjectRemoveResponse))]
public partial class ObjectRemoveRequest : MessageObject, IRequest
{
public static ObjectRemoveRequest Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(ObjectRemoveRequest), isFromPool) as ObjectRemoveRequest;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public int Type { get; set; }
[MemoryPackOrder(2)]
public long Key { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Type = default;
this.Key = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.ObjectRemoveResponse)]
public partial class ObjectRemoveResponse : MessageObject, IResponse
{
public static ObjectRemoveResponse Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(ObjectRemoveResponse), isFromPool) as ObjectRemoveResponse;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public int Error { get; set; }
[MemoryPackOrder(2)]
public string Message { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Error = default;
this.Message = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.ObjectGetRequest)]
[ResponseType(nameof(ObjectGetResponse))]
public partial class ObjectGetRequest : MessageObject, IRequest
{
public static ObjectGetRequest Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(ObjectGetRequest), isFromPool) as ObjectGetRequest;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public int Type { get; set; }
[MemoryPackOrder(2)]
public long Key { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Type = default;
this.Key = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.ObjectGetResponse)]
public partial class ObjectGetResponse : MessageObject, IResponse
{
public static ObjectGetResponse Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(ObjectGetResponse), isFromPool) as ObjectGetResponse;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public int Error { get; set; }
[MemoryPackOrder(2)]
public string Message { get; set; }
[MemoryPackOrder(3)]
public int Type { get; set; }
[MemoryPackOrder(4)]
public ActorId ActorId { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Error = default;
this.Message = default;
this.Type = default;
this.ActorId = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.R2G_GetLoginKey)]
[ResponseType(nameof(G2R_GetLoginKey))]
public partial class R2G_GetLoginKey : MessageObject, IRequest
{
public static R2G_GetLoginKey Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(R2G_GetLoginKey), isFromPool) as R2G_GetLoginKey;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public string Account { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Account = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.G2R_GetLoginKey)]
public partial class G2R_GetLoginKey : MessageObject, IResponse
{
public static G2R_GetLoginKey Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(G2R_GetLoginKey), isFromPool) as G2R_GetLoginKey;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public int Error { get; set; }
[MemoryPackOrder(2)]
public string Message { get; set; }
[MemoryPackOrder(3)]
public long Key { get; set; }
[MemoryPackOrder(4)]
public long GateId { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Error = default;
this.Message = default;
this.Key = default;
this.GateId = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.G2M_SessionDisconnect)]
public partial class G2M_SessionDisconnect : MessageObject, ILocationMessage
{
public static G2M_SessionDisconnect Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(G2M_SessionDisconnect), isFromPool) as G2M_SessionDisconnect;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.ObjectQueryResponse)]
public partial class ObjectQueryResponse : MessageObject, IResponse
{
public static ObjectQueryResponse Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(ObjectQueryResponse), isFromPool) as ObjectQueryResponse;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public int Error { get; set; }
[MemoryPackOrder(2)]
public string Message { get; set; }
[MemoryPackOrder(3)]
public byte[] Entity { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Error = default;
this.Message = default;
this.Entity = default;
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.M2M_UnitTransferRequest)]
[ResponseType(nameof(M2M_UnitTransferResponse))]
public partial class M2M_UnitTransferRequest : MessageObject, IRequest
{
public static M2M_UnitTransferRequest Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(M2M_UnitTransferRequest), isFromPool) as M2M_UnitTransferRequest;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public ActorId OldActorId { get; set; }
[MemoryPackOrder(2)]
public byte[] Unit { get; set; }
[MemoryPackOrder(3)]
public List<byte[]> Entitys { get; set; } = new();
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.OldActorId = default;
this.Unit = default;
this.Entitys.Clear();
ObjectPool.Instance.Recycle(this);
}
}
[MemoryPackable]
[Message(InnerMessage.M2M_UnitTransferResponse)]
public partial class M2M_UnitTransferResponse : MessageObject, IResponse
{
public static M2M_UnitTransferResponse Create(bool isFromPool = false)
{
return ObjectPool.Instance.Fetch(typeof(M2M_UnitTransferResponse), isFromPool) as M2M_UnitTransferResponse;
}
[MemoryPackOrder(0)]
public int RpcId { get; set; }
[MemoryPackOrder(1)]
public int Error { get; set; }
[MemoryPackOrder(2)]
public string Message { get; set; }
public override void Dispose()
{
if (!this.IsFromPool)
{
return;
}
this.RpcId = default;
this.Error = default;
this.Message = default;
ObjectPool.Instance.Recycle(this);
}
}
public static class InnerMessage
{
public const ushort ObjectQueryRequest = 20002;
public const ushort M2A_Reload = 20003;
public const ushort A2M_Reload = 20004;
public const ushort G2G_LockRequest = 20005;
public const ushort G2G_LockResponse = 20006;
public const ushort G2G_LockReleaseRequest = 20007;
public const ushort G2G_LockReleaseResponse = 20008;
public const ushort ObjectAddRequest = 20009;
public const ushort ObjectAddResponse = 20010;
public const ushort ObjectLockRequest = 20011;
public const ushort ObjectLockResponse = 20012;
public const ushort ObjectUnLockRequest = 20013;
public const ushort ObjectUnLockResponse = 20014;
public const ushort ObjectRemoveRequest = 20015;
public const ushort ObjectRemoveResponse = 20016;
public const ushort ObjectGetRequest = 20017;
public const ushort ObjectGetResponse = 20018;
public const ushort R2G_GetLoginKey = 20019;
public const ushort G2R_GetLoginKey = 20020;
public const ushort G2M_SessionDisconnect = 20021;
public const ushort ObjectQueryResponse = 20022;
public const ushort M2M_UnitTransferRequest = 20023;
public const ushort M2M_UnitTransferResponse = 20024;
}
} | ET/Unity/Assets/Scripts/Model/Generate/ClientServer/Message/InnerMessage_S_20001.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Model/Generate/ClientServer/Message/InnerMessage_S_20001.cs",
"repo_id": "ET",
"token_count": 10466
} | 141 |
using System;
using System.Collections.Generic;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Options;
using System.ComponentModel;
namespace ET
{
[Config]
public partial class StartSceneConfigCategory : Singleton<StartSceneConfigCategory>, IMerge
{
[BsonElement]
[BsonDictionaryOptions(DictionaryRepresentation.ArrayOfArrays)]
private Dictionary<int, StartSceneConfig> dict = new();
public void Merge(object o)
{
StartSceneConfigCategory s = o as StartSceneConfigCategory;
foreach (var kv in s.dict)
{
this.dict.Add(kv.Key, kv.Value);
}
}
public StartSceneConfig Get(int id)
{
this.dict.TryGetValue(id, out StartSceneConfig item);
if (item == null)
{
throw new Exception($"配置找不到,配置表名: {nameof (StartSceneConfig)},配置id: {id}");
}
return item;
}
public bool Contain(int id)
{
return this.dict.ContainsKey(id);
}
public Dictionary<int, StartSceneConfig> GetAll()
{
return this.dict;
}
public StartSceneConfig GetOne()
{
if (this.dict == null || this.dict.Count <= 0)
{
return null;
}
return this.dict.Values.GetEnumerator().Current;
}
}
public partial class StartSceneConfig: ProtoObject, IConfig
{
/// <summary>Id</summary>
public int Id { get; set; }
/// <summary>所属进程</summary>
public int Process { get; set; }
/// <summary>所属区</summary>
public int Zone { get; set; }
/// <summary>类型</summary>
public string SceneType { get; set; }
/// <summary>名字</summary>
public string Name { get; set; }
/// <summary>外网端口</summary>
public int Port { get; set; }
}
}
| ET/Unity/Assets/Scripts/Model/Generate/Server/Config/StartSceneConfig.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Model/Generate/Server/Config/StartSceneConfig.cs",
"repo_id": "ET",
"token_count": 927
} | 142 |
fileFormatVersion: 2
guid: 06f629321c0b3d44b9e0606d2b5f5303
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/Model/Server/Demo/Gate.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/Model/Server/Demo/Gate.meta",
"repo_id": "ET",
"token_count": 73
} | 143 |
fileFormatVersion: 2
guid: e2a25a771a90c4a8680f28e4f53a36a4
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/Model/Server/Demo/Robot/Case.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/Model/Server/Demo/Robot/Case.meta",
"repo_id": "ET",
"token_count": 73
} | 144 |
using System.Collections.Generic;
using Unity.Mathematics;
namespace ET.Server
{
[ComponentOf(typeof(Unit))]
public class AOIEntity: Entity, IAwake<int, float3>, IDestroy
{
public Unit Unit => this.GetParent<Unit>();
public int ViewDistance;
private EntityRef<Cell> cell;
public Cell Cell
{
get
{
return this.cell;
}
set
{
this.cell = value;
}
}
// 观察进入视野的Cell
public HashSet<long> SubEnterCells = new HashSet<long>();
// 观察离开视野的Cell
public HashSet<long> SubLeaveCells = new HashSet<long>();
// 观察进入视野的Cell
public HashSet<long> enterHashSet = new HashSet<long>();
// 观察离开视野的Cell
public HashSet<long> leaveHashSet = new HashSet<long>();
// 我看的见的Unit
public Dictionary<long, EntityRef<AOIEntity>> SeeUnits = new Dictionary<long, EntityRef<AOIEntity>>();
// 看见我的Unit
public Dictionary<long, EntityRef<AOIEntity>> BeSeeUnits = new Dictionary<long, EntityRef<AOIEntity>>();
// 我看的见的Player
public Dictionary<long, EntityRef<AOIEntity>> SeePlayers = new Dictionary<long, EntityRef<AOIEntity>>();
// 看见我的Player单独放一个Dict,用于广播
public Dictionary<long, EntityRef<AOIEntity>> BeSeePlayers = new Dictionary<long, EntityRef<AOIEntity>>();
}
} | ET/Unity/Assets/Scripts/Model/Server/Module/AOI/AOIEntity.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Model/Server/Module/AOI/AOIEntity.cs",
"repo_id": "ET",
"token_count": 776
} | 145 |
fileFormatVersion: 2
guid: 850082c851b74ff419893672cb613cf3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/Model/Server/Module/Http/IHttpHandler.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/Model/Server/Module/Http/IHttpHandler.cs.meta",
"repo_id": "ET",
"token_count": 92
} | 146 |
fileFormatVersion: 2
guid: bd01ac0fb84bbf64db1fcba8deb29db6
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/Model/Server/Module/Router.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/Model/Server/Module/Router.meta",
"repo_id": "ET",
"token_count": 69
} | 147 |
using System;
namespace ET
{
[EnableMethod]
public abstract partial class LSEntity: Entity
{
public new K AddComponent<K>(bool isFromPool = false) where K : LSEntity, IAwake, new()
{
return this.AddComponentWithId<K>(this.GetId(), isFromPool);
}
public new K AddComponent<K, P1>(P1 p1, bool isFromPool = false) where K : LSEntity, IAwake<P1>, new()
{
return this.AddComponentWithId<K, P1>(this.GetId(), p1, isFromPool);
}
public new K AddComponent<K, P1, P2>(P1 p1, P2 p2, bool isFromPool = false) where K : LSEntity, IAwake<P1, P2>, new()
{
return this.AddComponentWithId<K, P1, P2>(this.GetId(), p1, p2, isFromPool);
}
public new K AddComponent<K, P1, P2, P3>(P1 p1, P2 p2, P3 p3, bool isFromPool = false) where K : LSEntity, IAwake<P1, P2, P3>, new()
{
return this.AddComponentWithId<K, P1, P2, P3>(this.GetId(), p1, p2, p3, isFromPool);
}
[EnableAccessEntiyChild]
public new T AddChild<T>(bool isFromPool = false) where T : LSEntity, IAwake
{
return this.AddChildWithId<T>(this.GetId(), isFromPool);
}
[EnableAccessEntiyChild]
public new T AddChild<T, A>(A a, bool isFromPool = false) where T : LSEntity, IAwake<A>
{
return this.AddChildWithId<T, A>(this.GetId(), a, isFromPool);
}
[EnableAccessEntiyChild]
public new T AddChild<T, A, B>(A a, B b, bool isFromPool = false) where T : LSEntity, IAwake<A, B>
{
return this.AddChildWithId<T, A, B>(this.GetId(), a, b, isFromPool);
}
[EnableAccessEntiyChild]
public new T AddChild<T, A, B, C>(A a, B b, C c, bool isFromPool = false) where T : LSEntity, IAwake<A, B, C>
{
return this.AddChildWithId<T, A, B, C>(this.GetId(), a, b, c, isFromPool);
}
protected override long GetLongHashCode(Type type)
{
return LSEntitySystemSingleton.Instance.GetLongHashCode(type);
}
protected override void RegisterSystem()
{
LSWorld lsWorld = (LSWorld)this.IScene;
TypeSystems.OneTypeSystems oneTypeSystems = LSEntitySystemSingleton.Instance.GetOneTypeSystems(this.GetType());
if (oneTypeSystems == null)
{
return;
}
if (oneTypeSystems.QueueFlag[LSQueneUpdateIndex.LSUpdate])
{
lsWorld.RegisterSystem(this);
}
}
}
} | ET/Unity/Assets/Scripts/Model/Share/LockStep/LSEntity.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Model/Share/LockStep/LSEntity.cs",
"repo_id": "ET",
"token_count": 1269
} | 148 |
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;
using MemoryPack;
using TrueSync;
namespace ET
{
public static class LSWorldSystem
{
public static LSWorld LSWorld(this LSEntity entity)
{
return entity.IScene as LSWorld;
}
public static long GetId(this LSEntity entity)
{
return entity.LSWorld().GetId();
}
public static TSRandom GetRandom(this LSEntity entity)
{
return entity.LSWorld().Random;
}
}
[EnableMethod]
[ChildOf]
[MemoryPackable]
public partial class LSWorld: Entity, IAwake, IScene
{
[MemoryPackConstructor]
public LSWorld()
{
}
public LSWorld(SceneType sceneType)
{
this.Id = this.GetId();
this.SceneType = sceneType;
}
private readonly LSUpdater updater = new();
[BsonIgnore]
[MemoryPackIgnore]
public Fiber Fiber { get; set; }
[BsonElement]
[MemoryPackInclude]
private long idGenerator;
public long GetId()
{
return ++this.idGenerator;
}
public TSRandom Random { get; set; }
[BsonIgnore]
[MemoryPackIgnore]
public SceneType SceneType { get; set; }
public int Frame { get; set; }
public void Update()
{
this.updater.Update();
++this.Frame;
}
public void RegisterSystem(LSEntity entity)
{
this.updater.Add(entity);
}
public new K AddComponent<K>(bool isFromPool = false) where K : LSEntity, IAwake, new()
{
return this.AddComponentWithId<K>(this.GetId(), isFromPool);
}
public new K AddComponent<K, P1>(P1 p1, bool isFromPool = false) where K : LSEntity, IAwake<P1>, new()
{
return this.AddComponentWithId<K, P1>(this.GetId(), p1, isFromPool);
}
public new K AddComponent<K, P1, P2>(P1 p1, P2 p2, bool isFromPool = false) where K : LSEntity, IAwake<P1, P2>, new()
{
return this.AddComponentWithId<K, P1, P2>(this.GetId(), p1, p2, isFromPool);
}
public new K AddComponent<K, P1, P2, P3>(P1 p1, P2 p2, P3 p3, bool isFromPool = false) where K : LSEntity, IAwake<P1, P2, P3>, new()
{
return this.AddComponentWithId<K, P1, P2, P3>(this.GetId(), p1, p2, p3, isFromPool);
}
public new T AddChild<T>(bool isFromPool = false) where T : LSEntity, IAwake
{
return this.AddChildWithId<T>(this.GetId(), isFromPool);
}
public new T AddChild<T, A>(A a, bool isFromPool = false) where T : LSEntity, IAwake<A>
{
return this.AddChildWithId<T, A>(this.GetId(), a, isFromPool);
}
public new T AddChild<T, A, B>(A a, B b, bool isFromPool = false) where T : LSEntity, IAwake<A, B>
{
return this.AddChildWithId<T, A, B>(this.GetId(), a, b, isFromPool);
}
public new T AddChild<T, A, B, C>(A a, B b, C c, bool isFromPool = false) where T : LSEntity, IAwake<A, B, C>
{
return this.AddChildWithId<T, A, B, C>(this.GetId(), a, b, c, isFromPool);
}
protected override long GetLongHashCode(Type type)
{
return LSEntitySystemSingleton.Instance.GetLongHashCode(type);
}
}
} | ET/Unity/Assets/Scripts/Model/Share/LockStep/LSWorld.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Model/Share/LockStep/LSWorld.cs",
"repo_id": "ET",
"token_count": 1773
} | 149 |
using System;
using System.Collections.Generic;
namespace ET
{
[Code]
public class AIDispatcherComponent: Singleton<AIDispatcherComponent>, ISingletonAwake
{
private readonly Dictionary<string, AAIHandler> aiHandlers = new();
public void Awake()
{
var types = CodeTypes.Instance.GetTypes(typeof (AIHandlerAttribute));
foreach (Type type in types)
{
AAIHandler aaiHandler = Activator.CreateInstance(type) as AAIHandler;
if (aaiHandler == null)
{
Log.Error($"robot ai is not AAIHandler: {type.Name}");
continue;
}
this.aiHandlers.Add(type.Name, aaiHandler);
}
}
public AAIHandler Get(string key)
{
this.aiHandlers.TryGetValue(key, out var aaiHandler);
return aaiHandler;
}
}
} | ET/Unity/Assets/Scripts/Model/Share/Module/AI/AIDispatcherComponent.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/AI/AIDispatcherComponent.cs",
"repo_id": "ET",
"token_count": 479
} | 150 |
using System;
namespace ET
{
public interface IMessageSessionHandler
{
void Handle(Session session, object message);
Type GetMessageType();
Type GetResponseType();
}
} | ET/Unity/Assets/Scripts/Model/Share/Module/Message/IMessageSessionHandler.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Message/IMessageSessionHandler.cs",
"repo_id": "ET",
"token_count": 75
} | 151 |
namespace ET
{
// 刚accept的session只持续5秒,必须通过验证,否则断开
[ComponentOf(typeof(Session))]
public class SessionAcceptTimeoutComponent: Entity, IAwake, IDestroy
{
public long Timer;
}
} | ET/Unity/Assets/Scripts/Model/Share/Module/Message/SessionAcceptTimeoutComponent.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Message/SessionAcceptTimeoutComponent.cs",
"repo_id": "ET",
"token_count": 118
} | 152 |
using System;
namespace ET
{
[AttributeUsage(AttributeTargets.Class)]
public class NumericWatcherAttribute : BaseAttribute
{
public SceneType SceneType { get; }
public int NumericType { get; }
public NumericWatcherAttribute(SceneType sceneType, int type)
{
this.SceneType = sceneType;
this.NumericType = type;
}
}
} | ET/Unity/Assets/Scripts/Model/Share/Module/Numeric/NumericWatcherAttribute.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Numeric/NumericWatcherAttribute.cs",
"repo_id": "ET",
"token_count": 123
} | 153 |
using System.Diagnostics;
using MongoDB.Bson.Serialization.Attributes;
using Unity.Mathematics;
namespace ET
{
[ChildOf(typeof(UnitComponent))]
[DebuggerDisplay("ViewName,nq")]
public partial class Unit: Entity, IAwake<int>
{
public int ConfigId { get; set; } //配置表id
[BsonElement]
private float3 position; //坐标
[BsonIgnore]
public float3 Position
{
get => this.position;
set
{
float3 oldPos = this.position;
this.position = value;
EventSystem.Instance.Publish(this.Scene(), new ChangePosition() { Unit = this, OldPos = oldPos });
}
}
[BsonIgnore]
public float3 Forward
{
get => math.mul(this.Rotation, math.forward());
set => this.Rotation = quaternion.LookRotation(value, math.up());
}
[BsonElement]
private quaternion rotation;
[BsonIgnore]
public quaternion Rotation
{
get => this.rotation;
set
{
this.rotation = value;
EventSystem.Instance.Publish(this.Scene(), new ChangeRotation() { Unit = this });
}
}
protected override string ViewName
{
get
{
return $"{this.GetType().FullName} ({this.Id})";
}
}
}
} | ET/Unity/Assets/Scripts/Model/Share/Module/Unit/Unit.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/Model/Share/Module/Unit/Unit.cs",
"repo_id": "ET",
"token_count": 768
} | 154 |
{
"name": "Unity.Model",
"rootNamespace": "ET",
"references": [
"Unity.ThirdParty",
"Unity.Core",
"Unity.Mathematics",
"MemoryPack"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": true,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [
"UNITY_COMPILE || UNITY_EDITOR"
],
"versionDefines": [],
"noEngineReferences": true
} | ET/Unity/Assets/Scripts/Model/Unity.Model.asmdef/0 | {
"file_path": "ET/Unity/Assets/Scripts/Model/Unity.Model.asmdef",
"repo_id": "ET",
"token_count": 224
} | 155 |
using UnityEngine;
using UnityEngine.UI;
namespace ET.Client
{
[ComponentOf(typeof(UI))]
public class UILobbyComponent : Entity, IAwake
{
public GameObject enterMap;
public Text text;
}
}
| ET/Unity/Assets/Scripts/ModelView/Client/Demo/UI/UILobby/UILobbyComponent.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/ModelView/Client/Demo/UI/UILobby/UILobbyComponent.cs",
"repo_id": "ET",
"token_count": 75
} | 156 |
using System.Collections.Generic;
using UnityEngine;
namespace ET.Client
{
[ComponentOf]
public class LSAnimatorComponent : 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/LockStep/LSAnimatorComponent.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/ModelView/Client/LockStep/LSAnimatorComponent.cs",
"repo_id": "ET",
"token_count": 135
} | 157 |
using UnityEngine;
using UnityEngine.UI;
namespace ET.Client
{
[ComponentOf(typeof(UI))]
public class UILSRoomComponent: Entity, IAwake, IUpdate
{
public Button saveReplay;
public InputField saveName;
public Text totalFrame;
public Text frameText;
public Text predictFrameText;
public InputField jumpToField;
public Button jump;
public Button replaySpeed;
public int frame;
public int predictFrame;
}
} | ET/Unity/Assets/Scripts/ModelView/Client/LockStep/UI/UILSRoom/UILSRoomComponent.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/ModelView/Client/LockStep/UI/UILSRoom/UILSRoomComponent.cs",
"repo_id": "ET",
"token_count": 199
} | 158 |
fileFormatVersion: 2
guid: 871912424dfff414b83ffac903b92716
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/ModelView/Client/Module/UI/UIComponent.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/ModelView/Client/Module/UI/UIComponent.cs.meta",
"repo_id": "ET",
"token_count": 92
} | 159 |
fileFormatVersion: 2
guid: 5aaea4ae92be1594f8eb20d6db2ddf82
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/ThirdParty/DotRecast.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast.meta",
"repo_id": "ET",
"token_count": 70
} | 160 |
fileFormatVersion: 2
guid: ef4176267ba8b1842a1f6b474fcb1936
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/Loader.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/Loader.cs.meta",
"repo_id": "ET",
"token_count": 95
} | 161 |
fileFormatVersion: 2
guid: c84e6e08809926d458b3830320482d42
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcByteOrder.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcByteOrder.cs.meta",
"repo_id": "ET",
"token_count": 93
} | 162 |
fileFormatVersion: 2
guid: 65437c9b2bb5abe4395808f3d5358c6e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcImmutableArray.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Core/RcImmutableArray.cs.meta",
"repo_id": "ET",
"token_count": 96
} | 163 |
namespace DotRecast.Detour.Crowd
{
/// Provides neighbor data for agents managed by the crowd.
/// @ingroup crowd
/// @see dtCrowdAgent::neis, dtCrowd
public readonly struct DtCrowdNeighbour
{
public readonly DtCrowdAgent agent;
/// < The index of the neighbor in the crowd.
public readonly float dist;
/// < The distance between the current agent and the neighbor.
public DtCrowdNeighbour(DtCrowdAgent agent, float dist)
{
this.agent = agent;
this.dist = dist;
}
};
} | ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/DtCrowdNeighbour.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/DtCrowdNeighbour.cs",
"repo_id": "ET",
"token_count": 237
} | 164 |
using DotRecast.Core;
namespace DotRecast.Detour.Crowd
{
public class DtObstacleSegment
{
/** End points of the obstacle segment */
public RcVec3f p = new RcVec3f();
/** End points of the obstacle segment */
public RcVec3f q = new RcVec3f();
public bool touch;
}
} | ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/DtObstacleSegment.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/DtObstacleSegment.cs",
"repo_id": "ET",
"token_count": 144
} | 165 |
fileFormatVersion: 2
guid: 68e95d7709e4e77479c519b6e150a90b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/Tracking/DtCrowdAgentDebugInfo.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Crowd/Tracking/DtCrowdAgentDebugInfo.cs.meta",
"repo_id": "ET",
"token_count": 95
} | 166 |
fileFormatVersion: 2
guid: de753262ef6b4094b8d6460981df9e8d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Dynamic/Colliders/ConvexTrimeshCollider.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Dynamic/Colliders/ConvexTrimeshCollider.cs.meta",
"repo_id": "ET",
"token_count": 95
} | 167 |
/*
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;
using DotRecast.Recast;
namespace DotRecast.Detour.Dynamic
{
/**
* Voxel raycast based on the algorithm described in
*
* "A Fast Voxel Traversal Algorithm for Ray Tracing" by John Amanatides and Andrew Woo
*/
public class VoxelQuery
{
private readonly RcVec3f origin;
private readonly float tileWidth;
private readonly float tileDepth;
private readonly Func<int, int, RcHeightfield> heightfieldProvider;
public VoxelQuery(RcVec3f origin, float tileWidth, float tileDepth, Func<int, int, RcHeightfield> heightfieldProvider)
{
this.origin = origin;
this.tileWidth = tileWidth;
this.tileDepth = tileDepth;
this.heightfieldProvider = heightfieldProvider;
}
/**
* Perform raycast using voxels heightfields.
*
* @return Optional with hit parameter (t) or empty if no hit found
*/
public bool Raycast(RcVec3f start, RcVec3f end, out float hit)
{
return TraverseTiles(start, end, out hit);
}
private bool TraverseTiles(RcVec3f start, RcVec3f end, out float hit)
{
float relStartX = start.x - origin.x;
float relStartZ = start.z - origin.z;
int sx = (int)Math.Floor(relStartX / tileWidth);
int sz = (int)Math.Floor(relStartZ / tileDepth);
int ex = (int)Math.Floor((end.x - origin.x) / tileWidth);
int ez = (int)Math.Floor((end.z - origin.z) / tileDepth);
int dx = ex - sx;
int dz = ez - sz;
int stepX = dx < 0 ? -1 : 1;
int stepZ = dz < 0 ? -1 : 1;
float xRem = (tileWidth + (relStartX % tileWidth)) % tileWidth;
float zRem = (tileDepth + (relStartZ % tileDepth)) % tileDepth;
float tx = end.x - start.x;
float tz = end.z - start.z;
float xOffest = Math.Abs(tx < 0 ? xRem : tileWidth - xRem);
float zOffest = Math.Abs(tz < 0 ? zRem : tileDepth - zRem);
tx = Math.Abs(tx);
tz = Math.Abs(tz);
float tMaxX = xOffest / tx;
float tMaxZ = zOffest / tz;
float tDeltaX = tileWidth / tx;
float tDeltaZ = tileDepth / tz;
float t = 0;
while (true)
{
bool isHit = TraversHeightfield(sx, sz, start, end, t, Math.Min(1, Math.Min(tMaxX, tMaxZ)), out hit);
if (isHit)
{
return true;
}
if ((dx > 0 ? sx >= ex : sx <= ex) && (dz > 0 ? sz >= ez : sz <= ez))
{
break;
}
if (tMaxX < tMaxZ)
{
t = tMaxX;
tMaxX += tDeltaX;
sx += stepX;
}
else
{
t = tMaxZ;
tMaxZ += tDeltaZ;
sz += stepZ;
}
}
return false;
}
private bool TraversHeightfield(int x, int z, RcVec3f start, RcVec3f end, float tMin, float tMax, out float hit)
{
RcHeightfield hf = heightfieldProvider.Invoke(x, z);
if (null != hf)
{
float tx = end.x - start.x;
float ty = end.y - start.y;
float tz = end.z - start.z;
float[] entry = { start.x + tMin * tx, start.y + tMin * ty, start.z + tMin * tz };
float[] exit = { start.x + tMax * tx, start.y + tMax * ty, start.z + tMax * tz };
float relStartX = entry[0] - hf.bmin.x;
float relStartZ = entry[2] - hf.bmin.z;
int sx = (int)Math.Floor(relStartX / hf.cs);
int sz = (int)Math.Floor(relStartZ / hf.cs);
int ex = (int)Math.Floor((exit[0] - hf.bmin.x) / hf.cs);
int ez = (int)Math.Floor((exit[2] - hf.bmin.z) / hf.cs);
int dx = ex - sx;
int dz = ez - sz;
int stepX = dx < 0 ? -1 : 1;
int stepZ = dz < 0 ? -1 : 1;
float xRem = (hf.cs + (relStartX % hf.cs)) % hf.cs;
float zRem = (hf.cs + (relStartZ % hf.cs)) % hf.cs;
float xOffest = Math.Abs(tx < 0 ? xRem : hf.cs - xRem);
float zOffest = Math.Abs(tz < 0 ? zRem : hf.cs - zRem);
tx = Math.Abs(tx);
tz = Math.Abs(tz);
float tMaxX = xOffest / tx;
float tMaxZ = zOffest / tz;
float tDeltaX = hf.cs / tx;
float tDeltaZ = hf.cs / tz;
float t = 0;
while (true)
{
if (sx >= 0 && sx < hf.width && sz >= 0 && sz < hf.height)
{
float y1 = start.y + ty * (tMin + t) - hf.bmin.y;
float y2 = start.y + ty * (tMin + Math.Min(tMaxX, tMaxZ)) - hf.bmin.y;
float ymin = Math.Min(y1, y2) / hf.ch;
float ymax = Math.Max(y1, y2) / hf.ch;
RcSpan span = hf.spans[sx + sz * hf.width];
while (span != null)
{
if (span.smin <= ymin && span.smax >= ymax)
{
hit = Math.Min(1, tMin + t);
return true;
}
span = span.next;
}
}
if ((dx > 0 ? sx >= ex : sx <= ex) && (dz > 0 ? sz >= ez : sz <= ez))
{
break;
}
if (tMaxX < tMaxZ)
{
t = tMaxX;
tMaxX += tDeltaX;
sx += stepX;
}
else
{
t = tMaxZ;
tMaxZ += tDeltaZ;
sz += stepZ;
}
}
}
hit = 0.0f;
return false;
}
}
} | ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Dynamic/VoxelQuery.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Dynamic/VoxelQuery.cs",
"repo_id": "ET",
"token_count": 4087
} | 168 |
using DotRecast.Core;
namespace DotRecast.Detour.Extras.Jumplink
{
public class GroundSample
{
public RcVec3f p = new RcVec3f();
public bool validTrajectory;
public bool validHeight;
}
} | ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/GroundSample.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/GroundSample.cs",
"repo_id": "ET",
"token_count": 100
} | 169 |
namespace DotRecast.Detour.Extras.Jumplink
{
public class JumpSegment
{
public int groundSegment;
public int startSample;
public int samples;
}
} | ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/JumpSegment.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/Jumplink/JumpSegment.cs",
"repo_id": "ET",
"token_count": 78
} | 170 |
/*
recast4j copyright (c) 2015-2019 Piotr Piastucki piotr@jtilia.org
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
namespace DotRecast.Detour.Extras
{
public static class PolyUtils
{
/**
* Find edge shared by 2 polygons within the same tile
*/
public static int FindEdge(DtPoly node, DtPoly neighbour, DtMeshData tile, DtMeshData neighbourTile)
{
// Compare indices first assuming there are no duplicate vertices
for (int i = 0; i < node.vertCount; i++)
{
int j = (i + 1) % node.vertCount;
for (int k = 0; k < neighbour.vertCount; k++)
{
int l = (k + 1) % neighbour.vertCount;
if ((node.verts[i] == neighbour.verts[l] && node.verts[j] == neighbour.verts[k])
|| (node.verts[i] == neighbour.verts[k] && node.verts[j] == neighbour.verts[l]))
{
return i;
}
}
}
// Fall back to comparing actual positions in case of duplicate vertices
for (int i = 0; i < node.vertCount; i++)
{
int j = (i + 1) % node.vertCount;
for (int k = 0; k < neighbour.vertCount; k++)
{
int l = (k + 1) % neighbour.vertCount;
if ((SamePosition(tile.verts, node.verts[i], neighbourTile.verts, neighbour.verts[l])
&& SamePosition(tile.verts, node.verts[j], neighbourTile.verts, neighbour.verts[k]))
|| (SamePosition(tile.verts, node.verts[i], neighbourTile.verts, neighbour.verts[k])
&& SamePosition(tile.verts, node.verts[j], neighbourTile.verts, neighbour.verts[l])))
{
return i;
}
}
}
return -1;
}
private static bool SamePosition(float[] verts, int v, float[] verts2, int v2)
{
for (int i = 0; i < 3; i++)
{
if (verts[3 * v + i] != verts2[3 * v2 + 1])
{
return false;
}
}
return true;
}
/**
* Find edge closest to the given coordinate
*/
public static int FindEdge(DtPoly node, DtMeshData tile, float value, int comp)
{
float error = float.MaxValue;
int edge = 0;
for (int i = 0; i < node.vertCount; i++)
{
int j = (i + 1) % node.vertCount;
float v1 = tile.verts[3 * node.verts[i] + comp] - value;
float v2 = tile.verts[3 * node.verts[j] + comp] - value;
float d = v1 * v1 + v2 * v2;
if (d < error)
{
error = d;
edge = i;
}
}
return edge;
}
}
} | ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/PolyUtils.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.Extras/PolyUtils.cs",
"repo_id": "ET",
"token_count": 1840
} | 171 |
fileFormatVersion: 2
guid: 0b3773df0ab70d448ab20cb61a5f44b5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.TileCache/DtTileCacheBuilder.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour.TileCache/DtTileCacheBuilder.cs.meta",
"repo_id": "ET",
"token_count": 95
} | 172 |
namespace DotRecast.Detour
{
public class BVItem
{
public readonly int[] bmin = new int[3];
public readonly int[] bmax = new int[3];
public int i;
};
} | ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/BVItem.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/BVItem.cs",
"repo_id": "ET",
"token_count": 88
} | 173 |
using System.Runtime.InteropServices;
namespace DotRecast.Detour
{
public readonly struct DtConnectPoly
{
public readonly long refs;
public readonly float tmin;
public readonly float tmax;
public DtConnectPoly(long refs, float tmin, float tmax)
{
this.refs = refs;
this.tmin = tmin;
this.tmax = tmax;
}
}
} | ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtConnectPoly.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtConnectPoly.cs",
"repo_id": "ET",
"token_count": 197
} | 174 |
/*
Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
recast4j copyright (c) 2015-2019 Piotr Piastucki piotr@jtilia.org
DotRecast Copyright (c) 2023 Choi Ikpil ikpil@naver.com
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
using System;
using DotRecast.Core;
namespace DotRecast.Detour
{
using static DotRecast.Core.RcMath;
public static class DtNavMeshBuilder
{
const int MESH_NULL_IDX = 0xffff;
private static int[][] CalcExtends(BVItem[] items, int nitems, int imin, int imax)
{
int[] bmin = new int[3];
int[] bmax = new int[3];
bmin[0] = items[imin].bmin[0];
bmin[1] = items[imin].bmin[1];
bmin[2] = items[imin].bmin[2];
bmax[0] = items[imin].bmax[0];
bmax[1] = items[imin].bmax[1];
bmax[2] = items[imin].bmax[2];
for (int i = imin + 1; i < imax; ++i)
{
BVItem it = items[i];
if (it.bmin[0] < bmin[0])
bmin[0] = it.bmin[0];
if (it.bmin[1] < bmin[1])
bmin[1] = it.bmin[1];
if (it.bmin[2] < bmin[2])
bmin[2] = it.bmin[2];
if (it.bmax[0] > bmax[0])
bmax[0] = it.bmax[0];
if (it.bmax[1] > bmax[1])
bmax[1] = it.bmax[1];
if (it.bmax[2] > bmax[2])
bmax[2] = it.bmax[2];
}
return new int[][] { bmin, bmax };
}
private static int LongestAxis(int x, int y, int z)
{
int axis = 0;
int maxVal = x;
if (y > maxVal)
{
axis = 1;
maxVal = y;
}
if (z > maxVal)
{
axis = 2;
maxVal = z;
}
return axis;
}
public static int Subdivide(BVItem[] items, int nitems, int imin, int imax, int curNode, DtBVNode[] nodes)
{
int inum = imax - imin;
int icur = curNode;
DtBVNode node = new DtBVNode();
nodes[curNode++] = node;
if (inum == 1)
{
// Leaf
node.bmin[0] = items[imin].bmin[0];
node.bmin[1] = items[imin].bmin[1];
node.bmin[2] = items[imin].bmin[2];
node.bmax[0] = items[imin].bmax[0];
node.bmax[1] = items[imin].bmax[1];
node.bmax[2] = items[imin].bmax[2];
node.i = items[imin].i;
}
else
{
// Split
int[][] minmax = CalcExtends(items, nitems, imin, imax);
node.bmin = minmax[0];
node.bmax = minmax[1];
int axis = LongestAxis(node.bmax[0] - node.bmin[0], node.bmax[1] - node.bmin[1],
node.bmax[2] - node.bmin[2]);
if (axis == 0)
{
// Sort along x-axis
Array.Sort(items, imin, inum, BVItemXComparer.Shared);
}
else if (axis == 1)
{
// Sort along y-axis
Array.Sort(items, imin, inum, BVItemYComparer.Shared);
}
else
{
// Sort along z-axis
Array.Sort(items, imin, inum, BVItemZComparer.Shared);
}
int isplit = imin + inum / 2;
// Left
curNode = Subdivide(items, nitems, imin, isplit, curNode, nodes);
// Right
curNode = Subdivide(items, nitems, isplit, imax, curNode, nodes);
int iescape = curNode - icur;
// Negative index means escape.
node.i = -iescape;
}
return curNode;
}
private static int CreateBVTree(DtNavMeshCreateParams option, DtBVNode[] nodes)
{
// Build tree
float quantFactor = 1 / option.cs;
BVItem[] items = new BVItem[option.polyCount];
for (int i = 0; i < option.polyCount; i++)
{
BVItem it = new BVItem();
items[i] = it;
it.i = i;
// Calc polygon bounds. Use detail meshes if available.
if (option.detailMeshes != null)
{
int vb = option.detailMeshes[i * 4 + 0];
int ndv = option.detailMeshes[i * 4 + 1];
RcVec3f bmin = new RcVec3f();
RcVec3f bmax = new RcVec3f();
int dv = vb * 3;
bmin.Set(option.detailVerts, dv);
bmax.Set(option.detailVerts, dv);
for (int j = 1; j < ndv; j++)
{
bmin.Min(option.detailVerts, dv + j * 3);
bmax.Max(option.detailVerts, dv + j * 3);
}
// BV-tree uses cs for all dimensions
it.bmin[0] = Clamp((int)((bmin.x - option.bmin.x) * quantFactor), 0, int.MaxValue);
it.bmin[1] = Clamp((int)((bmin.y - option.bmin.y) * quantFactor), 0, int.MaxValue);
it.bmin[2] = Clamp((int)((bmin.z - option.bmin.z) * quantFactor), 0, int.MaxValue);
it.bmax[0] = Clamp((int)((bmax.x - option.bmin.x) * quantFactor), 0, int.MaxValue);
it.bmax[1] = Clamp((int)((bmax.y - option.bmin.y) * quantFactor), 0, int.MaxValue);
it.bmax[2] = Clamp((int)((bmax.z - option.bmin.z) * quantFactor), 0, int.MaxValue);
}
else
{
int p = i * option.nvp * 2;
it.bmin[0] = it.bmax[0] = option.verts[option.polys[p] * 3 + 0];
it.bmin[1] = it.bmax[1] = option.verts[option.polys[p] * 3 + 1];
it.bmin[2] = it.bmax[2] = option.verts[option.polys[p] * 3 + 2];
for (int j = 1; j < option.nvp; ++j)
{
if (option.polys[p + j] == MESH_NULL_IDX)
break;
int x = option.verts[option.polys[p + j] * 3 + 0];
int y = option.verts[option.polys[p + j] * 3 + 1];
int z = option.verts[option.polys[p + j] * 3 + 2];
if (x < it.bmin[0])
it.bmin[0] = x;
if (y < it.bmin[1])
it.bmin[1] = y;
if (z < it.bmin[2])
it.bmin[2] = z;
if (x > it.bmax[0])
it.bmax[0] = x;
if (y > it.bmax[1])
it.bmax[1] = y;
if (z > it.bmax[2])
it.bmax[2] = z;
}
// Remap y
it.bmin[1] = (int)Math.Floor(it.bmin[1] * option.ch * quantFactor);
it.bmax[1] = (int)Math.Ceiling(it.bmax[1] * option.ch * quantFactor);
}
}
return Subdivide(items, option.polyCount, 0, option.polyCount, 0, nodes);
}
const int XP = 1 << 0;
const int ZP = 1 << 1;
const int XM = 1 << 2;
const int ZM = 1 << 3;
public static int ClassifyOffMeshPoint(RcVec3f pt, RcVec3f bmin, RcVec3f bmax)
{
int outcode = 0;
outcode |= (pt.x >= bmax.x) ? XP : 0;
outcode |= (pt.z >= bmax.z) ? ZP : 0;
outcode |= (pt.x < bmin.x) ? XM : 0;
outcode |= (pt.z < bmin.z) ? ZM : 0;
switch (outcode)
{
case XP:
return 0;
case XP | ZP:
return 1;
case ZP:
return 2;
case XM | ZP:
return 3;
case XM:
return 4;
case XM | ZM:
return 5;
case ZM:
return 6;
case XP | ZM:
return 7;
}
return 0xff;
}
/**
* Builds navigation mesh tile data from the provided tile creation data.
*
* @param option
* Tile creation data.
*
* @return created tile data
*/
public static DtMeshData CreateNavMeshData(DtNavMeshCreateParams option)
{
if (option.vertCount >= 0xffff)
return null;
if (option.vertCount == 0 || option.verts == null)
return null;
if (option.polyCount == 0 || option.polys == null)
return null;
int nvp = option.nvp;
// Classify off-mesh connection points. We store only the connections
// whose start point is inside the tile.
int[] offMeshConClass = null;
int storedOffMeshConCount = 0;
int offMeshConLinkCount = 0;
if (option.offMeshConCount > 0)
{
offMeshConClass = new int[option.offMeshConCount * 2];
// Find tight heigh bounds, used for culling out off-mesh start
// locations.
float hmin = float.MaxValue;
float hmax = -float.MaxValue;
if (option.detailVerts != null && option.detailVertsCount != 0)
{
for (int i = 0; i < option.detailVertsCount; ++i)
{
float h = option.detailVerts[i * 3 + 1];
hmin = Math.Min(hmin, h);
hmax = Math.Max(hmax, h);
}
}
else
{
for (int i = 0; i < option.vertCount; ++i)
{
int iv = i * 3;
float h = option.bmin.y + option.verts[iv + 1] * option.ch;
hmin = Math.Min(hmin, h);
hmax = Math.Max(hmax, h);
}
}
hmin -= option.walkableClimb;
hmax += option.walkableClimb;
RcVec3f bmin = new RcVec3f();
RcVec3f bmax = new RcVec3f();
bmin = option.bmin;
bmax = option.bmax;
bmin.y = hmin;
bmax.y = hmax;
for (int i = 0; i < option.offMeshConCount; ++i)
{
var p0 = RcVec3f.Of(option.offMeshConVerts, (i * 2 + 0) * 3);
var p1 = RcVec3f.Of(option.offMeshConVerts, (i * 2 + 1) * 3);
offMeshConClass[i * 2 + 0] = ClassifyOffMeshPoint(p0, bmin, bmax);
offMeshConClass[i * 2 + 1] = ClassifyOffMeshPoint(p1, bmin, bmax);
// Zero out off-mesh start positions which are not even
// potentially touching the mesh.
if (offMeshConClass[i * 2 + 0] == 0xff)
{
if (p0.y < bmin.y || p0.y > bmax.y)
offMeshConClass[i * 2 + 0] = 0;
}
// Count how many links should be allocated for off-mesh
// connections.
if (offMeshConClass[i * 2 + 0] == 0xff)
offMeshConLinkCount++;
if (offMeshConClass[i * 2 + 1] == 0xff)
offMeshConLinkCount++;
if (offMeshConClass[i * 2 + 0] == 0xff)
storedOffMeshConCount++;
}
}
// Off-mesh connections are stored as polygons, adjust values.
int totPolyCount = option.polyCount + storedOffMeshConCount;
int totVertCount = option.vertCount + storedOffMeshConCount * 2;
// Find portal edges which are at tile borders.
int edgeCount = 0;
int portalCount = 0;
for (int i = 0; i < option.polyCount; ++i)
{
int p = i * 2 * nvp;
for (int j = 0; j < nvp; ++j)
{
if (option.polys[p + j] == MESH_NULL_IDX)
break;
edgeCount++;
if ((option.polys[p + nvp + j] & 0x8000) != 0)
{
int dir = option.polys[p + nvp + j] & 0xf;
if (dir != 0xf)
portalCount++;
}
}
}
int maxLinkCount = edgeCount + portalCount * 2 + offMeshConLinkCount * 2;
// Find unique detail vertices.
int uniqueDetailVertCount = 0;
int detailTriCount = 0;
if (option.detailMeshes != null)
{
// Has detail mesh, count unique detail vertex count and use input
// detail tri count.
detailTriCount = option.detailTriCount;
for (int i = 0; i < option.polyCount; ++i)
{
int p = i * nvp * 2;
int ndv = option.detailMeshes[i * 4 + 1];
int nv = 0;
for (int j = 0; j < nvp; ++j)
{
if (option.polys[p + j] == MESH_NULL_IDX)
break;
nv++;
}
ndv -= nv;
uniqueDetailVertCount += ndv;
}
}
else
{
// No input detail mesh, build detail mesh from nav polys.
uniqueDetailVertCount = 0; // No extra detail verts.
detailTriCount = 0;
for (int i = 0; i < option.polyCount; ++i)
{
int p = i * nvp * 2;
int nv = 0;
for (int j = 0; j < nvp; ++j)
{
if (option.polys[p + j] == MESH_NULL_IDX)
break;
nv++;
}
detailTriCount += nv - 2;
}
}
int bvTreeSize = option.buildBvTree ? option.polyCount * 2 : 0;
DtMeshHeader header = new DtMeshHeader();
float[] navVerts = new float[3 * totVertCount];
DtPoly[] navPolys = new DtPoly[totPolyCount];
DtPolyDetail[] navDMeshes = new DtPolyDetail[option.polyCount];
float[] navDVerts = new float[3 * uniqueDetailVertCount];
int[] navDTris = new int[4 * detailTriCount];
DtBVNode[] navBvtree = new DtBVNode[bvTreeSize];
DtOffMeshConnection[] offMeshCons = new DtOffMeshConnection[storedOffMeshConCount];
// Store header
header.magic = DtMeshHeader.DT_NAVMESH_MAGIC;
header.version = DtMeshHeader.DT_NAVMESH_VERSION;
header.x = option.tileX;
header.y = option.tileZ;
header.layer = option.tileLayer;
header.userId = option.userId;
header.polyCount = totPolyCount;
header.vertCount = totVertCount;
header.maxLinkCount = maxLinkCount;
header.bmin = option.bmin;
header.bmax = option.bmax;
header.detailMeshCount = option.polyCount;
header.detailVertCount = uniqueDetailVertCount;
header.detailTriCount = detailTriCount;
header.bvQuantFactor = 1.0f / option.cs;
header.offMeshBase = option.polyCount;
header.walkableHeight = option.walkableHeight;
header.walkableRadius = option.walkableRadius;
header.walkableClimb = option.walkableClimb;
header.offMeshConCount = storedOffMeshConCount;
header.bvNodeCount = bvTreeSize;
int offMeshVertsBase = option.vertCount;
int offMeshPolyBase = option.polyCount;
// Store vertices
// Mesh vertices
for (int i = 0; i < option.vertCount; ++i)
{
int iv = i * 3;
int v = i * 3;
navVerts[v] = option.bmin.x + option.verts[iv] * option.cs;
navVerts[v + 1] = option.bmin.y + option.verts[iv + 1] * option.ch;
navVerts[v + 2] = option.bmin.z + option.verts[iv + 2] * option.cs;
}
// Off-mesh link vertices.
int n = 0;
for (int i = 0; i < option.offMeshConCount; ++i)
{
// Only store connections which start from this tile.
if (offMeshConClass[i * 2 + 0] == 0xff)
{
int linkv = i * 2 * 3;
int v = (offMeshVertsBase + n * 2) * 3;
Array.Copy(option.offMeshConVerts, linkv, navVerts, v, 6);
n++;
}
}
// Store polygons
// Mesh polys
int src = 0;
for (int i = 0; i < option.polyCount; ++i)
{
DtPoly p = new DtPoly(i, nvp);
navPolys[i] = p;
p.vertCount = 0;
p.flags = option.polyFlags[i];
p.SetArea(option.polyAreas[i]);
p.SetPolyType(DtPoly.DT_POLYTYPE_GROUND);
for (int j = 0; j < nvp; ++j)
{
if (option.polys[src + j] == MESH_NULL_IDX)
break;
p.verts[j] = option.polys[src + j];
if ((option.polys[src + nvp + j] & 0x8000) != 0)
{
// Border or portal edge.
int dir = option.polys[src + nvp + j] & 0xf;
if (dir == 0xf) // Border
p.neis[j] = 0;
else if (dir == 0) // Portal x-
p.neis[j] = DtNavMesh.DT_EXT_LINK | 4;
else if (dir == 1) // Portal z+
p.neis[j] = DtNavMesh.DT_EXT_LINK | 2;
else if (dir == 2) // Portal x+
p.neis[j] = DtNavMesh.DT_EXT_LINK | 0;
else if (dir == 3) // Portal z-
p.neis[j] = DtNavMesh.DT_EXT_LINK | 6;
}
else
{
// Normal connection
p.neis[j] = option.polys[src + nvp + j] + 1;
}
p.vertCount++;
}
src += nvp * 2;
}
// Off-mesh connection vertices.
n = 0;
for (int i = 0; i < option.offMeshConCount; ++i)
{
// Only store connections which start from this tile.
if (offMeshConClass[i * 2 + 0] == 0xff)
{
DtPoly p = new DtPoly(offMeshPolyBase + n, nvp);
navPolys[offMeshPolyBase + n] = p;
p.vertCount = 2;
p.verts[0] = offMeshVertsBase + n * 2;
p.verts[1] = offMeshVertsBase + n * 2 + 1;
p.flags = option.offMeshConFlags[i];
p.SetArea(option.offMeshConAreas[i]);
p.SetPolyType(DtPoly.DT_POLYTYPE_OFFMESH_CONNECTION);
n++;
}
}
// Store detail meshes and vertices.
// The nav polygon vertices are stored as the first vertices on each
// mesh.
// We compress the mesh data by skipping them and using the navmesh
// coordinates.
if (option.detailMeshes != null)
{
int vbase = 0;
for (int i = 0; i < option.polyCount; ++i)
{
DtPolyDetail dtl = new DtPolyDetail();
navDMeshes[i] = dtl;
int vb = option.detailMeshes[i * 4 + 0];
int ndv = option.detailMeshes[i * 4 + 1];
int nv = navPolys[i].vertCount;
dtl.vertBase = vbase;
dtl.vertCount = (ndv - nv);
dtl.triBase = option.detailMeshes[i * 4 + 2];
dtl.triCount = option.detailMeshes[i * 4 + 3];
// Copy vertices except the first 'nv' verts which are equal to
// nav poly verts.
if (ndv - nv != 0)
{
Array.Copy(option.detailVerts, (vb + nv) * 3, navDVerts, vbase * 3, 3 * (ndv - nv));
vbase += ndv - nv;
}
}
// Store triangles.
Array.Copy(option.detailTris, 0, navDTris, 0, 4 * option.detailTriCount);
}
else
{
// Create dummy detail mesh by triangulating polys.
int tbase = 0;
for (int i = 0; i < option.polyCount; ++i)
{
DtPolyDetail dtl = new DtPolyDetail();
navDMeshes[i] = dtl;
int nv = navPolys[i].vertCount;
dtl.vertBase = 0;
dtl.vertCount = 0;
dtl.triBase = tbase;
dtl.triCount = (nv - 2);
// Triangulate polygon (local indices).
for (int j = 2; j < nv; ++j)
{
int t = tbase * 4;
navDTris[t + 0] = 0;
navDTris[t + 1] = (j - 1);
navDTris[t + 2] = j;
// Bit for each edge that belongs to poly boundary.
navDTris[t + 3] = (1 << 2);
if (j == 2)
navDTris[t + 3] |= (1 << 0);
if (j == nv - 1)
navDTris[t + 3] |= (1 << 4);
tbase++;
}
}
}
// Store and create BVtree.
// TODO: take detail mesh into account! use byte per bbox extent?
if (option.buildBvTree)
{
// Do not set header.bvNodeCount set to make it work look exactly the same as in original Detour
header.bvNodeCount = CreateBVTree(option, navBvtree);
}
// Store Off-Mesh connections.
n = 0;
for (int i = 0; i < option.offMeshConCount; ++i)
{
// Only store connections which start from this tile.
if (offMeshConClass[i * 2 + 0] == 0xff)
{
DtOffMeshConnection con = new DtOffMeshConnection();
offMeshCons[n] = con;
con.poly = (offMeshPolyBase + n);
// Copy connection end-points.
int endPts = i * 2 * 3;
Array.Copy(option.offMeshConVerts, endPts, con.pos, 0, 6);
con.rad = option.offMeshConRad[i];
con.flags = option.offMeshConDir[i] != 0 ? DtNavMesh.DT_OFFMESH_CON_BIDIR : 0;
con.side = offMeshConClass[i * 2 + 1];
if (option.offMeshConUserID != null)
con.userId = option.offMeshConUserID[i];
n++;
}
}
DtMeshData nmd = new DtMeshData();
nmd.header = header;
nmd.verts = navVerts;
nmd.polys = navPolys;
nmd.detailMeshes = navDMeshes;
nmd.detailVerts = navDVerts;
nmd.detailTris = navDTris;
nmd.bvTree = navBvtree;
nmd.offMeshCons = offMeshCons;
return nmd;
}
}
} | ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtNavMeshBuilder.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtNavMeshBuilder.cs",
"repo_id": "ET",
"token_count": 15109
} | 175 |
using DotRecast.Core;
namespace DotRecast.Detour
{
public class DtQueryNoOpFilter : IDtQueryFilter
{
public static readonly DtQueryNoOpFilter Shared = new DtQueryNoOpFilter();
private DtQueryNoOpFilter()
{
}
public bool PassFilter(long refs, DtMeshTile tile, DtPoly poly)
{
return true;
}
public float GetCost(RcVec3f pa, RcVec3f pb, long prevRef, DtMeshTile prevTile, DtPoly prevPoly, long curRef,
DtMeshTile curTile, DtPoly curPoly, long nextRef, DtMeshTile nextTile, DtPoly nextPoly)
{
return 0;
}
}
} | ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtQueryNoOpFilter.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/DtQueryNoOpFilter.cs",
"repo_id": "ET",
"token_count": 300
} | 176 |
fileFormatVersion: 2
guid: a403e6d52bac9f54e82aeb34895369c1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/Io/DtMeshSetReader.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/Io/DtMeshSetReader.cs.meta",
"repo_id": "ET",
"token_count": 95
} | 177 |
fileFormatVersion: 2
guid: 7555d7b60be8d16479a0dbf21a80faff
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/PathUtils.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Detour/PathUtils.cs.meta",
"repo_id": "ET",
"token_count": 95
} | 178 |
fileFormatVersion: 2
guid: 316a6545c5aa3b64c8edbac232d4d430
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcContourHoleComparer.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcContourHoleComparer.cs.meta",
"repo_id": "ET",
"token_count": 95
} | 179 |
fileFormatVersion: 2
guid: e820b921c79702c4cb41a044df1955d7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcLayerRegion.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcLayerRegion.cs.meta",
"repo_id": "ET",
"token_count": 94
} | 180 |
fileFormatVersion: 2
guid: 1e808d2b5893de147bd2b47c1d85a268
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcRegion.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RcRegion.cs.meta",
"repo_id": "ET",
"token_count": 95
} | 181 |
fileFormatVersion: 2
guid: 2c927b4f438f7234ba83295a2fc28169
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RecastCommon.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RecastCommon.cs.meta",
"repo_id": "ET",
"token_count": 94
} | 182 |
fileFormatVersion: 2
guid: 1be7bba3f28c1cd4cb767b060b5a0a46
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RecastRasterization.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/DotRecast/Recast/RecastRasterization.cs.meta",
"repo_id": "ET",
"token_count": 97
} | 183 |
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace ET
{
[AsyncMethodBuilder(typeof (AsyncETTaskCompletedMethodBuilder))]
public struct ETTaskCompleted: ICriticalNotifyCompletion
{
[DebuggerHidden]
public ETTaskCompleted GetAwaiter()
{
return this;
}
[DebuggerHidden]
public bool IsCompleted => true;
[DebuggerHidden]
public void GetResult()
{
}
[DebuggerHidden]
public void OnCompleted(Action continuation)
{
}
[DebuggerHidden]
public void UnsafeOnCompleted(Action continuation)
{
}
}
} | ET/Unity/Assets/Scripts/ThirdParty/ETTask/ETTaskCompleted.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/ETTask/ETTaskCompleted.cs",
"repo_id": "ET",
"token_count": 310
} | 184 |
fileFormatVersion: 2
guid: 8268fb22100eff945b4afe255bacc0ea
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/List.cs.meta/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/List.cs.meta",
"repo_id": "ET",
"token_count": 91
} | 185 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace NativeCollection.UnsafeType
{
public unsafe struct MultiMap<T, K> : IEnumerable<MultiMapPair<T, K>>, IDisposable
where T : unmanaged, IEquatable<T>, IComparable<T> where K : unmanaged, IEquatable<K>
{
private UnsafeType.SortedSet<MultiMapPair<T, K>>* _sortedSet;
private FixedSizeMemoryPool* _listMemoryPool;
private NativeStackPool<List<K>>* _listStackPool;
public static MultiMap<T, K>* Create(int poolBlockSize,int listPoolSize)
{
MultiMap<T, K>* multiMap = (MultiMap<T, K>*)NativeMemoryHelper.Alloc((UIntPtr)Unsafe.SizeOf<MultiMap<T, K>>());
multiMap->_sortedSet = UnsafeType.SortedSet<MultiMapPair<T, K>>.Create(poolBlockSize);
multiMap->_listMemoryPool = FixedSizeMemoryPool.Create(poolBlockSize,Unsafe.SizeOf<List<K>>());
multiMap->_listStackPool = NativeStackPool<List<K>>.Create(listPoolSize);
return multiMap;
}
public Span<K> this[T key] {
get
{
var list = new MultiMapPair<T, K>(key);
var node = _sortedSet->FindNode(list);
if (node!=null)
{
return node->Item.Value.WrittenSpan();
}
return Span<K>.Empty;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Add(in T key,in K value)
{
var list = new MultiMapPair<T, K>(key);
var node = _sortedSet->FindNode(list);
if (node != null)
{
list = node->Item;
}
else
{
list = MultiMapPair<T, K>.Create(key,_listMemoryPool,_listStackPool);
_sortedSet->AddRef(list);
}
list.Value.AddRef(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Remove(in T key,in K value)
{
var list = new MultiMapPair<T, K>(key);
var node = _sortedSet->FindNode(list);
if (node == null) return false;
list = node->Item;
if (!list.Value.RemoveRef(value)) return false;
if (list.Value.Count == 0) Remove(key);
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Remove(in T key)
{
var list = new MultiMapPair<T, K>(key);
SortedSet<MultiMapPair<T, K>>.Node* node = _sortedSet->FindNode(list);
if (node == null) return false;
list = node->Item;
var sortedSetRemove = _sortedSet->RemoveRef(list);
list.Dispose(_listMemoryPool,_listStackPool);
return sortedSetRemove;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Clear()
{
using var enumerator = GetEnumerator();
do
{
if (enumerator.CurrentPointer != null)
{
enumerator.CurrentPointer->Item.Dispose(_listMemoryPool,_listStackPool);
}
} while (enumerator.MoveNext());
List<K>* list = _listStackPool->Alloc();
while (list!=null)
{
list->Dispose();
_listMemoryPool->Free(list);
list = _listStackPool->Alloc();
}
_sortedSet->Clear();
_listMemoryPool->ReleaseUnUsedSlabs();
}
public int Count => _sortedSet->Count;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
IEnumerator<MultiMapPair<T, K>> IEnumerable<MultiMapPair<T, K>>.GetEnumerator()
{
return _sortedSet->GetEnumerator();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
IEnumerator IEnumerable.GetEnumerator()
{
return _sortedSet->GetEnumerator();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public UnsafeType.SortedSet<MultiMapPair<T, K>>.Enumerator GetEnumerator()
{
return new UnsafeType.SortedSet<MultiMapPair<T, K>>.Enumerator(_sortedSet);
}
public void Dispose()
{
if (_sortedSet != null)
{
Clear();
_sortedSet->Dispose();
NativeMemoryHelper.Free(_sortedSet);
NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<UnsafeType.SortedSet<MultiMapPair<T, K>>>());
}
if (_listStackPool!=null)
{
_listStackPool->Dispose();
NativeMemoryHelper.Free(_listStackPool);
NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<NativeStackPool<List<K>>>());
}
if (_listMemoryPool!=null)
{
_listMemoryPool->Dispose();
_listMemoryPool = null;
}
}
}
}
| ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/MultiMap/MultiMap.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/MultiMap/MultiMap.cs",
"repo_id": "ET",
"token_count": 2128
} | 186 |
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 UnOrderMap<T,K> : IEnumerable<MapPair<T, K>>
where T : unmanaged, IEquatable<T>, IComparable<T> where K : unmanaged, IEquatable<K>
{
/// <summary>Cutoff point for stackallocs. This corresponds to the number of ints.</summary>
private const int StackAllocThreshold = 100;
/// <summary>
/// When constructing a hashset from an existing collection, it may contain duplicates,
/// so this is used as the max acceptable excess ratio of capacity to count. Note that
/// this is only used on the ctor and not to automatically shrink if the hashset has, e.g,
/// a lot of adds followed by removes. Users must explicitly shrink by calling TrimExcess.
/// This is set to 3 because capacity is acceptable as 2x rounded up to nearest prime.
/// </summary>
private const int ShrinkThreshold = 3;
private const int StartOfFreeList = -3;
private UnOrderMap<T,K>* _self;
private int* _buckets;
private int _bucketLength;
private Entry* _entries;
private int _entryLength;
#if TARGET_64BIT
private ulong _fastModMultiplier;
#endif
private int _count;
private int _freeList;
private int _freeCount;
private int _version;
public static UnOrderMap<T,K>* Create(int capacity = 0)
{
UnOrderMap<T,K>* unOrderMap = (UnOrderMap<T,K>*)NativeMemoryHelper.Alloc((UIntPtr)Unsafe.SizeOf<UnOrderMap<T,K>>());
unOrderMap->_buckets = null;
unOrderMap->_entries = null;
unOrderMap->_self = unOrderMap;
unOrderMap->Initialize(capacity);
return unOrderMap;
}
public K this[T key]
{
get
{
bool contains = TryGetValue(key, out var value);
if (contains)
{
return value;
}
return default;
}
set
{
bool modified = TryInsert(key, value, InsertionBehavior.OverwriteExisting);
Debug.Assert(modified);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Add(T key,K value) => AddRef(key,value);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool AddRef(in T key, in K value) => TryInsert(key,value, InsertionBehavior.ThrowOnExisting);
IEnumerator<MapPair<T, K>> IEnumerable<MapPair<T, K>>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Enumerator GetEnumerator() => new Enumerator(_self);
#region ICollection<T> methods
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Clear()
{
int count = _count;
if (count > 0)
{
Debug.Assert(_buckets != null, "_buckets should be non-null");
Debug.Assert(_entries != null, "_entries should be non-null");
Unsafe.InitBlockUnaligned(_buckets,0,(uint)(Unsafe.SizeOf<int>()*_bucketLength));
Unsafe.InitBlockUnaligned(_entries,0,(uint)(Unsafe.SizeOf<int>()*count));
_count = 0;
_freeList = -1;
_freeCount = 0;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool ContainsKey(T key)
{
return FindItemIndex(key) >= 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool ContainsKeyRef(in T key)
{
return FindItemIndex(key) >= 0;
}
#endregion
public void CopyTo(T[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public bool RemoveRef(in T key)
{
//if (_buckets == null) return false;
var entries = _entries;
Debug.Assert(entries != null, "entries should be non-null");
uint collisionCount = 0;
int last = -1;
int hashCode = key.GetHashCode();
ref int bucket = ref GetBucketRef(hashCode);
int i = bucket - 1; // Value in buckets is 1-based
while (i >= 0)
{
ref Entry entry = ref entries[i];
if (entry.HashCode == hashCode && (key.Equals(entry.Key)))
{
if (last < 0)
{
bucket = entry.Next + 1; // Value in buckets is 1-based
}
else
{
entries[last].Next = entry.Next;
}
Debug.Assert((StartOfFreeList - _freeList) < 0, "shouldn't underflow because max hashtable length is MaxPrimeArrayLength = 0x7FEFFFFD(2146435069) _freelist underflow threshold 2147483646");
entry.Next = StartOfFreeList - _freeList;
_freeList = i;
_freeCount++;
return true;
}
last = i;
i = entry.Next;
collisionCount++;
if (collisionCount > (uint)_entryLength)
{
// The chain of entries forms a loop; which means a concurrent update has happened.
// Break out of the loop and throw, rather than looping forever.
ThrowHelper.ConcurrentOperationsNotSupported();
}
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Remove(T item)
{
return RemoveRef(item);
}
public bool TryGetValue(in T key, out K actualValue)
{
int index = FindItemIndex(key);
if (index>=0)
{
actualValue = _entries[index].Value;
return true;
}
actualValue = default;
return false;
}
public int Count => _count - _freeCount;
public void Dispose()
{
NativeMemoryHelper.Free(_buckets);
NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<int>()*_bucketLength);
NativeMemoryHelper.Free(_entries);
NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<Entry>()*_entryLength);
}
#region Helper methods
/// <summary>
/// Initializes buckets and slots arrays. Uses suggested capacity by finding next prime
/// greater than or equal to capacity.
/// </summary>
private int Initialize(int capacity)
{
int size = HashHelpers.GetPrime(capacity);
_buckets = (int*)NativeMemoryHelper.AllocZeroed((UIntPtr)(Unsafe.SizeOf<int>() * size));
_bucketLength = size;
_entries = (Entry*)NativeMemoryHelper.AllocZeroed((UIntPtr)(Unsafe.SizeOf<Entry>() * size));
_entryLength = size;
// Assign member variables after both arrays are allocated to guard against corruption from OOM if second fails.
_freeList = -1;
_freeCount = 0;
_count = 0;
_version = 0;
#if TARGET_64BIT
_fastModMultiplier = HashHelpers.GetFastModMultiplier((uint)size);
#endif
return size;
}
/// <summary>Adds the specified element to the set if it's not already contained.</summary>
/// <param name="value">The element to add to the set.</param>
/// <param name="location">The index into <see cref="_entries" /> of the element.</param>
/// <returns>true if the element is added to the <see cref="HashSet{T}" /> object; false if the element is already present.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool TryInsert(in T key,in K value,InsertionBehavior insertionBehavior)
{
//Console.WriteLine($"AddIfNotPresent:{value}");
//if (_buckets == null) Initialize(0);
Debug.Assert(_buckets != null);
Entry* entries = _entries;
Debug.Assert(entries != null, "expected entries to be non-null");
//var comparer = _comparer;
int hashCode;
uint collisionCount = 0;
ref var bucket = ref Unsafe.NullRef<int>();
hashCode = key.GetHashCode();
bucket = ref GetBucketRef(hashCode);
var i = bucket - 1; // Value in _buckets is 1-based
// Console.WriteLine($"i:{i}");
while (i >= 0)
{
// Console.WriteLine($"i:{i}");
ref Entry entry = ref _entries[i];
// Console.WriteLine($"entry.HashCode:{entry.HashCode} hashCode:{hashCode} Equals:{comparer.Equals(entry.Value, value)}");
if (entry.HashCode == hashCode && entry.Key.Equals(key))
{
if (insertionBehavior== InsertionBehavior.OverwriteExisting)
{
entries[i].Value = value;
return true;
}
if (insertionBehavior == InsertionBehavior.ThrowOnExisting)
{
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException();
}
return false;
}
i = entry.Next;
collisionCount++;
// Console.WriteLine($"collisionCount :{collisionCount} i:{i}");
if (collisionCount > (uint)_entryLength)
// The chain of entries forms a loop, which means a concurrent update has happened.
ThrowHelper.ConcurrentOperationsNotSupported();
}
int index;
if (_freeCount > 0)
{
index = _freeList;
_freeCount--;
Debug.Assert(StartOfFreeList - _entries[_freeList].Next >= -1,
"shouldn't overflow because `next` cannot underflow");
_freeList = StartOfFreeList - _entries[_freeList].Next;
}
else
{
var count = _count;
if (count == _entryLength)
{
Resize();
bucket = ref GetBucketRef(hashCode);
}
index = count;
_count = count + 1;
}
{
ref Entry entry = ref _entries[index];
entry.HashCode = hashCode;
entry.Next = bucket - 1; // Value in _buckets is 1-based
entry.Key = key;
entry.Value = value;
bucket = index + 1;
_version++;
}
return true;
}
/// <summary>Gets a reference to the specified hashcode's bucket, containing an index into <see cref="_entries"/>.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private ref int GetBucketRef(int hashCode)
{
//var buckets = _buckets;
#if TARGET_64BIT
return ref _buckets[HashHelpers.FastMod((uint)hashCode, (uint)_buckets.Length, _fastModMultiplier)];
#else
int index = (int)((uint)hashCode %(uint)_bucketLength);
return ref _buckets[index];
#endif
}
#endregion
/// <summary>Ensures that this hash set can hold the specified number of elements without growing.</summary>
public int EnsureCapacity(int capacity)
{
if (capacity < 0)
{
ThrowHelper.HashSetCapacityOutOfRange();
}
int currentCapacity = _entries == null ? 0 : _entryLength;
if (currentCapacity >= capacity)
{
return currentCapacity;
}
if (_buckets == null)
{
return Initialize(capacity);
}
int newSize = HashHelpers.GetPrime(capacity);
Resize(newSize, forceNewHashCodes: false);
return newSize;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void Resize() => Resize(HashHelpers.ExpandPrime(_count), forceNewHashCodes: false);
private void Resize(int newSize, bool forceNewHashCodes)
{
// Console.WriteLine($"before resize:{*self}");
// Value types never rehash
Debug.Assert(!forceNewHashCodes || !typeof(T).IsValueType);
Debug.Assert(_entries != null, "_entries should be non-null");
Debug.Assert(newSize >= _entryLength);
// Console.WriteLine($"Resize newSize:{newSize} byteSize:{Unsafe.SizeOf<Entry>() * newSize}");
var newEntries = (Entry*)NativeMemoryHelper.AllocZeroed((UIntPtr)(Unsafe.SizeOf<Entry>() * newSize));
Unsafe.CopyBlockUnaligned(newEntries,_entries,(uint)(Unsafe.SizeOf<Entry>()*_entryLength));
int count = _count;
// Assign member variables after both arrays allocated to guard against corruption from OOM if second fails
var newBucket = (int*)NativeMemoryHelper.AllocZeroed((UIntPtr)(Unsafe.SizeOf<int>() * newSize));
NativeMemoryHelper.Free(_buckets);
NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<int>()*_bucketLength);
_buckets = newBucket;
_bucketLength = newSize;
#if TARGET_64BIT
_fastModMultiplier = HashHelpers.GetFastModMultiplier((uint)newSize);
#endif
for (int i = 0; i < count; i++)
{
ref Entry entry = ref newEntries[i];
if (entry.Next >= -1)
{
ref int bucket = ref GetBucketRef(entry.HashCode);
entry.Next = bucket - 1; // Value in _buckets is 1-based
// Console.WriteLine($"entry.Next:{entry.Next} bucket:{bucket}");
bucket = i + 1;
}
}
NativeMemoryHelper.Free(_entries);
NativeMemoryHelper.RemoveNativeMemoryByte(Unsafe.SizeOf<Entry>()*_entryLength);
_entries = newEntries;
_entryLength = newSize;
//Console.WriteLine($"after resize:{*self} totalSize:{_entryLength}");
}
/// <summary>Gets the index of the item in <see cref="_entries"/>, or -1 if it's not in the set.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int FindItemIndex(in T key)
{
//if (_buckets == null) return -1;
var entries = _entries;
Debug.Assert(entries != null, "Expected _entries to be initialized");
uint collisionCount = 0;
//IEqualityComparer<T>? comparer = _comparer;
int hashCode = key.GetHashCode();
int i = GetBucketRef(hashCode) - 1; // Value in _buckets is 1-based
while (i >= 0)
{
ref Entry entry = ref entries[i];
if (entry.HashCode == hashCode && key.Equals(entry.Key))
{
return i;
}
i = entry.Next;
collisionCount++;
if (collisionCount > (uint)_entryLength)
{
// The chain of entries forms a loop, which means a concurrent update has happened.
ThrowHelper.ConcurrentOperationsNotSupported();
}
}
return -1;
}
private struct Entry : IEquatable<Entry>
{
public int HashCode;
/// <summary>
/// 0-based index of next entry in chain: -1 means end of chain
/// also encodes whether this entry _itself_ is part of the free list by changing sign and subtracting 3,
/// so -2 means end of free list, -3 means index 0 but on free list, -4 means index 1 but on free list, etc.
/// </summary>
public int Next;
public T Key;
public K Value;
public bool Equals(Entry other)
{
return HashCode == other.HashCode && Next == other.Next && Key.Equals(other.Key);
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (var value in *_self)
{
sb.Append($"{value} ");
}
sb.Append("\n");
return sb.ToString();
}
internal enum InsertionBehavior : byte
{
None,
OverwriteExisting,
ThrowOnExisting,
}
public struct Enumerator : IEnumerator<MapPair<T, K>>
{
private readonly UnOrderMap<T,K>* _unOrderMap;
private readonly int _version;
private int _index;
private MapPair<T, K> _current;
internal Enumerator(UnOrderMap<T,K>* unOrderMap)
{
_unOrderMap = unOrderMap;
_version = unOrderMap->_version;
_index = 0;
_current = default!;
}
public bool MoveNext()
{
if (_version != _unOrderMap->_version)
ThrowHelper.HashSetEnumFailedVersion();
// Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends.
// dictionary.count+1 could be negative if dictionary.count is int.MaxValue
while ((uint)_index < (uint)_unOrderMap->_count)
{
ref Entry entry = ref _unOrderMap->_entries[_index++];
if (entry.Next >= -1)
{
_current = new MapPair<T, K>(entry.Key,entry.Value);
return true;
}
}
_index = _unOrderMap->_count + 1;
_current = default!;
return false;
}
public MapPair<T, K> Current => _current;
public void Dispose()
{
}
object IEnumerator.Current => Current;
public void Reset()
{
if (_version != _unOrderMap->_version)
ThrowHelper.HashSetEnumFailedVersion();
_index = 0;
_current = default!;
}
}
}
}
| ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/UnOrderMap/UnOrderMap.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/NativeCollection/UnsafeType/UnOrderMap/UnOrderMap.cs",
"repo_id": "ET",
"token_count": 8296
} | 187 |
/* Copyright (C) <2009-2011> <Thorben Linneweber, Jitter Physics>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
namespace TrueSync
{
/// <summary>
/// 3x3 Matrix.
/// </summary>
public struct TSMatrix4x4
{
/// <summary>
/// M11
/// </summary>
public FP M11; // 1st row vector
/// <summary>
/// M12
/// </summary>
public FP M12;
/// <summary>
/// M13
/// </summary>
public FP M13;
/// <summary>
/// M14
/// </summary>
public FP M14;
/// <summary>
/// M21
/// </summary>
public FP M21; // 2nd row vector
/// <summary>
/// M22
/// </summary>
public FP M22;
/// <summary>
/// M23
/// </summary>
public FP M23;
/// <summary>
/// M24
/// </summary>
public FP M24;
/// <summary>
/// M31
/// </summary>
public FP M31; // 3rd row vector
/// <summary>
/// M32
/// </summary>
public FP M32;
/// <summary>
/// M33
/// </summary>
public FP M33;
/// <summary>
/// M34
/// </summary>
public FP M34;
/// <summary>
/// M41
/// </summary>
public FP M41; // 4rd row vector
/// <summary>
/// M42
/// </summary>
public FP M42;
/// <summary>
/// M43
/// </summary>
public FP M43;
/// <summary>
/// M44
/// </summary>
public FP M44;
internal static TSMatrix4x4 InternalIdentity;
/// <summary>
/// Identity matrix.
/// </summary>
public static readonly TSMatrix4x4 Identity;
public static readonly TSMatrix4x4 Zero;
static TSMatrix4x4()
{
Zero = new TSMatrix4x4();
Identity = new TSMatrix4x4();
Identity.M11 = FP.One;
Identity.M22 = FP.One;
Identity.M33 = FP.One;
Identity.M44 = FP.One;
InternalIdentity = Identity;
}
/// <summary>
/// Initializes a new instance of the matrix structure.
/// </summary>
/// <param name="m11">m11</param>
/// <param name="m12">m12</param>
/// <param name="m13">m13</param>
/// <param name="m14">m14</param>
/// <param name="m21">m21</param>
/// <param name="m22">m22</param>
/// <param name="m23">m23</param>
/// <param name="m24">m24</param>
/// <param name="m31">m31</param>
/// <param name="m32">m32</param>
/// <param name="m33">m33</param>
/// <param name="m34">m34</param>
/// <param name="m41">m41</param>
/// <param name="m42">m42</param>
/// <param name="m43">m43</param>
/// <param name="m44">m44</param>
public TSMatrix4x4(FP m11, FP m12, FP m13, FP m14,
FP m21, FP m22, FP m23, FP m24,
FP m31, FP m32, FP m33, FP m34,
FP m41, FP m42, FP m43, FP m44)
{
this.M11 = m11;
this.M12 = m12;
this.M13 = m13;
this.M14 = m14;
this.M21 = m21;
this.M22 = m22;
this.M23 = m23;
this.M24 = m24;
this.M31 = m31;
this.M32 = m32;
this.M33 = m33;
this.M34 = m34;
this.M41 = m41;
this.M42 = m42;
this.M43 = m43;
this.M44 = m44;
}
/// <summary>
/// Multiply two matrices. Notice: matrix multiplication is not commutative.
/// </summary>
/// <param name="matrix1">The first matrix.</param>
/// <param name="matrix2">The second matrix.</param>
/// <returns>The product of both matrices.</returns>
public static TSMatrix4x4 Multiply(TSMatrix4x4 matrix1, TSMatrix4x4 matrix2)
{
TSMatrix4x4 result;
TSMatrix4x4.Multiply(ref matrix1, ref matrix2, out result);
return result;
}
/// <summary>
/// Multiply two matrices. Notice: matrix multiplication is not commutative.
/// </summary>
/// <param name="matrix1">The first matrix.</param>
/// <param name="matrix2">The second matrix.</param>
/// <param name="result">The product of both matrices.</param>
public static void Multiply(ref TSMatrix4x4 matrix1, ref TSMatrix4x4 matrix2, out TSMatrix4x4 result)
{
// First row
result.M11 = matrix1.M11 * matrix2.M11 + matrix1.M12 * matrix2.M21 + matrix1.M13 * matrix2.M31 + matrix1.M14 * matrix2.M41;
result.M12 = matrix1.M11 * matrix2.M12 + matrix1.M12 * matrix2.M22 + matrix1.M13 * matrix2.M32 + matrix1.M14 * matrix2.M42;
result.M13 = matrix1.M11 * matrix2.M13 + matrix1.M12 * matrix2.M23 + matrix1.M13 * matrix2.M33 + matrix1.M14 * matrix2.M43;
result.M14 = matrix1.M11 * matrix2.M14 + matrix1.M12 * matrix2.M24 + matrix1.M13 * matrix2.M34 + matrix1.M14 * matrix2.M44;
// Second row
result.M21 = matrix1.M21 * matrix2.M11 + matrix1.M22 * matrix2.M21 + matrix1.M23 * matrix2.M31 + matrix1.M24 * matrix2.M41;
result.M22 = matrix1.M21 * matrix2.M12 + matrix1.M22 * matrix2.M22 + matrix1.M23 * matrix2.M32 + matrix1.M24 * matrix2.M42;
result.M23 = matrix1.M21 * matrix2.M13 + matrix1.M22 * matrix2.M23 + matrix1.M23 * matrix2.M33 + matrix1.M24 * matrix2.M43;
result.M24 = matrix1.M21 * matrix2.M14 + matrix1.M22 * matrix2.M24 + matrix1.M23 * matrix2.M34 + matrix1.M24 * matrix2.M44;
// Third row
result.M31 = matrix1.M31 * matrix2.M11 + matrix1.M32 * matrix2.M21 + matrix1.M33 * matrix2.M31 + matrix1.M34 * matrix2.M41;
result.M32 = matrix1.M31 * matrix2.M12 + matrix1.M32 * matrix2.M22 + matrix1.M33 * matrix2.M32 + matrix1.M34 * matrix2.M42;
result.M33 = matrix1.M31 * matrix2.M13 + matrix1.M32 * matrix2.M23 + matrix1.M33 * matrix2.M33 + matrix1.M34 * matrix2.M43;
result.M34 = matrix1.M31 * matrix2.M14 + matrix1.M32 * matrix2.M24 + matrix1.M33 * matrix2.M34 + matrix1.M34 * matrix2.M44;
// Fourth row
result.M41 = matrix1.M41 * matrix2.M11 + matrix1.M42 * matrix2.M21 + matrix1.M43 * matrix2.M31 + matrix1.M44 * matrix2.M41;
result.M42 = matrix1.M41 * matrix2.M12 + matrix1.M42 * matrix2.M22 + matrix1.M43 * matrix2.M32 + matrix1.M44 * matrix2.M42;
result.M43 = matrix1.M41 * matrix2.M13 + matrix1.M42 * matrix2.M23 + matrix1.M43 * matrix2.M33 + matrix1.M44 * matrix2.M43;
result.M44 = matrix1.M41 * matrix2.M14 + matrix1.M42 * matrix2.M24 + matrix1.M43 * matrix2.M34 + matrix1.M44 * matrix2.M44;
}
/// <summary>
/// Matrices are added.
/// </summary>
/// <param name="matrix1">The first matrix.</param>
/// <param name="matrix2">The second matrix.</param>
/// <returns>The sum of both matrices.</returns>
public static TSMatrix4x4 Add(TSMatrix4x4 matrix1, TSMatrix4x4 matrix2)
{
TSMatrix4x4 result;
TSMatrix4x4.Add(ref matrix1, ref matrix2, out result);
return result;
}
/// <summary>
/// Matrices are added.
/// </summary>
/// <param name="matrix1">The first matrix.</param>
/// <param name="matrix2">The second matrix.</param>
/// <param name="result">The sum of both matrices.</param>
public static void Add(ref TSMatrix4x4 matrix1, ref TSMatrix4x4 matrix2, out TSMatrix4x4 result)
{
result.M11 = matrix1.M11 + matrix2.M11;
result.M12 = matrix1.M12 + matrix2.M12;
result.M13 = matrix1.M13 + matrix2.M13;
result.M14 = matrix1.M14 + matrix2.M14;
result.M21 = matrix1.M21 + matrix2.M21;
result.M22 = matrix1.M22 + matrix2.M22;
result.M23 = matrix1.M23 + matrix2.M23;
result.M24 = matrix1.M24 + matrix2.M24;
result.M31 = matrix1.M31 + matrix2.M31;
result.M32 = matrix1.M32 + matrix2.M32;
result.M33 = matrix1.M33 + matrix2.M33;
result.M34 = matrix1.M34 + matrix2.M34;
result.M41 = matrix1.M41 + matrix2.M41;
result.M42 = matrix1.M42 + matrix2.M42;
result.M43 = matrix1.M43 + matrix2.M43;
result.M44 = matrix1.M44 + matrix2.M44;
}
/// <summary>
/// Calculates the inverse of a give matrix.
/// </summary>
/// <param name="matrix">The matrix to invert.</param>
/// <returns>The inverted JMatrix.</returns>
public static TSMatrix4x4 Inverse(TSMatrix4x4 matrix)
{
TSMatrix4x4 result;
TSMatrix4x4.Inverse(ref matrix, out result);
return result;
}
public FP determinant
{
get
{
// | a b c d | | f g h | | e g h | | e f h | | e f g |
// | e f g h | = a | j k l | - b | i k l | + c | i j l | - d | i j k |
// | i j k l | | n o p | | m o p | | m n p | | m n o |
// | m n o p |
//
// | f g h |
// a | j k l | = a ( f ( kp - lo ) - g ( jp - ln ) + h ( jo - kn ) )
// | n o p |
//
// | e g h |
// b | i k l | = b ( e ( kp - lo ) - g ( ip - lm ) + h ( io - km ) )
// | m o p |
//
// | e f h |
// c | i j l | = c ( e ( jp - ln ) - f ( ip - lm ) + h ( in - jm ) )
// | m n p |
//
// | e f g |
// d | i j k | = d ( e ( jo - kn ) - f ( io - km ) + g ( in - jm ) )
// | m n o |
//
// Cost of operation
// 17 adds and 28 muls.
//
// add: 6 + 8 + 3 = 17
// mul: 12 + 16 = 28
FP a = M11, b = M12, c = M13, d = M14;
FP e = M21, f = M22, g = M23, h = M24;
FP i = M31, j = M32, k = M33, l = M34;
FP m = M41, n = M42, o = M43, p = M44;
FP kp_lo = k * p - l * o;
FP jp_ln = j * p - l * n;
FP jo_kn = j * o - k * n;
FP ip_lm = i * p - l * m;
FP io_km = i * o - k * m;
FP in_jm = i * n - j * m;
return a * (f * kp_lo - g * jp_ln + h * jo_kn) -
b * (e * kp_lo - g * ip_lm + h * io_km) +
c * (e * jp_ln - f * ip_lm + h * in_jm) -
d * (e * jo_kn - f * io_km + g * in_jm);
}
}
/// <summary>
/// Calculates the inverse of a give matrix.
/// </summary>
/// <param name="matrix">The matrix to invert.</param>
/// <param name="result">The inverted JMatrix.</param>
public static void Inverse(ref TSMatrix4x4 matrix, out TSMatrix4x4 result)
{
// -1
// If you have matrix M, inverse Matrix M can compute
//
// -1 1
// M = --------- A
// det(M)
//
// A is adjugate (adjoint) of M, where,
//
// T
// A = C
//
// C is Cofactor matrix of M, where,
// i + j
// C = (-1) * det(M )
// ij ij
//
// [ a b c d ]
// M = [ e f g h ]
// [ i j k l ]
// [ m n o p ]
//
// First Row
// 2 | f g h |
// C = (-1) | j k l | = + ( f ( kp - lo ) - g ( jp - ln ) + h ( jo - kn ) )
// 11 | n o p |
//
// 3 | e g h |
// C = (-1) | i k l | = - ( e ( kp - lo ) - g ( ip - lm ) + h ( io - km ) )
// 12 | m o p |
//
// 4 | e f h |
// C = (-1) | i j l | = + ( e ( jp - ln ) - f ( ip - lm ) + h ( in - jm ) )
// 13 | m n p |
//
// 5 | e f g |
// C = (-1) | i j k | = - ( e ( jo - kn ) - f ( io - km ) + g ( in - jm ) )
// 14 | m n o |
//
// Second Row
// 3 | b c d |
// C = (-1) | j k l | = - ( b ( kp - lo ) - c ( jp - ln ) + d ( jo - kn ) )
// 21 | n o p |
//
// 4 | a c d |
// C = (-1) | i k l | = + ( a ( kp - lo ) - c ( ip - lm ) + d ( io - km ) )
// 22 | m o p |
//
// 5 | a b d |
// C = (-1) | i j l | = - ( a ( jp - ln ) - b ( ip - lm ) + d ( in - jm ) )
// 23 | m n p |
//
// 6 | a b c |
// C = (-1) | i j k | = + ( a ( jo - kn ) - b ( io - km ) + c ( in - jm ) )
// 24 | m n o |
//
// Third Row
// 4 | b c d |
// C = (-1) | f g h | = + ( b ( gp - ho ) - c ( fp - hn ) + d ( fo - gn ) )
// 31 | n o p |
//
// 5 | a c d |
// C = (-1) | e g h | = - ( a ( gp - ho ) - c ( ep - hm ) + d ( eo - gm ) )
// 32 | m o p |
//
// 6 | a b d |
// C = (-1) | e f h | = + ( a ( fp - hn ) - b ( ep - hm ) + d ( en - fm ) )
// 33 | m n p |
//
// 7 | a b c |
// C = (-1) | e f g | = - ( a ( fo - gn ) - b ( eo - gm ) + c ( en - fm ) )
// 34 | m n o |
//
// Fourth Row
// 5 | b c d |
// C = (-1) | f g h | = - ( b ( gl - hk ) - c ( fl - hj ) + d ( fk - gj ) )
// 41 | j k l |
//
// 6 | a c d |
// C = (-1) | e g h | = + ( a ( gl - hk ) - c ( el - hi ) + d ( ek - gi ) )
// 42 | i k l |
//
// 7 | a b d |
// C = (-1) | e f h | = - ( a ( fl - hj ) - b ( el - hi ) + d ( ej - fi ) )
// 43 | i j l |
//
// 8 | a b c |
// C = (-1) | e f g | = + ( a ( fk - gj ) - b ( ek - gi ) + c ( ej - fi ) )
// 44 | i j k |
//
// Cost of operation
// 53 adds, 104 muls, and 1 div.
FP a = matrix.M11, b = matrix.M12, c = matrix.M13, d = matrix.M14;
FP e = matrix.M21, f = matrix.M22, g = matrix.M23, h = matrix.M24;
FP i = matrix.M31, j = matrix.M32, k = matrix.M33, l = matrix.M34;
FP m = matrix.M41, n = matrix.M42, o = matrix.M43, p = matrix.M44;
FP kp_lo = k * p - l * o;
FP jp_ln = j * p - l * n;
FP jo_kn = j * o - k * n;
FP ip_lm = i * p - l * m;
FP io_km = i * o - k * m;
FP in_jm = i * n - j * m;
FP a11 = (f * kp_lo - g * jp_ln + h * jo_kn);
FP a12 = -(e * kp_lo - g * ip_lm + h * io_km);
FP a13 = (e * jp_ln - f * ip_lm + h * in_jm);
FP a14 = -(e * jo_kn - f * io_km + g * in_jm);
FP det = a * a11 + b * a12 + c * a13 + d * a14;
if (det == FP.Zero)
{
result.M11 = FP.PositiveInfinity;
result.M12 = FP.PositiveInfinity;
result.M13 = FP.PositiveInfinity;
result.M14 = FP.PositiveInfinity;
result.M21 = FP.PositiveInfinity;
result.M22 = FP.PositiveInfinity;
result.M23 = FP.PositiveInfinity;
result.M24 = FP.PositiveInfinity;
result.M31 = FP.PositiveInfinity;
result.M32 = FP.PositiveInfinity;
result.M33 = FP.PositiveInfinity;
result.M34 = FP.PositiveInfinity;
result.M41 = FP.PositiveInfinity;
result.M42 = FP.PositiveInfinity;
result.M43 = FP.PositiveInfinity;
result.M44 = FP.PositiveInfinity;
}
else
{
FP invDet = FP.One / det;
result.M11 = a11 * invDet;
result.M21 = a12 * invDet;
result.M31 = a13 * invDet;
result.M41 = a14 * invDet;
result.M12 = -(b * kp_lo - c * jp_ln + d * jo_kn) * invDet;
result.M22 = (a * kp_lo - c * ip_lm + d * io_km) * invDet;
result.M32 = -(a * jp_ln - b * ip_lm + d * in_jm) * invDet;
result.M42 = (a * jo_kn - b * io_km + c * in_jm) * invDet;
FP gp_ho = g * p - h * o;
FP fp_hn = f * p - h * n;
FP fo_gn = f * o - g * n;
FP ep_hm = e * p - h * m;
FP eo_gm = e * o - g * m;
FP en_fm = e * n - f * m;
result.M13 = (b * gp_ho - c * fp_hn + d * fo_gn) * invDet;
result.M23 = -(a * gp_ho - c * ep_hm + d * eo_gm) * invDet;
result.M33 = (a * fp_hn - b * ep_hm + d * en_fm) * invDet;
result.M43 = -(a * fo_gn - b * eo_gm + c * en_fm) * invDet;
FP gl_hk = g * l - h * k;
FP fl_hj = f * l - h * j;
FP fk_gj = f * k - g * j;
FP el_hi = e * l - h * i;
FP ek_gi = e * k - g * i;
FP ej_fi = e * j - f * i;
result.M14 = -(b * gl_hk - c * fl_hj + d * fk_gj) * invDet;
result.M24 = (a * gl_hk - c * el_hi + d * ek_gi) * invDet;
result.M34 = -(a * fl_hj - b * el_hi + d * ej_fi) * invDet;
result.M44 = (a * fk_gj - b * ek_gi + c * ej_fi) * invDet;
}
}
/// <summary>
/// Multiply a matrix by a scalefactor.
/// </summary>
/// <param name="matrix1">The matrix.</param>
/// <param name="scaleFactor">The scale factor.</param>
/// <returns>A JMatrix multiplied by the scale factor.</returns>
public static TSMatrix4x4 Multiply(TSMatrix4x4 matrix1, FP scaleFactor)
{
TSMatrix4x4 result;
TSMatrix4x4.Multiply(ref matrix1, scaleFactor, out result);
return result;
}
/// <summary>
/// Multiply a matrix by a scalefactor.
/// </summary>
/// <param name="matrix1">The matrix.</param>
/// <param name="scaleFactor">The scale factor.</param>
/// <param name="result">A JMatrix multiplied by the scale factor.</param>
public static void Multiply(ref TSMatrix4x4 matrix1, FP scaleFactor, out TSMatrix4x4 result)
{
FP num = scaleFactor;
result.M11 = matrix1.M11 * num;
result.M12 = matrix1.M12 * num;
result.M13 = matrix1.M13 * num;
result.M14 = matrix1.M14 * num;
result.M21 = matrix1.M21 * num;
result.M22 = matrix1.M22 * num;
result.M23 = matrix1.M23 * num;
result.M24 = matrix1.M24 * num;
result.M31 = matrix1.M31 * num;
result.M32 = matrix1.M32 * num;
result.M33 = matrix1.M33 * num;
result.M34 = matrix1.M34 * num;
result.M41 = matrix1.M41 * num;
result.M42 = matrix1.M42 * num;
result.M43 = matrix1.M43 * num;
result.M44 = matrix1.M44 * num;
}
public static TSMatrix4x4 Rotate(TSQuaternion quaternion)
{
TSMatrix4x4 result;
TSMatrix4x4.Rotate(ref quaternion, out result);
return result;
}
/// <summary>
/// Creates a JMatrix representing an orientation from a quaternion.
/// </summary>
/// <param name="quaternion">The quaternion the matrix should be created from.</param>
/// <param name="result">JMatrix representing an orientation.</param>
public static void Rotate(ref TSQuaternion quaternion, out TSMatrix4x4 result)
{
// Precalculate coordinate products
FP x = quaternion.x * 2;
FP y = quaternion.y * 2;
FP z = quaternion.z * 2;
FP xx = quaternion.x * x;
FP yy = quaternion.y * y;
FP zz = quaternion.z * z;
FP xy = quaternion.x * y;
FP xz = quaternion.x * z;
FP yz = quaternion.y * z;
FP wx = quaternion.w * x;
FP wy = quaternion.w * y;
FP wz = quaternion.w * z;
// Calculate 3x3 matrix from orthonormal basis
result.M11 = FP.One - (yy + zz);
result.M21 = xy + wz;
result.M31 = xz - wy;
result.M41 = FP.Zero;
result.M12 = xy - wz;
result.M22 = FP.One - (xx + zz);
result.M32 = yz + wx;
result.M42 = FP.Zero;
result.M13 = xz + wy;
result.M23 = yz - wx;
result.M33 = FP.One - (xx + yy);
result.M43 = FP.Zero;
result.M14 = FP.Zero;
result.M24 = FP.Zero;
result.M34 = FP.Zero;
result.M44 = FP.One;
}
/// <summary>
/// Creates the transposed matrix.
/// </summary>
/// <param name="matrix">The matrix which should be transposed.</param>
/// <returns>The transposed JMatrix.</returns>
public static TSMatrix4x4 Transpose(TSMatrix4x4 matrix)
{
TSMatrix4x4 result;
TSMatrix4x4.Transpose(ref matrix, out result);
return result;
}
/// <summary>
/// Creates the transposed matrix.
/// </summary>
/// <param name="matrix">The matrix which should be transposed.</param>
/// <param name="result">The transposed JMatrix.</param>
public static void Transpose(ref TSMatrix4x4 matrix, out TSMatrix4x4 result)
{
result.M11 = matrix.M11;
result.M12 = matrix.M21;
result.M13 = matrix.M31;
result.M14 = matrix.M41;
result.M21 = matrix.M12;
result.M22 = matrix.M22;
result.M23 = matrix.M32;
result.M24 = matrix.M42;
result.M31 = matrix.M13;
result.M32 = matrix.M23;
result.M33 = matrix.M33;
result.M34 = matrix.M43;
result.M41 = matrix.M14;
result.M42 = matrix.M24;
result.M43 = matrix.M34;
result.M44 = matrix.M44;
}
/// <summary>
/// Multiplies two matrices.
/// </summary>
/// <param name="value1">The first matrix.</param>
/// <param name="value2">The second matrix.</param>
/// <returns>The product of both values.</returns>
public static TSMatrix4x4 operator *(TSMatrix4x4 value1, TSMatrix4x4 value2)
{
TSMatrix4x4 result;
TSMatrix4x4.Multiply(ref value1, ref value2, out result);
return result;
}
public FP Trace()
{
return this.M11 + this.M22 + this.M33 + this.M44;
}
/// <summary>
/// Adds two matrices.
/// </summary>
/// <param name="value1">The first matrix.</param>
/// <param name="value2">The second matrix.</param>
/// <returns>The sum of both values.</returns>
public static TSMatrix4x4 operator +(TSMatrix4x4 value1, TSMatrix4x4 value2)
{
TSMatrix4x4 result;
TSMatrix4x4.Add(ref value1, ref value2, out result);
return result;
}
/// <summary>
/// Returns a new matrix with the negated elements of the given matrix.
/// </summary>
/// <param name="value">The source matrix.</param>
/// <returns>The negated matrix.</returns>
public static TSMatrix4x4 operator -(TSMatrix4x4 value)
{
TSMatrix4x4 result;
result.M11 = -value.M11;
result.M12 = -value.M12;
result.M13 = -value.M13;
result.M14 = -value.M14;
result.M21 = -value.M21;
result.M22 = -value.M22;
result.M23 = -value.M23;
result.M24 = -value.M24;
result.M31 = -value.M31;
result.M32 = -value.M32;
result.M33 = -value.M33;
result.M34 = -value.M34;
result.M41 = -value.M41;
result.M42 = -value.M42;
result.M43 = -value.M43;
result.M44 = -value.M44;
return result;
}
/// <summary>
/// Subtracts two matrices.
/// </summary>
/// <param name="value1">The first matrix.</param>
/// <param name="value2">The second matrix.</param>
/// <returns>The difference of both values.</returns>
public static TSMatrix4x4 operator -(TSMatrix4x4 value1, TSMatrix4x4 value2)
{
TSMatrix4x4 result;
TSMatrix4x4.Multiply(ref value2, -FP.One, out value2);
TSMatrix4x4.Add(ref value1, ref value2, out result);
return result;
}
public static bool operator ==(TSMatrix4x4 value1, TSMatrix4x4 value2)
{
return value1.M11 == value2.M11 &&
value1.M12 == value2.M12 &&
value1.M13 == value2.M13 &&
value1.M14 == value2.M14 &&
value1.M21 == value2.M21 &&
value1.M22 == value2.M22 &&
value1.M23 == value2.M23 &&
value1.M24 == value2.M24 &&
value1.M31 == value2.M31 &&
value1.M32 == value2.M32 &&
value1.M33 == value2.M33 &&
value1.M34 == value2.M34 &&
value1.M41 == value2.M41 &&
value1.M42 == value2.M42 &&
value1.M43 == value2.M43 &&
value1.M44 == value2.M44;
}
public static bool operator !=(TSMatrix4x4 value1, TSMatrix4x4 value2)
{
return value1.M11 != value2.M11 ||
value1.M12 != value2.M12 ||
value1.M13 != value2.M13 ||
value1.M14 != value2.M14 ||
value1.M21 != value2.M21 ||
value1.M22 != value2.M22 ||
value1.M23 != value2.M23 ||
value1.M24 != value2.M24 ||
value1.M31 != value2.M31 ||
value1.M32 != value2.M32 ||
value1.M33 != value2.M33 ||
value1.M34 != value2.M34 ||
value1.M41 != value2.M41 ||
value1.M42 != value2.M42 ||
value1.M43 != value2.M43 ||
value1.M44 != value2.M44;
}
public override bool Equals(object obj)
{
if (!(obj is TSMatrix4x4)) return false;
TSMatrix4x4 other = (TSMatrix4x4)obj;
return this.M11 == other.M11 &&
this.M12 == other.M12 &&
this.M13 == other.M13 &&
this.M14 == other.M14 &&
this.M21 == other.M21 &&
this.M22 == other.M22 &&
this.M23 == other.M23 &&
this.M24 == other.M24 &&
this.M31 == other.M31 &&
this.M32 == other.M32 &&
this.M33 == other.M33 &&
this.M34 == other.M44 &&
this.M41 == other.M41 &&
this.M42 == other.M42 &&
this.M43 == other.M43 &&
this.M44 == other.M44 ;
}
public override int GetHashCode()
{
return M11.GetHashCode() ^
M12.GetHashCode() ^
M13.GetHashCode() ^
M14.GetHashCode() ^
M21.GetHashCode() ^
M22.GetHashCode() ^
M23.GetHashCode() ^
M24.GetHashCode() ^
M31.GetHashCode() ^
M32.GetHashCode() ^
M33.GetHashCode() ^
M34.GetHashCode() ^
M41.GetHashCode() ^
M42.GetHashCode() ^
M43.GetHashCode() ^
M44.GetHashCode();
}
/// <summary>
/// Creates a translation matrix.
/// </summary>
/// <param name="xPosition">The amount to translate on the X-axis.</param>
/// <param name="yPosition">The amount to translate on the Y-axis.</param>
/// <param name="zPosition">The amount to translate on the Z-axis.</param>
/// <returns>The translation matrix.</returns>
public static TSMatrix4x4 Translate(FP xPosition, FP yPosition, FP zPosition)
{
TSMatrix4x4 result;
result.M11 = FP.One; result.M12 = FP.Zero; result.M13 = FP.Zero; result.M14 = xPosition;
result.M21 = FP.Zero; result.M22 = FP.One; result.M23 = FP.Zero; result.M24 = yPosition;
result.M31 = FP.Zero; result.M32 = FP.Zero; result.M33 = FP.One; result.M34 = zPosition;
result.M41 = FP.Zero; result.M42 = FP.Zero; result.M43 = FP.Zero; result.M44 = FP.One;
return result;
}
public static TSMatrix4x4 Translate(TSVector translation)
{
return Translate(translation.x, translation.y, translation.z);
}
/// <summary>
/// Creates a scaling matrix.
/// </summary>
/// <param name="xScale">Value to scale by on the X-axis.</param>
/// <param name="yScale">Value to scale by on the Y-axis.</param>
/// <param name="zScale">Value to scale by on the Z-axis.</param>
/// <returns>The scaling matrix.</returns>
public static TSMatrix4x4 Scale(FP xScale, FP yScale, FP zScale)
{
TSMatrix4x4 result;
result.M11 = xScale; result.M12 = FP.Zero; result.M13 = FP.Zero; result.M14 = FP.Zero;
result.M21 = FP.Zero; result.M22 = yScale; result.M23 = FP.Zero; result.M24 = FP.Zero;
result.M31 = FP.Zero; result.M32 = FP.Zero; result.M33 = zScale; result.M34 = FP.Zero;
result.M41 = FP.Zero; result.M42 = FP.Zero; result.M43 = FP.Zero; result.M44 = FP.One;
return result;
}
/// <summary>
/// Creates a scaling matrix with a center point.
/// </summary>
/// <param name="xScale">Value to scale by on the X-axis.</param>
/// <param name="yScale">Value to scale by on the Y-axis.</param>
/// <param name="zScale">Value to scale by on the Z-axis.</param>
/// <param name="centerPoint">The center point.</param>
/// <returns>The scaling matrix.</returns>
public static TSMatrix4x4 Scale(FP xScale, FP yScale, FP zScale, TSVector centerPoint)
{
TSMatrix4x4 result;
FP tx = centerPoint.x * (FP.One - xScale);
FP ty = centerPoint.y * (FP.One - yScale);
FP tz = centerPoint.z * (FP.One - zScale);
result.M11 = xScale; result.M12 = FP.Zero; result.M13 = FP.Zero; result.M14 = FP.Zero;
result.M21 = FP.Zero; result.M22 = yScale; result.M23 = FP.Zero; result.M24 = FP.Zero;
result.M31 = FP.Zero; result.M32 = FP.Zero; result.M33 = zScale; result.M34 = FP.Zero;
result.M41 = tx; result.M42 = ty; result.M43 = tz; result.M44 = FP.One;
return result;
}
/// <summary>
/// Creates a scaling matrix.
/// </summary>
/// <param name="scales">The vector containing the amount to scale by on each axis.</param>
/// <returns>The scaling matrix.</returns>
public static TSMatrix4x4 Scale(TSVector scales)
{
return Scale(scales.x, scales.y, scales.z);
}
/// <summary>
/// Creates a scaling matrix with a center point.
/// </summary>
/// <param name="scales">The vector containing the amount to scale by on each axis.</param>
/// <param name="centerPoint">The center point.</param>
/// <returns>The scaling matrix.</returns>
public static TSMatrix4x4 Scale(TSVector scales, TSVector centerPoint)
{
return Scale(scales.x, scales.y, scales.z, centerPoint);
}
/// <summary>
/// Creates a uniform scaling matrix that scales equally on each axis.
/// </summary>
/// <param name="scale">The uniform scaling factor.</param>
/// <returns>The scaling matrix.</returns>
public static TSMatrix4x4 Scale(FP scale)
{
return Scale(scale, scale, scale);
}
/// <summary>
/// Creates a uniform scaling matrix that scales equally on each axis with a center point.
/// </summary>
/// <param name="scale">The uniform scaling factor.</param>
/// <param name="centerPoint">The center point.</param>
/// <returns>The scaling matrix.</returns>
public static TSMatrix4x4 Scale(FP scale, TSVector centerPoint)
{
return Scale(scale, scale, scale, centerPoint);
}
/// <summary>
/// Creates a matrix for rotating points around the X-axis.
/// </summary>
/// <param name="radians">The amount, in radians, by which to rotate around the X-axis.</param>
/// <returns>The rotation matrix.</returns>
public static TSMatrix4x4 RotateX(FP radians)
{
TSMatrix4x4 result;
FP c = TSMath.Cos(radians);
FP s = TSMath.Sin(radians);
// [ 1 0 0 0 ]
// [ 0 c s 0 ]
// [ 0 -s c 0 ]
// [ 0 0 0 1 ]
result.M11 = FP.One;
result.M12 = FP.Zero;
result.M13 = FP.Zero;
result.M14 = FP.Zero;
result.M21 = FP.Zero;
result.M22 = c;
result.M23 = s;
result.M24 = FP.Zero;
result.M31 = FP.Zero;
result.M32 = -s;
result.M33 = c;
result.M34 = FP.Zero;
result.M41 = FP.Zero;
result.M42 = FP.Zero;
result.M43 = FP.Zero;
result.M44 = FP.One;
return result;
}
/// <summary>
/// Creates a matrix for rotating points around the X-axis, from a center point.
/// </summary>
/// <param name="radians">The amount, in radians, by which to rotate around the X-axis.</param>
/// <param name="centerPoint">The center point.</param>
/// <returns>The rotation matrix.</returns>
public static TSMatrix4x4 RotateX(FP radians, TSVector centerPoint)
{
TSMatrix4x4 result;
FP c = TSMath.Cos(radians);
FP s = TSMath.Sin(radians);
FP y = centerPoint.y * (FP.One - c) + centerPoint.z * s;
FP z = centerPoint.z * (FP.One - c) - centerPoint.y * s;
// [ 1 0 0 0 ]
// [ 0 c s 0 ]
// [ 0 -s c 0 ]
// [ 0 y z 1 ]
result.M11 = FP.One;
result.M12 = FP.Zero;
result.M13 = FP.Zero;
result.M14 = FP.Zero;
result.M21 = FP.Zero;
result.M22 = c;
result.M23 = s;
result.M24 = FP.Zero;
result.M31 = FP.Zero;
result.M32 = -s;
result.M33 = c;
result.M34 = FP.Zero;
result.M41 = FP.Zero;
result.M42 = y;
result.M43 = z;
result.M44 = FP.One;
return result;
}
/// <summary>
/// Creates a matrix for rotating points around the Y-axis.
/// </summary>
/// <param name="radians">The amount, in radians, by which to rotate around the Y-axis.</param>
/// <returns>The rotation matrix.</returns>
public static TSMatrix4x4 RotateY(FP radians)
{
TSMatrix4x4 result;
FP c = TSMath.Cos(radians);
FP s = TSMath.Sin(radians);
// [ c 0 -s 0 ]
// [ 0 1 0 0 ]
// [ s 0 c 0 ]
// [ 0 0 0 1 ]
result.M11 = c;
result.M12 = FP.Zero;
result.M13 = -s;
result.M14 = FP.Zero;
result.M21 = FP.Zero;
result.M22 = FP.One;
result.M23 = FP.Zero;
result.M24 = FP.Zero;
result.M31 = s;
result.M32 = FP.Zero;
result.M33 = c;
result.M34 = FP.Zero;
result.M41 = FP.Zero;
result.M42 = FP.Zero;
result.M43 = FP.Zero;
result.M44 = FP.One;
return result;
}
/// <summary>
/// Creates a matrix for rotating points around the Y-axis, from a center point.
/// </summary>
/// <param name="radians">The amount, in radians, by which to rotate around the Y-axis.</param>
/// <param name="centerPoint">The center point.</param>
/// <returns>The rotation matrix.</returns>
public static TSMatrix4x4 RotateY(FP radians, TSVector centerPoint)
{
TSMatrix4x4 result;
FP c = TSMath.Cos(radians);
FP s = TSMath.Sin(radians);
FP x = centerPoint.x * (FP.One - c) - centerPoint.z * s;
FP z = centerPoint.x * (FP.One - c) + centerPoint.x * s;
// [ c 0 -s 0 ]
// [ 0 1 0 0 ]
// [ s 0 c 0 ]
// [ x 0 z 1 ]
result.M11 = c;
result.M12 = FP.Zero;
result.M13 = -s;
result.M14 = FP.Zero;
result.M21 = FP.Zero;
result.M22 = FP.One;
result.M23 = FP.Zero;
result.M24 = FP.Zero;
result.M31 = s;
result.M32 = FP.Zero;
result.M33 = c;
result.M34 = FP.Zero;
result.M41 = x;
result.M42 = FP.Zero;
result.M43 = z;
result.M44 = FP.One;
return result;
}
/// <summary>
/// Creates a matrix for rotating points around the Z-axis.
/// </summary>
/// <param name="radians">The amount, in radians, by which to rotate around the Z-axis.</param>
/// <returns>The rotation matrix.</returns>
public static TSMatrix4x4 RotateZ(FP radians)
{
TSMatrix4x4 result;
FP c = TSMath.Cos(radians);
FP s = TSMath.Sin(radians);
// [ c s 0 0 ]
// [ -s c 0 0 ]
// [ 0 0 1 0 ]
// [ 0 0 0 1 ]
result.M11 = c;
result.M12 = s;
result.M13 = FP.Zero;
result.M14 = FP.Zero;
result.M21 = -s;
result.M22 = c;
result.M23 = FP.Zero;
result.M24 = FP.Zero;
result.M31 = FP.Zero;
result.M32 = FP.Zero;
result.M33 = FP.One;
result.M34 = FP.Zero;
result.M41 = FP.Zero;
result.M42 = FP.Zero;
result.M43 = FP.Zero;
result.M44 = FP.One;
return result;
}
/// <summary>
/// Creates a matrix for rotating points around the Z-axis, from a center point.
/// </summary>
/// <param name="radians">The amount, in radians, by which to rotate around the Z-axis.</param>
/// <param name="centerPoint">The center point.</param>
/// <returns>The rotation matrix.</returns>
public static TSMatrix4x4 RotateZ(FP radians, TSVector centerPoint)
{
TSMatrix4x4 result;
FP c = TSMath.Cos(radians);
FP s = TSMath.Sin(radians);
FP x = centerPoint.x * (1 - c) + centerPoint.y * s;
FP y = centerPoint.y * (1 - c) - centerPoint.x * s;
// [ c s 0 0 ]
// [ -s c 0 0 ]
// [ 0 0 1 0 ]
// [ x y 0 1 ]
result.M11 = c;
result.M12 = s;
result.M13 = FP.Zero;
result.M14 = FP.Zero;
result.M21 = -s;
result.M22 = c;
result.M23 = FP.Zero;
result.M24 = FP.Zero;
result.M31 = FP.Zero;
result.M32 = FP.Zero;
result.M33 = FP.One;
result.M34 = FP.Zero;
result.M41 = FP.Zero;
result.M42 = FP.Zero;
result.M43 = FP.Zero;
result.M44 = FP.One;
return result;
}
/// <summary>
/// Creates a matrix which rotates around the given axis by the given angle.
/// </summary>
/// <param name="axis">The axis.</param>
/// <param name="angle">The angle.</param>
/// <param name="result">The resulting rotation matrix</param>
public static void AxisAngle(ref TSVector axis, FP angle, out TSMatrix4x4 result)
{
// a: angle
// x, y, z: unit vector for axis.
//
// Rotation matrix M can compute by using below equation.
//
// T T
// M = uu + (cos a)( I-uu ) + (sin a)S
//
// Where:
//
// u = ( x, y, z )
//
// [ 0 -z y ]
// S = [ z 0 -x ]
// [ -y x 0 ]
//
// [ 1 0 0 ]
// I = [ 0 1 0 ]
// [ 0 0 1 ]
//
//
// [ xx+cosa*(1-xx) yx-cosa*yx-sina*z zx-cosa*xz+sina*y ]
// M = [ xy-cosa*yx+sina*z yy+cosa(1-yy) yz-cosa*yz-sina*x ]
// [ zx-cosa*zx-sina*y zy-cosa*zy+sina*x zz+cosa*(1-zz) ]
//
FP x = axis.x, y = axis.y, z = axis.z;
FP sa = TSMath.Sin(angle), ca = TSMath.Cos(angle);
FP xx = x * x, yy = y * y, zz = z * z;
FP xy = x * y, xz = x * z, yz = y * z;
result.M11 = xx + ca * (FP.One - xx);
result.M12 = xy - ca * xy + sa * z;
result.M13 = xz - ca * xz - sa * y;
result.M14 = FP.Zero;
result.M21 = xy - ca * xy - sa * z;
result.M22 = yy + ca * (FP.One - yy);
result.M23 = yz - ca * yz + sa * x;
result.M24 = FP.Zero;
result.M31 = xz - ca * xz + sa * y;
result.M32 = yz - ca * yz - sa * x;
result.M33 = zz + ca * (FP.One - zz);
result.M34 = FP.Zero;
result.M41 = FP.Zero;
result.M42 = FP.Zero;
result.M43 = FP.Zero;
result.M44 = FP.One;
}
/// <summary>
/// Creates a matrix which rotates around the given axis by the given angle.
/// </summary>
/// <param name="axis">The axis.</param>
/// <param name="angle">The angle.</param>
/// <returns>The resulting rotation matrix</returns>
public static TSMatrix4x4 AngleAxis(FP angle, TSVector axis)
{
TSMatrix4x4 result;
AxisAngle(ref axis, angle, out result);
return result;
}
public override string ToString()
{
return string.Format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|{10}|{11}|{12}|{13}|{14}|{15}",
M11.RawValue, M12.RawValue, M13.RawValue, M14.RawValue,
M21.RawValue, M22.RawValue, M23.RawValue, M24.RawValue,
M31.RawValue, M32.RawValue, M33.RawValue, M34.RawValue,
M41.RawValue, M42.RawValue, M43.RawValue, M44.RawValue);
}
public static void TRS(TSVector translation, TSQuaternion rotation, TSVector scale, out TSMatrix4x4 matrix)
{
matrix = TSMatrix4x4.Translate(translation) * TSMatrix4x4.Rotate(rotation) * TSMatrix4x4.Scale(scale);
}
public static TSMatrix4x4 TRS(TSVector translation, TSQuaternion rotation, TSVector scale)
{
TSMatrix4x4 result;
TRS(translation, rotation, scale, out result);
return result;
}
}
} | ET/Unity/Assets/Scripts/ThirdParty/TrueSync/TSMatrix4x4.cs/0 | {
"file_path": "ET/Unity/Assets/Scripts/ThirdParty/TrueSync/TSMatrix4x4.cs",
"repo_id": "ET",
"token_count": 25028
} | 188 |
fileFormatVersion: 2
guid: 71645c2e495da4f479dc650dcca520a3
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Settings.meta/0 | {
"file_path": "ET/Unity/Assets/Settings.meta",
"repo_id": "ET",
"token_count": 68
} | 189 |
fileFormatVersion: 2
guid: 1d02808fba1938d429693b69b6a091a8
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| ET/Unity/Assets/Settings/IgnoreAsmdef/HotfixView/Client/Ignore.asmdef.DISABLED.meta/0 | {
"file_path": "ET/Unity/Assets/Settings/IgnoreAsmdef/HotfixView/Client/Ignore.asmdef.DISABLED.meta",
"repo_id": "ET",
"token_count": 65
} | 190 |
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1200 &1
AutoStreamingSettings:
m_ObjectHideFlags: 0
serializedVersion: 2
mSearchMode: 7
mCustomSearchFile:
mTextures: []
mAudios: []
mMeshes: []
mScenes: []
mConfigCCD:
useCCD: 0
cosKey:
projectGuid:
bucketUuid:
bucketName:
badgeName:
| ET/Unity/ProjectSettings/AutoStreamingSettings.asset/0 | {
"file_path": "ET/Unity/ProjectSettings/AutoStreamingSettings.asset",
"repo_id": "ET",
"token_count": 154
} | 191 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Management.Automation;
using System.Text;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.TypeSystem;
namespace ICSharpCode.Decompiler.PowerShell
{
[Cmdlet(VerbsCommon.Get, "DecompiledSource")]
[OutputType(typeof(string))]
public class GetDecompiledSourceCmdlet : PSCmdlet
{
[Parameter(Position = 0, Mandatory = true)]
public CSharpDecompiler Decompiler { get; set; }
[Parameter]
public string TypeName { get; set; } = string.Empty;
protected override void ProcessRecord()
{
try
{
StringWriter output = new StringWriter();
if (TypeName == null)
{
output.Write(Decompiler.DecompileWholeModuleAsString());
}
else
{
var name = new FullTypeName(TypeName);
output.Write(Decompiler.DecompileTypeAsString(name));
}
WriteObject(output.ToString());
}
catch (Exception e)
{
WriteVerbose(e.ToString());
WriteError(new ErrorRecord(e, ErrorIds.DecompilationFailed, ErrorCategory.OperationStopped, null));
}
}
}
}
| ILSpy/ICSharpCode.Decompiler.PowerShell/GetDecompiledSourceCmdlet.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.PowerShell/GetDecompiledSourceCmdlet.cs",
"repo_id": "ILSpy",
"token_count": 421
} | 192 |
// Copyright (c) 2020 Siegfried Pammer
//
// 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.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ICSharpCode.Decompiler.Util;
using NuGet.Common;
using NuGet.Packaging;
using NuGet.Protocol;
using NuGet.Protocol.Core.Types;
using NuGet.Versioning;
namespace ICSharpCode.Decompiler.Tests.Helpers
{
abstract class AbstractToolset
{
readonly SourceCacheContext cache;
readonly SourceRepository repository;
readonly FindPackageByIdResource resource;
protected readonly string baseDir;
public AbstractToolset(string baseDir)
{
this.cache = new SourceCacheContext();
this.repository = Repository.Factory.GetCoreV3("https://api.nuget.org/v3/index.json");
this.resource = repository.GetResource<FindPackageByIdResource>();
this.baseDir = baseDir;
}
protected async Task FetchPackage(string packageName, string version, string sourcePath, string outputPath)
{
ILogger logger = NullLogger.Instance;
CancellationToken cancellationToken = CancellationToken.None;
using MemoryStream packageStream = new MemoryStream();
await resource.CopyNupkgToStreamAsync(
packageName,
NuGetVersion.Parse(version),
packageStream,
cache,
logger,
cancellationToken).ConfigureAwait(false);
using PackageArchiveReader packageReader = new PackageArchiveReader(packageStream);
NuspecReader nuspecReader = await packageReader.GetNuspecReaderAsync(cancellationToken).ConfigureAwait(false);
var files = (await packageReader.GetFilesAsync(cancellationToken).ConfigureAwait(false)).ToArray();
files = files.Where(f => f.StartsWith(sourcePath, StringComparison.OrdinalIgnoreCase)).ToArray();
await packageReader.CopyFilesAsync(outputPath, files,
(sourceFile, targetPath, fileStream) => {
fileStream.CopyToFile(targetPath);
return targetPath;
},
logger, cancellationToken).ConfigureAwait(false);
}
}
class RoslynToolset : AbstractToolset
{
readonly Dictionary<string, string> installedCompilers = new Dictionary<string, string> {
{ "legacy", Environment.ExpandEnvironmentVariables(@"%WINDIR%\Microsoft.NET\Framework\v4.0.30319") }
};
public RoslynToolset()
: base(Path.Combine(AppContext.BaseDirectory, "roslyn"))
{
}
public async Task Fetch(string version, string packageName = "Microsoft.Net.Compilers.Toolset", string sourcePath = "tasks/net472")
{
string path = Path.Combine(baseDir, version, sourcePath);
if (!Directory.Exists(path))
{
await FetchPackage(packageName, version, sourcePath, Path.Combine(baseDir, version)).ConfigureAwait(false);
}
installedCompilers.Add(SanitizeVersion(version), path);
}
public string GetCSharpCompiler(string version)
{
return GetCompiler("csc.exe", version);
}
public string GetVBCompiler(string version)
{
return GetCompiler("vbc.exe", version);
}
string GetCompiler(string compiler, string version)
{
if (installedCompilers.TryGetValue(SanitizeVersion(version), out var path))
return Path.Combine(path, compiler);
throw new NotSupportedException($"Cannot find {compiler} {version}, please add it to the initialization.");
}
internal static string SanitizeVersion(string version)
{
int index = version.IndexOf("-");
if (index > 0)
return version.Remove(index);
return version;
}
}
class VsWhereToolset : AbstractToolset
{
string vswherePath;
public VsWhereToolset()
: base(Path.Combine(AppContext.BaseDirectory, "vswhere"))
{
}
public async Task Fetch()
{
string path = Path.Combine(baseDir, "tools");
if (!Directory.Exists(path))
{
await FetchPackage("vswhere", "2.8.4", "tools", baseDir).ConfigureAwait(false);
}
vswherePath = Path.Combine(path, "vswhere.exe");
}
public string GetVsWhere() => vswherePath;
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/Helpers/RoslynToolset.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/Helpers/RoslynToolset.cs",
"repo_id": "ILSpy",
"token_count": 1631
} | 193 |
// 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.
#pragma warning disable 1998
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness
{
public class Async
{
public static void Main()
{
new Async().Run().Wait();
}
public async Task Run()
{
Console.WriteLine("SimpleBoolTaskMethod:");
await SimpleBoolTaskMethod();
Console.WriteLine("StreamCopyTo:");
StreamCopyTo(new MemoryStream(new byte[1024]), 16);
Console.WriteLine("StreamCopyToWithConfigureAwait:");
StreamCopyToWithConfigureAwait(new MemoryStream(new byte[1024]), 16);
Console.WriteLine("AwaitInForEach:");
await AwaitInForEach(Enumerable.Range(0, 100).Select(i => Task.FromResult(i)));
Console.WriteLine("TaskMethodWithoutAwaitButWithExceptionHandling:");
await TaskMethodWithoutAwaitButWithExceptionHandling();
#if CS60
Console.WriteLine($"{nameof(AwaitCatch)}:");
await AwaitCatch(Task.FromResult(1));
Console.WriteLine($"{nameof(AwaitMultipleCatchBlocks)}:");
await AwaitMultipleCatchBlocks(Task.FromResult(1));
Console.WriteLine($"{nameof(AwaitMultipleCatchBlocks2)}:");
await AwaitMultipleCatchBlocks2(Task.FromResult(1));
Console.WriteLine($"{nameof(AwaitInComplexFinally)}:");
Console.WriteLine(await AwaitInComplexFinally());
try
{
Console.WriteLine($"{nameof(AwaitFinally)}:");
await AwaitFinally(Task.FromResult(2));
}
catch (Exception ex)
{
Console.WriteLine(ex + " caught!");
}
#endif
Console.WriteLine("NestedAwait:");
await NestedAwait(Task.FromResult(Task.FromResult(5)));
Console.WriteLine("AwaitWithStack:");
await AwaitWithStack(Task.FromResult(3));
Console.WriteLine("AwaitWithStack2:");
await AwaitWithStack2(Task.FromResult(4));
#if CS60
Console.WriteLine($"{nameof(AwaitInCatch)}:");
await AwaitInCatch(Task.FromResult(1), Task.FromResult(2));
Console.WriteLine($"{nameof(AwaitInFinally)}:");
await AwaitInFinally(Task.FromResult(2), Task.FromResult(4));
Console.WriteLine($"{nameof(AwaitInCatchAndFinally)}:");
await AwaitInCatchAndFinally(Task.FromResult(3), Task.FromResult(6), Task.FromResult(9));
Console.WriteLine($"{nameof(AwaitInFinallyInUsing)}:");
Console.WriteLine(await AwaitInFinallyInUsing(Task.FromResult<IDisposable>(new StringWriter()), Task.FromResult(6), Task.FromResult(9)));
#endif
}
public async Task<bool> SimpleBoolTaskMethod()
{
Console.WriteLine("Before");
await Task.Delay(TimeSpan.FromSeconds(1.0));
Console.WriteLine("After");
return true;
}
public async void StreamCopyTo(Stream destination, int bufferSize)
{
Console.WriteLine("Before");
byte[] array = new byte[bufferSize];
int count;
Console.WriteLine("BeforeLoop");
while ((count = await destination.ReadAsync(array, 0, array.Length)) != 0)
{
Console.WriteLine("In Loop after condition!");
await destination.WriteAsync(array, 0, count);
Console.WriteLine("In Loop after inner await");
}
Console.WriteLine("After");
}
public async void StreamCopyToWithConfigureAwait(Stream destination, int bufferSize)
{
Console.WriteLine("Before");
byte[] array = new byte[bufferSize];
int count;
Console.WriteLine("Before Loop");
while ((count = await destination.ReadAsync(array, 0, array.Length).ConfigureAwait(false)) != 0)
{
Console.WriteLine("Before Inner Await");
await destination.WriteAsync(array, 0, count).ConfigureAwait(false);
Console.WriteLine("After Inner Await");
}
Console.WriteLine("After");
}
public async Task<int> AwaitInForEach(IEnumerable<Task<int>> elements)
{
int num = 0;
Console.WriteLine("Before Loop");
foreach (Task<int> current in elements)
{
Console.WriteLine("Before Inner Await");
num += await current;
Console.WriteLine("After Inner Await");
}
Console.WriteLine("After");
return num;
}
public async Task TaskMethodWithoutAwaitButWithExceptionHandling()
{
try
{
using (new StringWriter())
{
Console.WriteLine("No Await");
}
}
catch (Exception)
{
Console.WriteLine("Crash");
}
}
#if CS60
public async Task AwaitCatch(Task<int> task)
{
try
{
Console.WriteLine("Before throw");
throw new Exception();
}
catch
{
Console.WriteLine(await task);
}
}
public async Task AwaitMultipleCatchBlocks(Task<int> task)
{
try
{
Console.WriteLine("Before throw");
throw new Exception();
}
catch (OutOfMemoryException ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine(await task);
}
catch
{
Console.WriteLine(await task);
}
}
public async Task AwaitMultipleCatchBlocks2(Task<int> task)
{
try
{
Console.WriteLine("Before throw");
throw new Exception();
}
catch (OutOfMemoryException ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine(await task);
}
catch (InternalBufferOverflowException ex)
{
Console.WriteLine(ex.ToString());
}
catch
{
Console.WriteLine(await task);
}
}
public async Task AwaitFinally(Task<int> task)
{
try
{
Console.WriteLine("Before throw");
throw new Exception();
}
finally
{
Console.WriteLine(await task);
}
}
#endif
public async Task<int> NestedAwait(Task<Task<int>> task)
{
return await (await task);
}
public async Task AwaitWithStack(Task<int> task)
{
Console.WriteLine("A", 1, await task);
}
public async Task AwaitWithStack2(Task<int> task)
{
if (await this.SimpleBoolTaskMethod())
{
Console.WriteLine("A", 1, await task);
}
else
{
int num = 1;
Console.WriteLine("A", 1, num);
}
}
#if CS60
public async Task AwaitInCatch(Task<int> task1, Task<int> task2)
{
try
{
Console.WriteLine("Start try");
await task1;
Console.WriteLine("End try");
}
catch (Exception)
{
Console.WriteLine("Start catch");
await task2;
Console.WriteLine("End catch");
}
Console.WriteLine("End Method");
}
public async Task AwaitInFinally(Task<int> task1, Task<int> task2)
{
try
{
Console.WriteLine("Start try");
await task1;
Console.WriteLine("End try");
}
finally
{
Console.WriteLine("Start finally");
await task2;
Console.WriteLine("End finally");
}
Console.WriteLine("End Method");
}
public static async Task<int> AwaitInComplexFinally()
{
Console.WriteLine("a");
try
{
Console.WriteLine("b");
await Task.Delay(1);
Console.WriteLine("c");
}
catch (Exception ex)
{
await Task.Delay(ex.HResult);
}
finally
{
Console.WriteLine("d");
int i = 0;
if (Console.CapsLock)
{
i++;
await Task.Delay(i);
}
else
{
while (i < 5)
{
Console.WriteLine("i: " + i);
i++;
}
}
Console.WriteLine("e");
}
Console.WriteLine("f");
return 1;
}
public async Task AwaitInCatchAndFinally(Task<int> task1, Task<int> task2, Task<int> task3)
{
try
{
Console.WriteLine("Start try");
await task1;
Console.WriteLine("End try");
}
catch (Exception ex)
{
Console.WriteLine("Start catch");
await task2;
Console.WriteLine("End catch");
}
finally
{
Console.WriteLine("Start finally");
await task3;
Console.WriteLine("End finally");
}
Console.WriteLine("End Method");
}
public async Task<int> AwaitInFinallyInUsing(Task<IDisposable> task1, Task<int> task2, Task<int> task3)
{
using (await task1)
{
Console.WriteLine("Start using");
try
{
Console.WriteLine("Before return");
return await task2;
}
finally
{
Console.WriteLine("Start finally");
await task3;
Console.WriteLine("End finally");
}
}
}
#endif
}
} | ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/Async.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/Async.cs",
"repo_id": "ILSpy",
"token_count": 3604
} | 194 |
// 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.Globalization;
using System.Linq;
using System.Threading;
namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness
{
public class InitializerTests
{
public static int Main()
{
int[,] test = new int[2, 3];
test[0, 0] = 0;
test[0, 1] = 1;
test[0, 2] = 2;
int result = test.Length + test[0, 0] + test[0, 2];
Console.WriteLine(result);
return 0;
}
private enum MyEnum
{
a,
b
}
private enum MyEnum2
{
c,
d
}
private class Data
{
public List<InitializerTests.MyEnum2> FieldList = new List<InitializerTests.MyEnum2>();
public InitializerTests.MyEnum a {
get;
set;
}
public InitializerTests.MyEnum b {
get;
set;
}
public List<InitializerTests.MyEnum2> PropertyList {
get;
set;
}
public InitializerTests.Data MoreData {
get;
set;
}
public InitializerTests.StructData NestedStruct {
get;
set;
}
public InitializerTests.Data this[int i] {
get {
return null;
}
set { }
}
public InitializerTests.Data this[int i, string j] {
get {
return null;
}
set { }
}
}
private struct StructData
{
public int Field;
public int Property {
get;
set;
}
public InitializerTests.Data MoreData {
get;
set;
}
public StructData(int initialValue)
{
this = default(InitializerTests.StructData);
this.Field = initialValue;
this.Property = initialValue;
}
}
// Helper methods used to ensure initializers used within expressions work correctly
private static void X(object a, object b)
{
}
private static object Y()
{
return null;
}
public static void CollectionInitializerList()
{
InitializerTests.X(InitializerTests.Y(), new List<int>
{
1,
2,
3
});
}
public static object RecursiveCollectionInitializer()
{
List<object> list = new List<object>();
list.Add(list);
return list;
}
public static void CollectionInitializerDictionary()
{
InitializerTests.X(InitializerTests.Y(), new Dictionary<string, int>
{
{
"First",
1
},
{
"Second",
2
},
{
"Third",
3
}
});
}
public static void CollectionInitializerDictionaryWithEnumTypes()
{
InitializerTests.X(InitializerTests.Y(), new Dictionary<InitializerTests.MyEnum, InitializerTests.MyEnum2>
{
{
InitializerTests.MyEnum.a,
InitializerTests.MyEnum2.c
},
{
InitializerTests.MyEnum.b,
InitializerTests.MyEnum2.d
}
});
}
public static void NotACollectionInitializer()
{
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
InitializerTests.X(InitializerTests.Y(), list);
}
public static void ObjectInitializer()
{
InitializerTests.X(InitializerTests.Y(), new InitializerTests.Data {
a = InitializerTests.MyEnum.a
});
}
public static void NotAnObjectInitializer()
{
InitializerTests.Data data = new InitializerTests.Data();
data.a = InitializerTests.MyEnum.a;
InitializerTests.X(InitializerTests.Y(), data);
}
public static void ObjectInitializerAssignCollectionToField()
{
InitializerTests.X(InitializerTests.Y(), new InitializerTests.Data {
a = InitializerTests.MyEnum.a,
FieldList = new List<InitializerTests.MyEnum2>
{
InitializerTests.MyEnum2.c,
InitializerTests.MyEnum2.d
}
});
}
public static void ObjectInitializerAddToCollectionInField()
{
InitializerTests.X(InitializerTests.Y(), new InitializerTests.Data {
a = InitializerTests.MyEnum.a,
FieldList =
{
InitializerTests.MyEnum2.c,
InitializerTests.MyEnum2.d
}
});
}
public static void ObjectInitializerAssignCollectionToProperty()
{
InitializerTests.X(InitializerTests.Y(), new InitializerTests.Data {
a = InitializerTests.MyEnum.a,
PropertyList = new List<InitializerTests.MyEnum2>
{
InitializerTests.MyEnum2.c,
InitializerTests.MyEnum2.d
}
});
}
public static void ObjectInitializerAddToCollectionInProperty()
{
InitializerTests.X(InitializerTests.Y(), new InitializerTests.Data {
a = InitializerTests.MyEnum.a,
PropertyList =
{
InitializerTests.MyEnum2.c,
InitializerTests.MyEnum2.d
}
});
}
public static void ObjectInitializerWithInitializationOfNestedObjects()
{
InitializerTests.X(InitializerTests.Y(), new InitializerTests.Data {
MoreData =
{
a = InitializerTests.MyEnum.a,
MoreData = {
a = InitializerTests.MyEnum.b
}
}
});
}
static int GetInt()
{
return 1;
}
static string GetString()
{
return "Test";
}
#if CS60
public static void SimpleDictInitializer()
{
InitializerTests.X(InitializerTests.Y(), new InitializerTests.Data {
MoreData =
{
a = InitializerTests.MyEnum.a,
[2] = (Data)null
}
});
}
public static void MixedObjectAndDictInitializer()
{
InitializerTests.X(InitializerTests.Y(), new InitializerTests.Data {
MoreData =
{
a = InitializerTests.MyEnum.a,
[GetInt()] = {
a = InitializerTests.MyEnum.b,
FieldList = { MyEnum2.c },
[GetInt(), GetString()] = new Data(),
[2] = (Data)null
}
}
});
}
#endif
public static void ObjectInitializerWithInitializationOfDeeplyNestedObjects()
{
InitializerTests.X(InitializerTests.Y(), new InitializerTests.Data {
a = InitializerTests.MyEnum.b,
MoreData =
{
a = InitializerTests.MyEnum.a,
MoreData = { MoreData = { MoreData = { MoreData = { MoreData = { MoreData = { a = MyEnum.b } } } } } }
}
});
}
public static void CollectionInitializerInsideObjectInitializers()
{
InitializerTests.Data castPattern = new InitializerTests.Data {
MoreData = new InitializerTests.Data {
a = InitializerTests.MyEnum.a,
b = InitializerTests.MyEnum.b,
PropertyList = { InitializerTests.MyEnum2.c }
}
};
}
public static void NotAStructInitializer_DefaultConstructor()
{
InitializerTests.StructData data = new InitializerTests.StructData();
data.Field = 1;
data.Property = 2;
InitializerTests.X(InitializerTests.Y(), data);
}
public static void StructInitializer_DefaultConstructor()
{
InitializerTests.X(InitializerTests.Y(), new InitializerTests.StructData {
Field = 1,
Property = 2
});
}
public static void NotAStructInitializer_ExplicitConstructor()
{
InitializerTests.StructData data = new InitializerTests.StructData(0);
data.Field = 1;
data.Property = 2;
InitializerTests.X(InitializerTests.Y(), data);
}
public static void StructInitializer_ExplicitConstructor()
{
InitializerTests.X(InitializerTests.Y(), new InitializerTests.StructData(0) {
Field = 1,
Property = 2
});
}
public static void StructInitializerWithInitializationOfNestedObjects()
{
InitializerTests.X(InitializerTests.Y(), new InitializerTests.StructData {
MoreData =
{
a = InitializerTests.MyEnum.a,
FieldList =
{
InitializerTests.MyEnum2.c,
InitializerTests.MyEnum2.d
}
}
});
}
public static void StructInitializerWithinObjectInitializer()
{
InitializerTests.X(InitializerTests.Y(), new InitializerTests.Data {
NestedStruct = new InitializerTests.StructData(2) {
Field = 1,
Property = 2
}
});
}
public static void Bug270_NestedInitialisers()
{
NumberFormatInfo[] numberFormats = null;
Thread t = new Thread(Bug270_NestedInitialisers) {
Priority = ThreadPriority.BelowNormal,
CurrentCulture = new CultureInfo(0) {
DateTimeFormat = new DateTimeFormatInfo {
ShortDatePattern = "ddmmyy"
},
NumberFormat = (from format in numberFormats where format.CurrencySymbol == "$" select format).First()
}
};
}
#if CS60
class Issue2622a
{
public class C
{
public ServiceHost M()
{
return new ServiceHost(typeof(EWSService), null) {
Description = { Endpoints = { [0] = { Behaviors = { new EwsWebHttpBehavior() } } } }
};
}
}
class EWSService { }
public class ServiceHost
{
public ServiceHost(Type type, object x) { }
public Descr Description { get; }
}
public class Descr
{
public List<EP> Endpoints { get; }
}
public class EP
{
public List<Beh> Behaviors { get; }
}
public abstract class Beh { }
public class EwsWebHttpBehavior : Beh { }
}
#endif
class Issue855
{
class Data
{
public object Obj;
}
class Items
{
public void SetItem(int i, object item) { }
}
object Item(string s, Data d)
{
return new object();
}
void Test()
{
Items items = null;
int num = 0;
for (int i = 0; i < 2; i++)
{
if (num < 10)
items.SetItem(num, Item(string.Empty, new Data { Obj = null }));
}
}
}
}
} | ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/InitializerTests.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/InitializerTests.cs",
"repo_id": "ILSpy",
"token_count": 4253
} | 195 |
// 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;
namespace ICSharpCode.Decompiler.Tests.TestCases.Correctness
{
public class UndocumentedExpressions
{
static void Main(string[] args)
{
MakeTypedRef("abc");
VarArgs(1, __arglist());
VarArgs(__arglist(1));
VarArgs(1, __arglist("abc", 2, true));
VarArgs(1, __arglist((object)"abc", 2, true));
VarArgs(1, __arglist((short)1));
VarArgs(1, __arglist(ConsoleColor.Red));
}
public static void VarArgs(int normalArg, __arglist)
{
ArgIterator argIterator = new ArgIterator(__arglist);
Console.WriteLine("Called with {0} arguments", argIterator.GetRemainingCount());
int pos = 0;
while (argIterator.GetRemainingCount() > 0)
{
TypedReference tr = argIterator.GetNextArg();
object val;
try
{
val = __refvalue(tr, object);
}
catch (Exception ex)
{
val = ex.GetType().Name;
}
Console.WriteLine("{0} : {1} = {2}", pos++, __reftype(tr).Name, val);
}
}
public static void VarArgs(__arglist)
{
Console.WriteLine("The other varargs overload");
}
public static void MakeTypedRef(object o)
{
TypedReference tr = __makeref(o);
UndocumentedExpressions.AcceptTypedRef(tr);
}
private static void AcceptTypedRef(TypedReference tr)
{
Console.WriteLine("Value is: " + __refvalue(tr, object).ToString());
Console.WriteLine("Type is: " + __reftype(tr).Name);
__refvalue(tr, object) = 1;
}
}
} | ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/UndocumentedExpressions.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Correctness/UndocumentedExpressions.cs",
"repo_id": "ILSpy",
"token_count": 875
} | 196 |
using System;
internal class CallIndirect
{
private unsafe void Test(IntPtr f)
{
((delegate* unmanaged[Stdcall]<int, void>)f)(42);
}
private unsafe void UnmanagedDefaultCall(IntPtr f)
{
((delegate* unmanaged<int, void>)f)(42);
}
private unsafe void CustomCall(IntPtr f)
{
((delegate* unmanaged[Custom]<int, void>)f)(42);
}
private unsafe void MultipleCustomCall(IntPtr f)
{
((delegate* unmanaged[SuppressGCTransition, Custom]<int, void>)f)(42);
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/CallIndirect.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/CallIndirect.cs",
"repo_id": "ILSpy",
"token_count": 177
} | 197 |
using System;
using System.IO;
public static class FSharpUsingPatterns
{
public static void sample1()
{
using (FileStream fileStream = File.Create("x.txt"))
{
fileStream.WriteByte((byte)1);
}
}
public static void sample2()
{
Console.WriteLine("some text");
using (FileStream fileStream = File.Create("x.txt"))
{
fileStream.WriteByte((byte)2);
Console.WriteLine("some text");
}
}
public static void sample3()
{
Console.WriteLine("some text");
using (FileStream fileStream = File.Create("x.txt"))
{
fileStream.WriteByte((byte)3);
}
Console.WriteLine("some text");
}
public static void sample4()
{
Console.WriteLine("some text");
int num;
using (FileStream fileStream = File.OpenRead("x.txt"))
{
num = fileStream.ReadByte();
}
int num2 = num;
Console.WriteLine("read:" + num2);
}
public static void sample5()
{
Console.WriteLine("some text");
int num;
using (FileStream fileStream = File.OpenRead("x.txt"))
{
num = fileStream.ReadByte();
}
int num2 = num;
int num3;
using (FileStream fileStream = File.OpenRead("x.txt"))
{
fileStream.ReadByte();
num3 = fileStream.ReadByte();
}
int num4 = num3;
Console.WriteLine("read: {0}, {1}", num2, num4);
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/FSharpUsing_Debug.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/FSharpUsing_Debug.cs",
"repo_id": "ILSpy",
"token_count": 496
} | 198 |
public enum Enum0
{
// error: enumerator has no value
const_0,
// error: enumerator has no value
const_1,
// error: enumerator has no value
const_2,
// error: enumerator has no value
const_3
} | ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1323.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue1323.cs",
"repo_id": "ILSpy",
"token_count": 75
} | 199 |
.assembly issue2104
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = (
01 00 08 00 00 00 00 00
)
.custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = (
01 00 01 00 54 02 16 57 72 61 70 4e 6f 6e 45 78
63 65 70 74 69 6f 6e 54 68 72 6f 77 73 01
)
.custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = (
01 00 07 01 00 00 00 00
)
.hash algorithm 0x00008004 // SHA1
.ver 0:0:0:0
}
.module issue2104.exe
// MVID: {A7498FA1-F4D7-486E-A872-3DC0CAFD87E2}
.imagebase 0x10000000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003 // WindowsCui
.corflags 0x00000001 // ILOnly
.custom instance void [mscorlib]System.Security.UnverifiableCodeAttribute::.ctor() = (
01 00 00 00
)
.class private auto ansi '<Module>'
{
} // end of class <Module>
.class private auto ansi beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue2104
extends [mscorlib]System.Object
{
// Fields
.field private initonly string 'text'
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
01 00 00 00
)
// Methods
.method public hidebysig specialname
instance string get_Text () cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
01 00 00 00
)
// Method begins at RVA 0x2074
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldfld string ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue2104::text
IL_0006: ret
} // end of method ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue2104::get_Text
.method public hidebysig specialname rtspecialname
instance void .ctor (
string text
) cil managed
{
// Method begins at RVA 0x207c
// Code size 14 (0xe)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ldarg.0
IL_0007: ldarg.1
IL_0008: stfld string ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue2104::'text'
IL_000d: ret
} // end of method ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue2104::.ctor
// Properties
.property instance string Text()
{
.get instance string ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue2104::get_Text()
}
} // end of class ICSharpCode.Decompiler.Tests.TestCases.ILPretty.Issue2104
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue2104.il/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/Issue2104.il",
"repo_id": "ILSpy",
"token_count": 1109
} | 200 |
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 )
.ver 4:0:0:0
}
.assembly MonoFixed
{
.ver 1:0:0:0
}
.module MonoFixed.exe
.imagebase 0x00400000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003 // WindowsCui
.corflags 0x00000001 // ILOnly
.custom instance void [mscorlib]System.Security.UnverifiableCodeAttribute::.ctor() = (
01 00 00 00
)
.class public auto ansi beforefieldinit MonoFixed
extends [mscorlib]System.Object
{
.method public hidebysig instance void FixMultipleStrings (string text) cil managed
{
.maxstack 7
.locals init (
[0] char* pinned,
[1] char* pinned,
[2] char* pinned,
[3] string pinned,
[4] string pinned,
[5] string pinned
)
IL_0000: ldarg.1
IL_0001: stloc.3
IL_0002: ldloc.3
IL_0003: conv.i
IL_0004: call int32 [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::get_OffsetToStringData()
IL_0009: add
IL_000a: stloc.0
IL_000b: call string [mscorlib]System.Environment::get_UserName()
IL_0010: stloc.s 4
IL_0012: ldloc.s 4
IL_0014: conv.i
IL_0015: call int32 [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::get_OffsetToStringData()
IL_001a: add
IL_001b: stloc.1
IL_001c: ldarg.1
IL_001d: stloc.s 5
IL_001f: ldloc.s 5
IL_0021: conv.i
IL_0022: call int32 [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::get_OffsetToStringData()
IL_0027: add
IL_0028: stloc.2
IL_0029: ldloc.0
IL_002a: ldc.i4.s 99
IL_002c: stind.i2
IL_002d: ldloc.1
IL_002e: ldc.i4.s 100
IL_0030: stind.i2
IL_0031: ldloc.2
IL_0032: ldc.i4.s 101
IL_0034: stind.i2
IL_0035: ldnull
IL_0036: stloc.3
IL_0037: ldnull
IL_0038: stloc.s 4
IL_003a: ldnull
IL_003b: stloc.s 5
IL_003d: ret
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/MonoFixed.il/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/ILPretty/MonoFixed.il",
"repo_id": "ILSpy",
"token_count": 826
} | 201 |
namespace ICSharpCode.Decompiler.Tests.TestCases.CovariantReturns
{
public abstract class Base
{
public abstract Base Instance { get; }
public abstract Base this[int index] { get; }
public virtual Base Build()
{
throw null;
}
protected abstract Base SetParent(object parent);
}
public class Derived : Base
{
public override Derived Instance { get; }
public override Derived this[int index] {
get {
throw null;
}
}
public override Derived Build()
{
throw null;
}
protected override Derived SetParent(object parent)
{
throw null;
}
}
public class UseSites
{
public Base Test(Base x)
{
return x.Build();
}
public Derived Test(Derived x)
{
return x.Build();
}
}
} | ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/CovariantReturns.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/CovariantReturns.cs",
"repo_id": "ILSpy",
"token_count": 287
} | 202 |
#if !(CS110 && NET70)
using System;
#endif
using System.Text;
namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
{
public class FunctionPointerAddressOf
{
public static void Overloaded()
{
}
public static void Overloaded(int a)
{
}
public unsafe delegate*<void> GetAddress()
{
return &Overloaded;
}
#if !(CS110 && NET70)
public unsafe IntPtr GetAddressAsIntPtr()
{
return (IntPtr)(delegate*<void>)(&Overloaded);
}
#endif
public unsafe nint GetAddressAsNInt()
{
return (nint)(delegate*<void>)(&Overloaded);
}
public unsafe void* GetAddressAsVoidPtr()
{
return (delegate*<int, void>)(&Overloaded);
}
public static string VarianceTest(object o)
{
return null;
}
public unsafe delegate*<StringBuilder, object> Variance()
{
return (delegate*<object, string>)(&VarianceTest);
}
public unsafe delegate*<void> AddressOfLocalFunction()
{
return &LocalFunction;
static void LocalFunction()
{
}
}
}
internal class FunctionPointersWithCallingConvention
{
public unsafe delegate*<void> fn_default;
// Unmanaged without explicit callconv is only supported with .NET 5,
// and emits metadata that cannot be parsed by older SRM versions.
//public delegate* unmanaged<void> fn_unmanaged;
public unsafe delegate* unmanaged[Cdecl]<void> fn_cdecl;
public unsafe delegate* unmanaged[Fastcall]<void> fn_fastcall;
public unsafe delegate* unmanaged[Stdcall]<void> fn_stdcall;
public unsafe delegate* unmanaged[Thiscall]<void> fn_thiscall;
}
internal class FunctionPointersWithDynamicTypes
{
public class D<T, U>
{
}
public class A<T>
{
public class B<U>
{
}
}
public unsafe delegate*<dynamic, dynamic, dynamic> F1;
public unsafe delegate*<object, object, dynamic> F2;
public unsafe delegate*<dynamic, object, object> F3;
public unsafe delegate*<object, dynamic, object> F4;
public unsafe delegate*<object, object, object> F5;
public unsafe delegate*<object, object, ref dynamic> F6;
public unsafe delegate*<ref dynamic, object, object> F7;
public unsafe delegate*<object, ref dynamic, object> F8;
public unsafe delegate*<ref object, ref object, dynamic> F9;
public unsafe delegate*<dynamic, ref object, ref object> F10;
public unsafe delegate*<ref object, dynamic, ref object> F11;
public unsafe delegate*<object, ref readonly dynamic> F12;
public unsafe delegate*<in dynamic, object> F13;
public unsafe delegate*<out dynamic, object> F14;
public unsafe D<delegate*<dynamic>[], dynamic> F15;
public unsafe delegate*<A<object>.B<dynamic>> F16;
}
internal class FunctionPointersWithNativeIntegerTypes
{
public unsafe delegate*<nint, nint, nint> F1;
#if !(CS110 && NET70)
public unsafe delegate*<IntPtr, IntPtr, nint> F2;
public unsafe delegate*<nint, IntPtr, IntPtr> F3;
public unsafe delegate*<IntPtr, nint, IntPtr> F4;
public unsafe delegate*<delegate*<IntPtr, IntPtr, IntPtr>, nint> F5;
public unsafe delegate*<nint, delegate*<IntPtr, IntPtr, IntPtr>> F6;
public unsafe delegate*<delegate*<IntPtr, IntPtr, nint>, IntPtr> F7;
public unsafe delegate*<IntPtr, delegate*<IntPtr, nint, IntPtr>> F8;
public unsafe delegate*<IntPtr, delegate*<IntPtr, IntPtr, IntPtr>> F9;
#endif
}
internal class FunctionPointersWithRefParams
{
public unsafe delegate*<in byte, ref char, out float, ref readonly int> F1;
public unsafe delegate*<ref char, out float, ref int> F2;
public unsafe int CallF1(byte b, char c, out float f)
{
return F1(in b, ref c, out f);
}
public unsafe void CallF2(byte b, char c, out float f)
{
F2(ref c, out f) = b;
}
}
internal class FunctionPointerTypeInference
{
private static char Test(int i)
{
return (char)i;
}
public unsafe R GenericMethod<T, R>(delegate*<T, R> f, T arg)
{
return f(arg);
}
public unsafe void Call()
{
delegate*<int, char> f = &Test;
GenericMethod(f, 0);
GenericMethod((delegate*<int, char>)(&Test), 1);
GenericMethod<int, char>(null, 2);
}
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/FunctionPointers.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/FunctionPointers.cs",
"repo_id": "ILSpy",
"token_count": 1490
} | 203 |
// Copyright (c) 2020 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;
using System.Collections.Generic;
namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
{
internal class NativeInts
{
private const nint nint_const = 42;
private const nuint nuint_const = 99u;
#if CS110 && NET70
// C#11 on .NET7 no longer uses NativeIntegerAttribute,
// instead nint+IntPtr are considered to be the same type.
private nint intptr;
private nuint uintptr;
#else
private IntPtr intptr;
private UIntPtr uintptr;
#endif
private nint i;
private nuint u;
private int i32;
private uint u32;
private long i64;
private ulong u64;
#if !(CS110 && NET70)
private (IntPtr, nint, UIntPtr, nuint) tuple_field;
private (object, int, IntPtr, nint, UIntPtr, nuint) tuple_field2;
private Dictionary<nint, IntPtr> dict1;
private Dictionary<IntPtr, nint> dict2;
private Dictionary<IntPtr?, nint?> dict3;
private Dictionary<IntPtr, nint[]> dict4;
#endif
private Dictionary<nuint, nint[]> dict5;
public void Convert()
{
i = (nint)u;
u = (nuint)i;
#if !(CS110 && NET70)
intptr = i;
intptr = (nint)u;
intptr = (nint)(nuint)uintptr;
uintptr = (nuint)i;
uintptr = u;
uintptr = (nuint)(nint)intptr;
i = intptr;
i = (nint)u;
i = (nint)(nuint)uintptr;
u = (nuint)i;
u = uintptr;
u = (nuint)(nint)intptr;
#endif
}
public void Convert2()
{
i32 = (int)i;
i = i32;
#if !(CS110 && NET70)
intptr = (IntPtr)i32;
i64 = (long)intptr;
#endif
i64 = i;
i = (nint)i64;
u32 = (uint)i;
i = (nint)u32;
u64 = (uint)i;
i = (nint)u64;
}
public void Arithmetic()
{
#if !(CS110 && NET70)
Console.WriteLine((nint)intptr * 2);
#endif
Console.WriteLine(i * 2);
Console.WriteLine(i + (nint)u);
Console.WriteLine((nuint)i + u);
}
public void Shifts()
{
Console.WriteLine(i << i32);
Console.WriteLine(i >> i32);
Console.WriteLine(u >> i32);
Console.WriteLine(u << i32);
}
public void Comparisons()
{
Console.WriteLine(i < i32);
Console.WriteLine(i <= i32);
Console.WriteLine(i > i32);
Console.WriteLine(i >= i32);
Console.WriteLine(i == (nint)u);
Console.WriteLine(i < (nint)u);
Console.WriteLine((nuint)i < u);
}
public void Unary()
{
Console.WriteLine(~i);
Console.WriteLine(~u);
Console.WriteLine(-i);
}
public unsafe int* PtrArithmetic(int* ptr)
{
return ptr + i;
}
public unsafe nint* PtrArithmetic(nint* ptr)
{
return ptr + u;
}
public object[] Boxing()
{
return new object[10] {
1,
(nint)2,
3L,
4u,
(nuint)5u,
6uL,
int.MaxValue,
(nint)int.MaxValue,
i64,
(nint)i64
};
}
public NativeInts GetInstance(int i)
{
return this;
}
public void CompoundAssign()
{
GetInstance(0).i += i32;
checked
{
GetInstance(1).i += i32;
}
GetInstance(2).u *= 2u;
checked
{
GetInstance(3).u *= 2u;
}
#if !(CS110 && NET70)
GetInstance(4).intptr += (nint)i32;
checked
{
// Note: the cast is necessary here, without it we'd call IntPtr.op_Addition
// but that is always unchecked.
GetInstance(5).intptr += (nint)i32;
}
// multiplication results in compiler-error without the cast
GetInstance(6).intptr *= (nint)2;
#endif
GetInstance(7).i += i32;
GetInstance(8).i <<= i32;
}
#if !(CS110 && NET70)
public void LocalTypeFromStore()
{
nint num = 42;
IntPtr zero = IntPtr.Zero;
nint zero2 = IntPtr.Zero;
nuint num2 = 43u;
nint num3 = i;
IntPtr intPtr = intptr;
Console.WriteLine();
zero2 = 1;
Console.WriteLine();
intptr = num;
intptr = zero;
intptr = zero2;
uintptr = num2;
intptr = num3;
intptr = intPtr;
}
#endif
public void LocalTypeFromUse()
{
#if CS110 && NET70
nint num = intptr;
nint num2 = intptr;
Console.WriteLine();
intptr = num;
i = num2 + 1;
#else
IntPtr intPtr = intptr;
nint num = intptr;
Console.WriteLine();
intptr = intPtr;
i = num + 1;
#endif
}
public nint NegateUnsigned(nuint x)
{
return (nint)(0 - x);
}
public bool CompareToMinus3(nuint x)
{
return x == unchecked((nuint)(-3));
}
public nint SignedNotFittingIn32Bits()
{
// Explicit `unchecked` is necessary when casting oversized constant to nint
return unchecked((nint)9123123123123L);
}
public nuint UnsignedNotFittingIn32Bits()
{
// Explicit `unchecked` is necessary when casting oversized constant to nuint
return unchecked((nuint)9123123123123uL);
}
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/NativeInts.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/NativeInts.cs",
"repo_id": "ILSpy",
"token_count": 2358
} | 204 |
// 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.
// compile:
// csc ShortCircuit.cs /t:Library && ildasm /text ShortCircuit.dll >ShortCircuit.il
// csc ShortCircuit.cs /t:Library /o /out:ShortCircuit.opt.dll && ildasm /text ShortCircuit.opt.dll >ShortCircuit.opt.il
namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
{
public abstract class ShortCircuit
{
public abstract void B(bool b);
public abstract bool F(int i);
public abstract int GetInt(int i);
public abstract void M1();
public abstract void M2();
public abstract void E();
public void ExprAnd()
{
B(F(0) && F(1));
}
public void ExprOr()
{
B(F(0) || F(1));
}
public void ExprCond()
{
B(F(0) ? F(1) : F(2));
}
public void ExprCondAnd()
{
B((F(0) && F(1)) ? F(2) : F(3));
}
public void ExprMix4A()
{
B(((F(0) || F(1)) && F(2)) || F(3));
}
public void ExprMix4B()
{
B((F(0) || F(1)) && (F(2) || F(3)));
}
public void ExprMix4C()
{
B((F(0) && F(1)) || (F(2) && F(3)));
}
public void StmtAnd2()
{
if (F(0) && F(1))
{
M1();
}
else
{
M2();
}
E();
}
public void StmtOr2A()
{
if (F(0) || F(1))
{
M1();
}
}
public void StmtOr2B()
{
if (F(0) || F(1))
{
M1();
}
else
{
M2();
}
E();
}
public void StmtAnd3()
{
if (F(0) && F(1) && F(2))
{
M1();
}
else
{
M2();
}
E();
}
public void StmtOr3()
{
if (F(0) || F(1) || F(2))
{
M1();
}
else
{
M2();
}
E();
}
public void StmtOr4()
{
if (GetInt(0) != 0 || GetInt(1) != 0)
{
M1();
}
else
{
M2();
}
E();
}
public void StmtMix3A()
{
if ((F(0) || F(1)) && F(2))
{
M1();
}
}
public void StmtMix3B()
{
if ((F(0) || F(1)) && F(2))
{
M1();
}
else
{
M2();
}
}
public void StmtMix4V1A()
{
if (((F(0) || F(1)) && F(2)) || F(3))
{
M1();
}
}
public void StmtMix4V1B()
{
if (((F(0) || F(1)) && F(2)) || F(3))
{
M1();
}
else
{
M2();
}
}
public void StmtMix4V2A()
{
if ((F(0) || F(1)) && (F(2) || F(3)))
{
M1();
}
}
public void StmtMix4V2B()
{
if ((F(0) || F(1)) && (F(2) || F(3)))
{
M1();
}
else
{
M2();
}
}
public void StmtMix4V3A()
{
if ((F(0) && F(1)) || (F(2) && F(3)))
{
M1();
}
}
public void StmtMix4V3B()
{
if ((F(0) && F(1)) || (F(2) && F(3)))
{
M1();
}
else
{
M2();
}
}
public void StmtComplex()
{
if (F(0) && F(1) && !F(2) && (F(3) || F(4)))
{
M1();
}
else
{
M2();
}
E();
}
public void StmtComplex2(int i)
{
if (i > 1000 || (i >= 1 && i <= 8) || i == 42)
{
M1();
}
else
{
M2();
}
E();
}
public void StmtComplex3(int i)
{
if (i > 1000 || (i >= 1 && i <= 8) || (i >= 100 && i <= 200) || i == 42)
{
M1();
}
else
{
M2();
}
E();
}
public void StmtComplex4(int i)
{
if (i > 1000 || (i >= 1 && i <= 8) || i == 42 || i == 23)
{
M1();
}
else
{
M2();
}
E();
}
public void StmtComplex5()
{
if (F(0))
{
if (!F(1) && !F(2))
{
return;
}
}
else if (!F(3) || !F(4))
{
M2();
return;
}
E();
}
public int StmtComplex6()
{
if (F(0))
{
M1();
if (F(1) || F(2))
{
return 1;
}
}
return 2;
}
public int InferCorrectOrder()
{
if (F(1) || F(2))
{
return 1;
}
return 2;
}
#if !OPT
public void EmptyIf()
{
if (F(0))
{
}
if (!F(1))
{
}
if (F(4) || F(5))
{
}
E();
}
#endif
public void PreferLogicalToBitwise(bool a, bool b, int i, float f)
{
B(a && b);
B(a && i == 1);
B(i == 1 && a);
B(i > i - 3 && a);
B(f < 0.1f && a);
}
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/ShortCircuit.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/ShortCircuit.cs",
"repo_id": "ILSpy",
"token_count": 2680
} | 205 |
namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty
{
internal class VariableNamingWithoutSymbols
{
private class C
{
public string Name;
public string Text;
}
private void Test(string text, C c)
{
#if CS70
_ = c.Name;
#else
string name = c.Name;
#endif
}
private void Test2(string text, C c)
{
#if CS70
_ = c.Text;
#else
string text2 = c.Text;
#endif
}
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/VariableNamingWithoutSymbols.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Pretty/VariableNamingWithoutSymbols.cs",
"repo_id": "ILSpy",
"token_count": 181
} | 206 |
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace ICSharpCode.Decompiler.Tests.TestCases.Ugly
{
public class NoDecimalConstants
{
[DecimalConstant(1, 0, 0u, 0u, 10u)]
private static readonly decimal constant = 1.0m;
private void MethodWithOptionalParameter([Optional][DecimalConstant(1, 0, 0u, 0u, 10u)] decimal parameter)
{
}
}
}
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/NoDecimalConstants.Expected.cs/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/NoDecimalConstants.Expected.cs",
"repo_id": "ILSpy",
"token_count": 141
} | 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 prqfqkbt
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 )
.custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..WrapNonEx
63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) // ceptionThrows.
.permissionset reqmin
= {[mscorlib]System.Security.Permissions.SecurityPermissionAttribute = {property bool 'SkipVerification' = bool(true)}}
.hash algorithm 0x00008004
.ver 0:0:0:0
}
.module prqfqkbt.dll
.custom instance void [mscorlib]System.Security.UnverifiableCodeAttribute::.ctor() = ( 01 00 00 00 )
.imagebase 0x10000000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003 // WINDOWS_CUI
.corflags 0x00000001 // ILONLY
// =============== CLASS MEMBERS DECLARATION ===================
.class private auto ansi beforefieldinit ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoForEachStatement
extends [mscorlib]System.Object
{
.method public hidebysig static void SimpleNonGenericForeach(class [mscorlib]System.Collections.IEnumerable enumerable) cil managed
{
// Code size 50 (0x32)
.maxstack 1
.locals init (object V_0,
class [mscorlib]System.Collections.IEnumerator V_1,
class [mscorlib]System.IDisposable V_2)
IL_0000: ldarg.0
IL_0001: callvirt instance class [mscorlib]System.Collections.IEnumerator [mscorlib]System.Collections.IEnumerable::GetEnumerator()
IL_0006: stloc.1
.try
{
IL_0007: br.s IL_0016
IL_0009: ldloc.1
IL_000a: callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current()
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: call void [mscorlib]System.Console::WriteLine(object)
IL_0016: ldloc.1
IL_0017: callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()
IL_001c: brtrue.s IL_0009
IL_001e: leave.s IL_0031
} // end .try
finally
{
IL_0020: ldloc.1
IL_0021: isinst [mscorlib]System.IDisposable
IL_0026: stloc.2
IL_0027: ldloc.2
IL_0028: brfalse.s IL_0030
IL_002a: ldloc.2
IL_002b: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_0030: endfinally
} // end handler
IL_0031: ret
} // end of method NoForEachStatement::SimpleNonGenericForeach
.method public hidebysig static void SimpleForeachOverInts(class [mscorlib]System.Collections.Generic.IEnumerable`1<int32> enumerable) cil managed
{
// Code size 43 (0x2b)
.maxstack 1
.locals init (int32 V_0,
class [mscorlib]System.Collections.Generic.IEnumerator`1<int32> V_1)
IL_0000: ldarg.0
IL_0001: callvirt instance class [mscorlib]System.Collections.Generic.IEnumerator`1<!0> class [mscorlib]System.Collections.Generic.IEnumerable`1<int32>::GetEnumerator()
IL_0006: stloc.1
.try
{
IL_0007: br.s IL_0016
IL_0009: ldloc.1
IL_000a: callvirt instance !0 class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>::get_Current()
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: call void [mscorlib]System.Console::WriteLine(int32)
IL_0016: ldloc.1
IL_0017: callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()
IL_001c: brtrue.s IL_0009
IL_001e: leave.s IL_002a
} // end .try
finally
{
IL_0020: ldloc.1
IL_0021: brfalse.s IL_0029
IL_0023: ldloc.1
IL_0024: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_0029: endfinally
} // end handler
IL_002a: ret
} // end of method NoForEachStatement::SimpleForeachOverInts
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method NoForEachStatement::.ctor
} // end of class ICSharpCode.Decompiler.Tests.TestCases.Ugly.NoForEachStatement
// =============================================================
// *********** DISASSEMBLY COMPLETE ***********************
| ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/NoForEachStatement.opt.il/0 | {
"file_path": "ILSpy/ICSharpCode.Decompiler.Tests/TestCases/Ugly/NoForEachStatement.opt.il",
"repo_id": "ILSpy",
"token_count": 2126
} | 208 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.