This commit is contained in:
CortexCore 2025-03-09 13:38:23 +08:00
parent 8261a458e2
commit 18239a5ae4
67 changed files with 8573 additions and 831 deletions

View File

@ -240,6 +240,7 @@ namespace BITKit
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
public static string AppName { get; private set; } = nameof(BITApp);
public static UniTaskCompletionSource WalkUntilInitialize { get; set; } = new();
private static CancellationTokenSource CancellationTokenSource = new();
public static CancellationToken CancellationToken => CancellationTokenSource.Token;
public static InitializationState State;

View File

@ -13,28 +13,49 @@ namespace BITKit.Entities
public class EntitiesService:IEntitiesService,IDisposable
{
private readonly ILogger<EntitiesService> _logger;
private readonly IFixedTicker _ticker;
private static int _count;
public EntitiesService()
private static readonly ConcurrentQueue<IEntity> OnAddQueue = new();
private static ConcurrentDictionary<int, HashSet<int>> TypeCaches = new();
public EntitiesService(ILogger<EntitiesService> logger, IFixedTicker ticker)
{
_count++;
if (_count > 0)
{
throw new MulticastNotSupportedException();
}
public EntitiesService(ILogger<EntitiesService> logger)
{
_count++;
_logger = logger;
_ticker = ticker;
_ticker.Add(OnTick);
}
private void OnTick(float obj)
{
while (OnAddQueue.TryDequeue(out var entity))
{
OnAdd?.Invoke(entity);
foreach (var serviceDescriptor in entity.ServiceCollection)
{
var typeHash = serviceDescriptor.ServiceType.GetHashCode();
var hashSet = TypeCaches.GetOrCreate(typeHash);
hashSet.Add(entity.Id);
}
}
}
private static readonly ConcurrentDictionary<int, IEntity> Entities = new();
public event Action<IEntity> OnAdd;
public event Action<IEntity> OnRemove;
IEntity[] IEntitiesService.Entities => Entities.Values.ToArray();
IReadOnlyDictionary<int, IEntity> IEntitiesService.Entities => Entities;
public bool Register(IEntity entity)
{
if (!Entities.TryAdd(entity.Id, entity)) return false;
OnAdd?.Invoke(entity);
OnAddQueue.Enqueue(entity);
return true;
}
@ -42,8 +63,17 @@ namespace BITKit.Entities
{
if (!Entities.TryRemove(entity.Id, out _)) return false;
OnRemove?.Invoke(entity);
foreach (var serviceDescriptor in entity.ServiceCollection)
{
var typeHash = serviceDescriptor.ServiceType.GetHashCode();
var hashSet = TypeCaches.GetOrCreate(typeHash);
hashSet.Remove(entity.Id);
}
return true;
}
public CancellationToken CancellationToken => _cancellationTokenSource.Token;
private readonly CancellationTokenSource _cancellationTokenSource = new();
public IEntity Get(int id)
@ -262,6 +292,8 @@ namespace BITKit.Entities
_logger.LogInformation($"已释放,还剩{_count}个实例");
_cancellationTokenSource?.Dispose();
_ticker.Remove(OnTick);
}
}
}

View File

@ -8,24 +8,24 @@ namespace BITKit.Entities
{
public class Entity : IEntity, IDisposable
{
public Entity()
{
ServiceCollection.AddSingleton<IEntity>(this);
}
public void WaitForInitializationComplete()
{
throw new NotImplementedException();
}
public int Id { get; set; } = Guid.NewGuid().GetHashCode();
public CancellationToken CancellationToken => _cancellationTokenSource.Token;
private readonly CancellationTokenSource _cancellationTokenSource = new();
public CancellationToken CancellationToken { get; set; }
public IServiceProvider ServiceProvider => _serviceProvider ??= ServiceCollection.BuildServiceProvider();
private ServiceProvider _serviceProvider;
public IServiceCollection ServiceCollection { get; } = new ServiceCollection();
public IServiceCollection ServiceCollection
{
get
{
if (_serviceCollection is not null) return _serviceCollection;
_serviceCollection = new ServiceCollection();
_serviceCollection.AddSingleton<IEntity>(this);
return _serviceCollection;
}
}
private IServiceCollection _serviceCollection;
public object[] GetServices() => ServiceCollection.ToArray()
.Select(x => _serviceProvider.GetService(x.ServiceType)).ToArray();
public void Inject(object obj)
{
foreach (var fieldInfo in obj.GetType().GetFields(ReflectionHelper.Flags))
@ -39,7 +39,6 @@ namespace BITKit.Entities
public void Dispose()
{
_cancellationTokenSource.Cancel();
_serviceProvider.Dispose();
}
}

View File

@ -1,5 +1,6 @@
using System.Threading;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using Microsoft.Extensions.DependencyInjection;
#if NET5_0_OR_GREATER
@ -16,7 +17,6 @@ namespace BITKit.Entities
CancellationToken CancellationToken { get; }
IServiceProvider ServiceProvider { get; }
IServiceCollection ServiceCollection { get; }
object[] GetServices();
void Inject(object obj);
}
/// <summary>
@ -35,7 +35,7 @@ namespace BITKit.Entities
/// <summary>
/// 所有Entity
/// </summary>
IEntity[] Entities { get; }
IReadOnlyDictionary<int,IEntity> Entities { get; }
/// <summary>
/// 注册Entity
/// </summary>

106
Src/Core/ECS/UnityEntity.cs Normal file
View File

@ -0,0 +1,106 @@
#if UNITY_5_3_OR_NEWER
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using Microsoft.Extensions.DependencyInjection;
using UnityEngine;
using Object = UnityEngine.Object;
namespace BITKit.Entities
{
[DisallowMultipleComponent]
[DefaultExecutionOrder(-1)]
public class UnityEntity : MonoBehaviour,IEntity
{
private IEntitiesService _entitiesService;
private IEntity _entity;
private void Start()
{
_entitiesService = BITApp.ServiceProvider.GetRequiredService<IEntitiesService>();
if (_entitiesService.Entities.ContainsKey(gameObject.GetInstanceID())) return;
var entity = new Entity()
{
Id = gameObject.GetInstanceID(),
CancellationToken = destroyCancellationToken
};
var idComponent = new IdComponent()
{
Id = entity.Id,
Name = gameObject.name,
};
entity.ServiceCollection.AddSingleton(idComponent);
foreach (var component in GetComponents<Component>())
{
var type = component.GetType();
foreach (var x in type.GetInterfaces())
{
entity.ServiceCollection.AddSingleton(x, component);
}
while (type is not null)
{
var baseType = type.BaseType;
try
{
switch (baseType)
{
case null:
case not null when baseType == typeof(object):
case not null when baseType == typeof(Object):
case not null when baseType == typeof(MonoBehaviour):
case not null when baseType == typeof(Behaviour):
case not null when baseType == typeof(Component):
case not null when baseType == typeof(Component):
throw new OperationCanceledException();
}
}
catch (OperationCanceledException)
{
break;
}
entity.ServiceCollection.AddSingleton(baseType, component);
type = type.BaseType;
}
}
entity.ServiceCollection.AddSingleton(gameObject);
entity.ServiceCollection.AddSingleton(transform);
destroyCancellationToken.Register(Dispose);
_entity = entity;
_entitiesService.Register(entity);
}
private void Dispose()
{
_entitiesService?.UnRegister(_entity);
}
public int Id => _entity.Id;
public CancellationToken CancellationToken => _entity.CancellationToken;
public IServiceProvider ServiceProvider => _entity.ServiceProvider;
public IServiceCollection ServiceCollection => _entity.ServiceCollection;
public void Inject(object obj)
{
_entity.Inject(obj);
}
}
}
#endif

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 14ba5b1e81092234d944bec5c7063bc1
guid: 230e015069b45484f9c85d1aba1e901c
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@ -15,6 +15,9 @@ namespace BITKit
/// </summary>
public interface IRuntimeItemContainer:IBinarySerialize
{
public bool AllowAdd { get; set; }
public bool AllowRemove { get; set; }
public ValidHandle IsBusy { get; }
/// <summary>
/// 物品容器的唯一Id
@ -96,6 +99,8 @@ namespace BITKit
throw new NotImplementedException();
}
public bool AllowAdd { get; set; }
public bool AllowRemove { get; set; }
public ValidHandle IsBusy { get; } = new();
public int Id { get; set; }
public IRuntimeItem[] GetItems()=>Items.Values.ToArray();

View File

@ -9,13 +9,16 @@ namespace BITKit.Pool
/// </summary>
public interface IPoolService
{
public int DefaultCapacity { get; set; }
/// <summary>
/// 生成对象
/// </summary>
/// <param name="path">可寻址路径</param>
/// <param name="prefab">直接提供的预制体</param>
/// <typeparam name="T">类型</typeparam>
/// <returns></returns>
UniTask<T> Spawn<T>(string path) where T : class;
UniTask<T> Spawn<T>(string path,object prefab=null) where T : class;
/// <summary>
/// 回收对象
/// </summary>

View File

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
@ -24,7 +25,6 @@ namespace BITKit.StateMachine
public bool Enabled { get; set; } = true;
public T CurrentState { get;private set; }
public T NextOrCurrentState => _nextTargetState.IfNotAllow(CurrentState);
public event Action<T, T> OnStateChanging;
public event Func<T, T, UniTask> OnStateChangeAsync;
public event Action<T, T> OnStateChanged;
@ -35,41 +35,41 @@ namespace BITKit.StateMachine
public readonly ValidHandle IsBusy=new();
private readonly CancellationTokenSource _cancellationTokenSource=new();
private readonly Dictionary<int, T> _dictionary = new();
private readonly Optional<T> _nextTargetState = new();
private readonly HashSet<int> _isRegistered = new();
private CancellationTokenSource _transitionCts;
private T _entryCompletedState;
public async void Initialize()
{
await IsBusy;
if(_cancellationTokenSource.IsCancellationRequested)return;
using var _ = IsBusy.GetHandle();
foreach (var (_,value) in StateDictionary)
{
if (_isRegistered.Add(value.Identifier))
{
await value.InitializeAsync();
value.Initialize();
}
}
}
public async void UpdateState(float deltaTime)
{
if (CurrentState is null) return;
if (_entryCompletedState is null) return;
using var _ = IsBusy.GetHandle();
CurrentState.OnStateUpdate(deltaTime);
await CurrentState.OnStateUpdateAsync(deltaTime);
_entryCompletedState.OnStateUpdate(deltaTime);
await _entryCompletedState.OnStateUpdateAsync(deltaTime);
}
public async void DisposeState()
public void DisposeState()
{
await IsBusy;
if (_cancellationTokenSource.IsCancellationRequested) return;
if (CurrentState is null) return;
using var _ = IsBusy.GetHandle();
CurrentState.Enabled = false;
await CurrentState.OnStateExitAsync(CurrentState, null);
CurrentState.OnStateExit(CurrentState, null);
CurrentState = null;
TransitionState(null);
}
public T TransitionState<TState>() where TState : T
{
T nextState;
@ -96,50 +96,60 @@ namespace BITKit.StateMachine
nextState.Identifier = nextState.GetHashCode();
}
}
if (Equals(nextState, CurrentState)) return;
if(_nextTargetState.Allow && Equals(_nextTargetState.Value,nextState))return;
if (_nextTargetState.Allow)
{
_nextTargetState.Value = nextState;
return;
}
_nextTargetState.SetValueThenAllow(nextState);
await IsBusy;
if(CurrentState==nextState)return;
if(_cancellationTokenSource.IsCancellationRequested)return;
using var _ = IsBusy.GetHandle();
OnStateChanging?.Invoke(CurrentState,nextState);
await OnStateChangeAsync.UniTaskFunc(CurrentState,nextState);
if (nextState is not null && _dictionary.TryAdd(nextState.Identifier, nextState))
{
await nextState.InitializeAsync();
if(_cancellationTokenSource.IsCancellationRequested)return;
nextState.Initialize();
}
if (CurrentState is not null)
{
CurrentState.Enabled = false;
await CurrentState.OnStateExitAsync(CurrentState, nextState);
if(_cancellationTokenSource.IsCancellationRequested)return;
CurrentState.OnStateExit(CurrentState,nextState);
}
if (_nextTargetState.Allow && _nextTargetState.Value != nextState)
{
return;
}
var tempState = CurrentState;
CurrentState = _nextTargetState.Value;
_nextTargetState.Clear();
nextState.Enabled = true;
await nextState.OnStateEntryAsync(tempState);
CurrentState = nextState;
_transitionCts?.Cancel();
_transitionCts = new CancellationTokenSource();
var ct = _transitionCts.Token;
await IsBusy;
using var _ = IsBusy.GetHandle();
if(ct.IsCancellationRequested||_cancellationTokenSource.IsCancellationRequested)return;
OnStateChanging?.Invoke(tempState,nextState);
if (tempState is not null)
{
if (_entryCompletedState == tempState)
{
_entryCompletedState = null;
}
tempState.Enabled = false;
await tempState.OnStateExitAsync(tempState, nextState);
tempState.OnStateExit(tempState,nextState);
if(_cancellationTokenSource.IsCancellationRequested)return;
nextState.OnStateEntry(tempState);
OnStateChanged?.Invoke(tempState,nextState);
}
if(ct.IsCancellationRequested)return;
await OnStateChangeAsync.UniTaskFunc(CurrentState,nextState);
if(ct.IsCancellationRequested)return;
if (nextState is not null)
{
if (_isRegistered.Add(nextState.Identifier))
{
await RegisterAsync(nextState);
if(ct.IsCancellationRequested || _cancellationTokenSource.IsCancellationRequested)return;
}
nextState.Enabled = true;
await nextState.OnStateEntryAsync(CurrentState);
nextState.OnStateEntry(CurrentState);
if(ct.IsCancellationRequested || _cancellationTokenSource.IsCancellationRequested)return;
_entryCompletedState = nextState;
}
OnStateChanged?.Invoke(tempState, nextState);
}
public T TransitionState(T nextState)
@ -148,26 +158,48 @@ namespace BITKit.StateMachine
return nextState;
}
private async UniTask RegisterAsync(T newState)
{
StateDictionary.TryAdd(newState.GetType(),newState);
_dictionary.TryAdd(newState.Identifier, newState);
newState.Initialize();
await newState.InitializeAsync();
}
public async void Register(T newState)
{
await IsBusy;
using var _ = IsBusy.GetHandle();
await RegisterAsync(newState);
}
public async void UnRegister(T newState)
{
if (newState is null) return;
if (Dictionary.ContainsKey(newState.Identifier) is false) return;
_dictionary.Remove(newState.Identifier);
await IsBusy;
using var _ = IsBusy.GetHandle();
if (Equals(CurrentState, newState))
{
await CurrentState.OnStateExitAsync(CurrentState, null);
CurrentState.OnStateExit(CurrentState, null);
if (CurrentState is IAsyncDisposable asyncDisposable)
CurrentState = null;
}
if (newState is IAsyncDisposable asyncDisposable)
{
await asyncDisposable.DisposeAsync();
}
if (CurrentState is IDisposable disposable)
if (newState is IDisposable disposable)
{
disposable.Dispose();
}
CurrentState = null;
}
OnStateUnRegistered?.Invoke(newState);
}

View File

@ -1,8 +1,10 @@
using System.Collections.Generic;
namespace BITKit
{
public interface ITag
{
int Hash { get; }
string[] GetTags();
IReadOnlyCollection<string> Tags { get; }
}
}

View File

@ -41,7 +41,7 @@ namespace BITKit
/// <summary>
/// 异步循环
/// </summary>
public interface IAsyncTicker
public interface IAsyncTicker:IDisposable
{
ulong TickCount { get; }
int TickRate { get; set; }
@ -183,6 +183,7 @@ namespace BITKit
public void Dispose()
{
OnTickAsync = null;
_isDisposed = true;
_timer.Stop();
_timer.Dispose();

View File

@ -35,26 +35,18 @@ namespace BITKit.Tween
return new TweenSequence();
}
public static async UniTask MoveToForward(
Action<float> setter,
float from,
float to,
float duration = 1,
CancellationToken cancellationToken = default
)
public static async UniTask Lerp<T>(Action<T> setter,T from,T to,float duration, Func<T, T,float, T> lerp,CancellationToken cancellationToken = default)
{
var t = 0f;
var delta = 1 / duration;
var delta = 1f / duration;
setter(from);
//BIT4Log.Log<TweenSequence>($"已创建Tween,from:[{from}]to:[{to}]duration:[{duration}]delta:[{delta}]");
while (t < 1 && cancellationToken.IsCancellationRequested is false)
{
t = math.clamp(t + delta*BITApp.Time.DeltaTime, 0, 1);
var next = math.lerp(from, to, t);
//BIT4Log.Log<TweenSequence>($"当前进度:[{t}]next:[{next}]");
var next = lerp(from, to, t);
#if UNITY_5_3_OR_NEWER
await UniTask.NextFrame(cancellationToken);
await UniTask.SwitchToMainThread(cancellationToken);
#else
await UniTask.Yield();
#endif

View File

@ -7,5 +7,7 @@ namespace BITKit.UX
public interface IUXDialogue
{
void Show(string content,string title = "Alert",Action confirmAction=null,Action<bool> onChoose=null);
}
}

View File

@ -42,13 +42,9 @@ namespace BITKit
public static implicit operator T(References<T> self) => self.Get();
}
[System.Serializable]
public record Reference : References
[Serializable]
public struct Reference : IReference
{
public Reference()
{
}
public Reference(string value)
{
this.value = value;
@ -57,8 +53,7 @@ namespace BITKit
[UnityEngine.TextArea]
#endif
public string value;
public override string Get() => value;
public override string ToString() => value;
public string Get() => value;
}
[System.Serializable]

View File

@ -27,7 +27,7 @@ namespace BITKit
public class MyHandle:IDisposable
{
private readonly ValidHandle _validHandle;
private bool _isDisable = false;
private readonly bool _isDisable;
public MyHandle(ValidHandle validHandle,bool isDisable = false)
{
_validHandle = validHandle;
@ -61,106 +61,76 @@ namespace BITKit
public override string ToString()
{
return $"Allow:{enableHandle}\nElements:{string.Join("\n",objs)}\nDisableElements:{string.Join("\n",disableObjs)}";
return $"Allow:{_enableHandle}\nElements:{string.Join("\n",_objs)}\nDisableElements:{string.Join("\n",_disableObjs)}";
}
public ValidHandle() {}
public ValidHandle(Action<bool> boolDelegate)
{
AddListener(boolDelegate);
EventOnEnableChanged?.Invoke(enableHandle);
_eventOnEnableChanged?.Invoke(_enableHandle);
}
public static implicit operator bool(ValidHandle validHandle)
{
return !validHandle._isDisposed && validHandle.enableHandle;
return !validHandle._isDisposed && validHandle._enableHandle;
}
public bool Allow => this;
private bool enableHandle;
private bool _enableHandle;
/// <summary>
/// ⚠Dont operate this field directly
/// </summary>
public readonly List<object> objs = new List<object>();
private readonly HashSet<object> _objs = new();
/// <summary>
/// ⚠Dont operate this field directly
/// </summary>
public readonly List<object> disableObjs = new List<object>();
private bool tempEnable;
private Action<bool> EventOnEnableChanged;
private readonly HashSet<object> _disableObjs = new();
private bool _tempEnable;
private Action<bool> _eventOnEnableChanged;
private readonly ConcurrentQueue<UniTaskCompletionSource> _completionSources = new();
private bool _isDisposed;
public void AddElement(object obj)
{
if (objs.Contains(obj))
{
}
else
{
objs.Add(obj);
}
_objs.Add(obj);
CheckEnable();
}
private void CheckEnable()
{
tempEnable = objs.Count > 0 && disableObjs.Count == 0;
if (tempEnable != enableHandle)
{
enableHandle = tempEnable;
if (EventOnEnableChanged is not null)
{
EventOnEnableChanged.Invoke(enableHandle);
}
if (tempEnable) return;
_tempEnable = _objs.Count > 0 && _disableObjs.Count == 0;
if (_tempEnable == _enableHandle) return;
_enableHandle = _tempEnable;
_eventOnEnableChanged?.Invoke(_enableHandle);
if (_tempEnable) return;
if (_completionSources.TryDequeue(out var cs))
{
cs.TrySetResult();
}
}
}
public void RemoveElement(object obj)
{
if (objs.Contains(obj))
if (_objs.Contains(obj))
{
objs.Remove(obj);
_objs.Remove(obj);
}
else
{
}
CheckEnable();
}
public int lenght => objs.Count;
public string[] GetElements()
{
List<string> elementNames = new List<string>();
for (int i = 0; i < objs.Count; i++)
{
elementNames.Add(objs[i].ToString());
}
return elementNames.ToArray();
}
public bool Contains(object obj) => objs.Contains(obj);
public int Lenght => _objs.Count;
public bool Contains(object obj) => _objs.Contains(obj);
public void AddDisableElements(object obj)
{
if (disableObjs.Contains(obj))
{
}
else
{
disableObjs.Add(obj);
}
_disableObjs.Add(obj);
CheckEnable();
}
public void RemoveDisableElements(object obj)
{
if (disableObjs.Contains(obj))
if (_disableObjs.Contains(obj))
{
disableObjs.Remove(obj);
_disableObjs.Remove(obj);
}
else
{
@ -191,22 +161,22 @@ namespace BITKit
}
public void Invoke()
{
var enable = disableObjs.Count == 0 && objs.Count > 0;
EventOnEnableChanged?.Invoke(enable);
var enable = _disableObjs.Count == 0 && _objs.Count > 0;
_eventOnEnableChanged?.Invoke(enable);
}
public void Invoke(bool value)
{
EventOnEnableChanged?.Invoke(value);
_eventOnEnableChanged?.Invoke(value);
}
public void AddListener(Action<bool> action)
{
EventOnEnableChanged+= action;
_eventOnEnableChanged+= action;
}
public void RemoveListener(Action<bool> action)
{
if(EventOnEnableChanged is not null && action is not null)
if(_eventOnEnableChanged is not null && action is not null)
{
EventOnEnableChanged -= action;
_eventOnEnableChanged -= action;
}
}
public UniTask.Awaiter GetAwaiter()
@ -221,17 +191,17 @@ namespace BITKit
}
public void Clear()
{
objs.Clear();
disableObjs.Clear();
_objs.Clear();
_disableObjs.Clear();
Invoke();
}
public void Dispose()
{
_isDisposed = true;
objs.Clear();
disableObjs.Clear();
EventOnEnableChanged = null;
_objs.Clear();
_disableObjs.Clear();
_eventOnEnableChanged = null;
}
}

View File

@ -8,12 +8,6 @@ namespace BITKit.WorldNode
/// </summary>
public interface IWorldNode
{
public int Id { get; set; }
public object WorldObject { get; set; }
public void Initialize()
{
}
}
}

View File

@ -1,41 +0,0 @@
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace BITKit.WorldNode
{
/// <summary>
/// 世界节点服务,所有动态世界节点通过此接口注册
/// </summary>
public interface IWorldNodeService
{
public IReadOnlyDictionary<int, HashSet<IWorldNode>> WorldNodes { get; }
public void RegisterNode(IWorldNode node);
public event Action<IWorldNode> OnNodeRegistered;
}
/// <summary>
/// 世界节点默认实现
/// </summary>
[Serializable]
public class WorldNodeService : IWorldNodeService,IDisposable
{
public static event Action<IWorldNode> OnNodeRegistered;
IReadOnlyDictionary<int, HashSet<IWorldNode>> IWorldNodeService.WorldNodes => WorldNodes;
private static readonly ConcurrentDictionary<int, HashSet<IWorldNode>> WorldNodes = new();
public void RegisterNode(IWorldNode node)
{
OnNodeRegistered?.Invoke(node);
WorldNodes.GetOrCreate(node.Id).Add(node);
}
event Action<IWorldNode> IWorldNodeService.OnNodeRegistered
{
add=>OnNodeRegistered+=value;
remove=>OnNodeRegistered-=value;
}
public void Dispose()
{
WorldNodes.Clear();
}
}
}

View File

@ -2,37 +2,30 @@
using System;
using System.Collections;
using System.Collections.Generic;
using BITKit.Entities;
using Microsoft.Extensions.DependencyInjection;
using UnityEngine;
namespace BITKit.WorldNode
{
public sealed class UnityNode : MonoBehaviour,IWorldNode
[RequireComponent(typeof(UnityEntity))]
public sealed class UnityNode : MonoBehaviour
{
[SerializeReference, SubclassSelector] private IWorldNodeService worldNodeService = new WorldNodeService();
[SerializeReference, SubclassSelector] private IWorldNode worldNode;
public int Id { get; set; }
public IWorldNode WorldNode => worldNode;
public object WorldObject
{
get => gameObject;
set=>throw new InvalidOperationException("Cannot set WorldObject");
}
private void Start()
{
if (worldNode is null)
if(worldNode is null)return;
var entity = GetComponent<IEntity>();
var type = worldNode.GetType();
GetComponent<IEntity>().ServiceCollection.AddSingleton(type,worldNode);
foreach (var interfaceType in type.GetInterfaces())
{
Debug.LogWarning("WorldNode is null");
return;
entity.ServiceCollection.AddSingleton(interfaceType, worldNode);
}
Id = gameObject.GetInstanceID();
worldNode.Id = Id;
worldNode.WorldObject = gameObject;
worldNode.Initialize();
worldNodeService.RegisterNode(worldNode);
Destroy(this);
}
}
}

View File

@ -0,0 +1,33 @@
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
#if UNITY_5_3_OR_NEWER
using UnityEngine;
#endif
namespace BITKit.WorldNode
{
[Serializable]
public class WorldInfoNode : IWorldNode
{
#if UNITY_5_3_OR_NEWER
[SerializeReference, SubclassSelector]
private IReference name;
[SerializeReference, SubclassSelector]
private IReference description;
public string Name
{
get => name?.Value;
set => name = new Reference(value);
}
public string Description
{
get => description?.Value;
set=>description = new Reference(value);
}
#endif
}
}

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: ca82e09109a03de47b638f35b49b59e5
guid: 5e1cbe087263f1342abbc3c6fb5c4068
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@ -1,60 +0,0 @@
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
#if UNITY_5_3_OR_NEWER
using UnityEngine;
#endif
namespace BITKit.WorldNode
{
[Serializable]
public struct WorldInfoNode : IWorldNode
{
// ReSharper disable once InconsistentNaming
#if UNITY_5_3_OR_NEWER
[SerializeReference,SubclassSelector]
#endif
private IReference name;
// ReSharper disable once InconsistentNaming
#if UNITY_5_3_OR_NEWER
[SerializeReference,SubclassSelector]
#endif
private IReference description;
#if UNITY_5_3_OR_NEWER
public void Initialize()
{
Name = name?.Value;
Description = description?.Value;
}
#endif
public int Id { get; set; }
public object WorldObject { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public sealed class WorldInfoNodeService : IDisposable
{
public IReadOnlyDictionary<int, WorldInfoNode> WorldInfoNodes => InfoNodes;
private readonly IWorldNodeService _worldNodeService;
private static readonly ConcurrentDictionary<int, WorldInfoNode> InfoNodes = new();
public WorldInfoNodeService(IWorldNodeService worldNodeService)
{
_worldNodeService = worldNodeService;
_worldNodeService.OnNodeRegistered += OnNodeRegistered;
}
private void OnNodeRegistered(IWorldNode obj)
{
if (obj is not WorldInfoNode infoNode) return;
InfoNodes.TryAdd(obj.Id, infoNode);
}
public void Dispose()
{
InfoNodes.Clear();
}
}
}

View File

@ -5,13 +5,8 @@ using System.Collections.Generic;
namespace BITKit.WorldNode
{
[Serializable]
public struct WorldInfoNpcStartNode:IWorldNode
public class WorldInfoNpcStartNode:IWorldNode
{
public string Address;
public int Id { get; set; }
public object WorldObject { get; set; }
public void Initialize()
{
}
}
}

View File

@ -5,14 +5,8 @@ using System.Collections.Generic;
namespace BITKit.WorldNode
{
[Serializable]
public struct WorldInfoPlayerStart:IWorldNode
public class WorldInfoPlayerStart:IWorldNode
{
public static WorldInfoPlayerStart Current { get; set; }
public int Id { get; set; }
public object WorldObject { get; set; }
public void Initialize()
{
Current = this;
}
}
}

View File

@ -19,8 +19,6 @@ namespace BITKit.WorldNode
public IReference MapName;
public float3 Position;
public float3 EulerAngle;
public int Id { get; set; }
public object WorldObject { get; set; }
}
}

View File

@ -6101,7 +6101,7 @@ MonoBehaviour:
italicTypeface: {fileID: 0}
- regularTypeface: {fileID: 0}
italicTypeface: {fileID: 0}
- regularTypeface: {fileID: 11400000, guid: 7b6a2cbff5c66dc42a81b604c826c04d, type: 2}
- regularTypeface: {fileID: 0}
italicTypeface: {fileID: 0}
- regularTypeface: {fileID: 0}
italicTypeface: {fileID: 0}

View File

@ -101838,15 +101838,15 @@ MonoBehaviour:
italicTypeface: {fileID: 0}
- regularTypeface: {fileID: 0}
italicTypeface: {fileID: 0}
- regularTypeface: {fileID: 11400000, guid: 7b6a2cbff5c66dc42a81b604c826c04d, type: 2}
- regularTypeface: {fileID: 0}
italicTypeface: {fileID: 0}
- regularTypeface: {fileID: 0}
italicTypeface: {fileID: 0}
- regularTypeface: {fileID: 11400000, guid: 7b6a2cbff5c66dc42a81b604c826c04d, type: 2}
italicTypeface: {fileID: 0}
- regularTypeface: {fileID: 11400000}
- regularTypeface: {fileID: 0}
italicTypeface: {fileID: 0}
- regularTypeface: {fileID: 11400000}
- regularTypeface: {fileID: 0}
italicTypeface: {fileID: 0}
m_RegularStyleWeight: 0
m_RegularStyleSpacing: 0

Binary file not shown.

View File

@ -0,0 +1,21 @@
fileFormatVersion: 2
guid: 8b7684d3e4f46a246a45689991580374
TrueTypeFontImporter:
externalObjects: {}
serializedVersion: 4
fontSize: 16
forceTextureCase: -2
characterSpacing: 0
characterPadding: 1
includeFontData: 1
fontNames:
- Source Han Mono SC
fallbackFontReferences: []
customCharacters:
fontRenderingMode: 0
ascentCalculationMode: 1
useLegacyBoundsCalculation: 0
shouldRoundAdvanceValue: 1
userData:
assetBundleName:
assetBundleVariant:

View File

@ -34,21 +34,47 @@ namespace BITKit.IO
var scriptableObject = objs[index];
var entity = new Entity();
var idComponent = new IdComponent();
var idComponent = new IdComponent()
{
Name = scriptableObject.name
};
entity.ServiceCollection.AddSingleton(idComponent);
var type = scriptableObject.GetType();
var typeName = type.Name;
entity.ServiceCollection.AddSingleton(type, scriptableObject);
foreach (var x in type.GetInterfaces())
{
entity.ServiceCollection.AddSingleton(x, scriptableObject);
}
while (type is not null)
{
if (type.BaseType is null) break;
entity.ServiceCollection.AddSingleton(type.BaseType, scriptableObject);
type = type.BaseType;
typeName += $":{type.Name}";
}
_entitiesService.Register(entity);
logger?.LogInformation($"已加载:{scriptableObject.name}:{type.Name},剩余:{index + 1}/{objs.Count}");
logger?.LogInformation($"已加载:{scriptableObject.name}:{typeName},剩余:{index + 1}/{objs.Count}");
_registeredEntities.Add(entity);
continue;
}
logger?.LogInformation("加载完成");
return;
}
public void Dispose()

View File

@ -135,6 +135,8 @@ namespace BITKit
[RuntimeInitializeOnLoadMethod]
private static void Reload()
{
BITApp.WalkUntilInitialize = new();
IsPlaying = true;
//启动BITApp

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 1705803e58f488146b0c364b69f275ff
guid: ee77d81b8f27d6a44923a2a6901a66e0
folderAsset: yes
DefaultImporter:
externalObjects: {}

View File

@ -1,10 +1,11 @@
{
"name": "BITKit.Extensions.TranslucentImage",
"name": "Net.BITKit.Impact.Unity",
"rootNamespace": "",
"references": [
"GUID:14fe60d984bf9f84eac55c6ea033a8f4",
"GUID:6ef4ed8ff60a7aa4bb60a8030e6f4008",
"GUID:ff218ee40fe2b8648ab3234d56415557"
"GUID:89bd0da52dc3cc94daadea6252c6ad1b",
"GUID:d525ad6bd40672747bde77962f1c401e",
"GUID:49b49c76ee64f6b41bf28ef951cb0e50"
],
"includePlatforms": [],
"excludePlatforms": [],
@ -12,9 +13,7 @@
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [
"LeTai_TranslucentImage"
],
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: f4dea7f9c2d5c3d4abb7467736ee56df
guid: 24866f14213d2124aa20be037476b521
AssemblyDefinitionImporter:
externalObjects: {}
userData:

View File

@ -0,0 +1,28 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using AYellowpaper.SerializedCollections;
using BITKit;
using UnityEngine;
namespace Net.BITKit.Impact
{
public class ScriptableImpact : ScriptableObject,ITag
{
[SerializeReference, SubclassSelector] private IReference[] tags;
[SerializeField] private int priority;
[SerializeField] private Transform[] prefabs;
[SerializeField] private AudioClip[] audioClips;
public int Hash { get; set; }
public IReadOnlyCollection<string> Tags => tags.Select(x=>x.Get()).ToArray();
public Transform Prefab => prefabs.Random();
public AudioClip AudioClip => audioClips.Random();
public int Priority => priority;
}
}

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 45ff73d2202441b44a5453c22ebf0dab
guid: ac8fd6229773587428b5dca77471e986
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@ -4,6 +4,7 @@ using UnityEngine;
using UnityEngine.InputSystem;
using System;
using System.Linq;
using UnityEngine.InputSystem.Controls;
namespace BITKit
{
@ -11,7 +12,7 @@ namespace BITKit
{
public static bool JustPressed(this InputAction.CallbackContext self)
{
return self.interaction is null && self.started;
return self is { started:true, control: ButtonControl { wasPressedThisFrame: true , isPressed:true} };
}
public static InputAction RegisterCallback(this InputAction self, Action<InputAction.CallbackContext> action)
{

View File

@ -7,37 +7,6 @@ using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace BITKit
{
public abstract class UnityLogger:ILogger
{
[HideInCallstack]
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
switch (logLevel)
{
case LogLevel.Critical:
case LogLevel.Error:
if (exception is not null)
{
Debug.LogException(exception);
}
else
{
Debug.LogError($"{CurrentScope}:{state.ToString()}");
}
break;
default:
Debug.Log($"{CurrentScope}:{state.ToString()}");
break;
}
}
public bool IsEnabled(LogLevel logLevel) => true;
private string CurrentScope { get; set; }
public IDisposable BeginScope<TState>(TState state) where TState : notnull
{
CurrentScope = typeof(TState).Name;
return null;
}
}
public sealed class UnityLogger<T>:ILogger<T>
{
[HideInCallstack]
@ -53,11 +22,11 @@ namespace BITKit
}
else
{
Debug.LogError($"{typeof(T).Name}:{state.ToString()}");
Debug.LogError($"{typeof(T).CSharpName()}:{state.ToString()}");
}
break;
default:
Debug.Log($"<b>{typeof(T).Name}</b>:{state.ToString()}");
Debug.Log($"<b>{typeof(T).CSharpName()}</b>:{state.ToString()}");
break;
}
}

View File

@ -27,22 +27,31 @@ namespace BITKit.Physics
var vertices = _mesh.vertices;
if (vertices.Length > 2048) return false;
if (vertices.Length > 256) return false;
var minPos = new Vector3(64, 64, 64);
var minDistance = 64f;
for (var index = 0; index < _mesh.triangles.Length; index+=3)
{
var x = vertices[_mesh.triangles[index]];
if (Vector3.Distance(x, _position) > minDistance)
{
continue;
}
var y = vertices[_mesh.triangles[index + 1]];
var z = vertices[_mesh.triangles[index + 2]];
var pos = GeometryUtils.GetPosInTriangle(x, y, z, _position);
if (Vector3.Distance(pos, _position) < Vector3.Distance(minPos, _position))
{
var distance = Vector3.Distance(pos, _position);
if (!(distance < minDistance)) continue;
minPos = pos;
}
minDistance = distance;
}
position = minPos;

View File

@ -42,7 +42,9 @@ namespace BITKit.Pool
ReadyPool.Clear();
}
public async UniTask<T> Spawn<T>(string path) where T : class
public int DefaultCapacity { get; set; } = 8;
public async UniTask<T> Spawn<T>(string path,object prefab) where T : class
{
if (Pool.ContainsKey(path))
{
@ -55,7 +57,7 @@ namespace BITKit.Pool
return obj as T;
}
if (usingList.Count>0)
if (usingList.Count>=DefaultCapacity)
{
obj = usingList[0];
usingList.RemoveAt(0);
@ -81,13 +83,33 @@ namespace BITKit.Pool
#if UNITY_5_3_OR_NEWER
if (typeof(Object).IsAssignableFrom(typeof(T)))
{
var asset =await ModService.LoadAsset<T>(path);
var asset =prefab as T ?? await ModService.LoadAsset<T>(path);
if (asset is Object o)
{
var instance = Object.Instantiate(o);
list.Add(instance);
UsingPool.GetOrCreate(path).Add(instance);
ReadyPool.GetOrCreate(path);
if (instance is GameObject gameObject)
{
gameObject.GetCancellationTokenOnDestroy().Register(DisposeGo);
void DisposeGo()
{
Pool.GetOrCreate(path).TryRemove(gameObject);
UsingPool.GetOrCreate(path).TryRemove(gameObject);
var queue = ReadyPool.GetOrCreate(path);
var removeObjectList = new List<object>(queue);
removeObjectList.TryRemove(gameObject);
queue.Clear();
foreach (var x in removeObjectList)
{
queue.Enqueue(x);
}
}
}
return instance as T;
}
}

View File

@ -0,0 +1,18 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UnityAutoDestroyOnStart : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Destroy(gameObject);
}
// Update is called once per frame
void Update()
{
}
}

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 132a27b99db1e664692937ec23f40676
guid: 802bbaa627560f547ba5c71f6f7b4a0c
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@ -8,19 +8,10 @@ namespace BITKit
{
public class Tag : MonoBehaviour,ITag
{
[Header(Constant.Header.Settings)]
[Tooltip("It's will be deprecated in the future, use reference instead.")]
[SerializeField] private string[] tags;
[Tooltip("Disable when tags is not empty")]
[SerializeReference,SubclassSelector] private IReference[] reference;
public int Hash => _id is 0 ? _id = MathE.GetHash(GetTags()) : _id;
public int Hash => _id is 0 ? _id = MathE.GetHash(Tags) : _id;
private int _id;
public string[] GetTags() => CacheTags ??= reference?.Length > 0 ? reference.Select(x => x.Value).ToArray() : tags;
private string[] CacheTags;
public void SetTags(IReference[] newReference)
{
reference = newReference;
CacheTags = null;
}
public IReadOnlyCollection<string> Tags=> _cacheTags ??= reference.Select(x => x.Value).ToArray();
private string[] _cacheTags;
}
}

View File

@ -14,6 +14,7 @@ namespace BITKit
[Serializable]
public class IntervalTick:ITicker
{
[SerializeField]
private float interval;
public ulong TickCount=>IntervalTickService.GetTickCount(interval);

View File

@ -32,11 +32,6 @@ namespace BITKit.UX
_container.Clear();
_template =await ModService.LoadAsset<VisualTreeAsset>("ui_radial_menu-template");
RootVisualElement.RegisterCallback<PointerDownEvent>(x =>
{
UXService.Return();
});
}
protected override void OnPanelEntry()
{

View File

@ -74,7 +74,7 @@ namespace BITKit.UX
foreach (var fieldInfo in self.GetType()
.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
.Where(x => x.GetCustomAttribute<UXBindPathAttribute>() is not null)
)
{

View File

@ -461,6 +461,11 @@ namespace BITKit
return true;
}
component = self.GetComponentInParent<T>(true);
if (component is not null)
{
return true;
}
component = self.GetComponent<T>();
return component is not null;
}
public static bool TryGetFirstOrDefault<T>(this IEnumerable<T> self, out T value)

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: fdd91b53bafc0804d8d8382169b67308
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,19 @@
{
"name": "Net.Project.B.VFX.Unity",
"rootNamespace": "",
"references": [
"GUID:d525ad6bd40672747bde77962f1c401e",
"GUID:49b49c76ee64f6b41bf28ef951cb0e50",
"GUID:14fe60d984bf9f84eac55c6ea033a8f4",
"GUID:24866f14213d2124aa20be037476b521"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 21442fa5e0c49e3408652e96f6565891
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,63 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using BITKit;
using BITKit.Entities;
using Net.BITKit.Impact;
using UnityEngine;
namespace Net.BITKit.VFX
{
public class VFXService
{
private readonly IEntitiesService _entitiesService;
private readonly IReadOnlyCollection<ScriptableImpact> _scriptableImpacts;
public VFXService(IEntitiesService entitiesService)
{
_entitiesService = entitiesService;
_scriptableImpacts = _entitiesService.QueryComponents<ScriptableImpact>();
}
public AudioClip GetAudioClip(IReadOnlyCollection<string> tags)
{
var bestMatches = Search(tags);
return bestMatches.AudioClip;
}
public Transform GetPrefab(IReadOnlyCollection<string> tags)
{
var bestMatches = Search(tags);
return bestMatches.Prefab;
}
private ScriptableImpact Search(IReadOnlyCollection<string> tags)
{
var maxPoint = 0;
var max = new HashSet<ScriptableImpact>();
foreach (var impact in _scriptableImpacts)
{
var point = impact.Tags.Intersect(tags).Count();
if (point > maxPoint)
{
maxPoint = point;
max.Clear();
max.Add(impact);
}else if (point == maxPoint)
{
max.Add(impact);
}
}
if (max.Count is 1)
{
return max.First();
}
return max.OrderByDescending(x => x.Priority).First();
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0bee817d1b196f842899232c3a28d504
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -60,7 +60,7 @@ namespace BITKit.OpenWorld
#if UNITY_EDITOR
[BIT]
#endif
private void CalculateBounds()
public void CalculateBounds()
{
if (TryGetComponent<Collider>(out var _collider))
{

View File

@ -25,7 +25,6 @@ namespace BITKit.OpenWorld
private readonly ConcurrentDictionary<int, IWorldChunkObject> dictionary=new();
[SerializeReference, SubclassSelector] private ITicker ticker;
[SerializeReference, SubclassSelector] private ISceneService sceneService;
[SerializeField, ReadOnly] private int count;
[SerializeField, ReadOnly] private int tickTaskCount;
[SerializeField] private bool drawBounds;
@ -42,24 +41,13 @@ namespace BITKit.OpenWorld
protected virtual void Start()
{
sceneService?.RegisterLoadTaskAsync(LoadTask);
ticker.Add(OnTick);
destroyCancellationToken.Register(Dispose);
_quadtree = new QuadtreeRoot<IWorldChunkObject, Node<IWorldChunkObject>>(transform.position, size);
_camera = Camera.main;
}
private async UniTask LoadTask()
{
var frame=0;
while (count is 0 || frame++<32)
{
if (destroyCancellationToken.IsCancellationRequested) return;
await UniTask.NextFrame();
}
}
protected virtual void Dispose()
{
sceneService?.UnRegisterLoadTaskAsync(LoadTask);
ticker.Remove(OnTick);
_registerQueue.Clear();
_unregisterQueue.Clear();

View File

@ -14,6 +14,7 @@ namespace BITKit.OpenWorld
{
public class WorldTerrainBehaviour : MonoBehaviour,IWorldChunkObject
{
public static UniTaskCompletionSource WaitUntilInitialized = new();
[SerializeReference, SubclassSelector] private IReference sceneName;
[SerializeField] private Vector3 size;
[SerializeField] private Vector3 position;
@ -26,7 +27,15 @@ namespace BITKit.OpenWorld
var stopWatcher = new System.Diagnostics.Stopwatch();
stopWatcher.Start();
_sceneHandle = YooAssets.LoadSceneAsync(sceneName.Value,LoadSceneMode.Additive,priority:8);
await _sceneHandle;
try
{
await _sceneHandle.WithCancellation(destroyCancellationToken);
}
catch (OperationCanceledException)
{
}
stopWatcher.Stop();
Debug.Log($"加载场景 {sceneName.Value} 耗时 {stopWatcher.ElapsedMilliseconds}ms");
}

View File

@ -21,10 +21,11 @@ Material:
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: Billboard
m_Shader: {fileID: -6465566751694194690, guid: fc56a447eb0944f4f9fc3b51a4913759, type: 3}
m_Shader: {fileID: 4800000, guid: 86ce7e600deb17e429b8be445bb652f7, type: 3}
m_Parent: {fileID: 0}
m_ModifiedSerializedProperties: 0
m_ValidKeywords: []
m_ValidKeywords:
- SHAKEUV_ON
m_InvalidKeywords: []
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
@ -37,6 +38,14 @@ Material:
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _A:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _AlphaTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BaseMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
@ -45,6 +54,18 @@ Material:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ColorRampTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ColorRampTexGradient:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ColorSwapTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
@ -57,14 +78,30 @@ Material:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DistortTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
- _FadeBurnTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _FadeTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _GlowTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 10904, guid: 0000000000000000f000000000000000, type: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTexture:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
@ -73,14 +110,34 @@ Material:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _NormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OutlineDistortTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OutlineTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OverlayTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ShineMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SpecGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
@ -99,40 +156,216 @@ Material:
m_Offset: {x: 0, y: 0}
m_Ints: []
m_Floats:
- PixelSnap: 0
- _Alpha: 1
- _AlphaClip: 0
- _AlphaCutoffValue: 0.25
- _AlphaOutlineBlend: 1
- _AlphaOutlineGlow: 5
- _AlphaOutlineMinAlpha: 0
- _AlphaOutlinePower: 1
- _AlphaRoundThreshold: 0.5
- _AlphaToMask: 0
- _BillboardY: 0
- _Blend: 0
- _BlendModePreserveSpecular: 1
- _BlurHD: 0
- _BlurIntensity: 10
- _Brightness: 0
- _BumpScale: 1
- _ChromAberrAlpha: 0.4
- _ChromAberrAmount: 1
- _ClearCoatMask: 0
- _ClearCoatSmoothness: 0
- _ClipUvDown: 0
- _ClipUvLeft: 0
- _ClipUvRight: 0
- _ClipUvUp: 0
- _ColorChangeLuminosity: 0
- _ColorChangeTolerance: 0.25
- _ColorChangeTolerance2: 0.25
- _ColorChangeTolerance3: 0.25
- _ColorRampBlend: 1
- _ColorRampLuminosity: 0
- _ColorRampOutline: 0
- _ColorSwapBlend: 1
- _ColorSwapBlueLuminosity: 0.5
- _ColorSwapGreenLuminosity: 0.5
- _ColorSwapRedLuminosity: 0.5
- _Contrast: 1
- _Cull: 2
- _CullingOption: 0
- _Cutoff: 0.5
- _DetailAlbedoMapScale: 1
- _DetailNormalMapScale: 1
- _DistortAmount: 0.5
- _DistortTexXSpeed: 5
- _DistortTexYSpeed: 5
- _DstBlend: 0
- _DstBlendAlpha: 0
- _EditorDrawers: 6
- _EnableExternalAlpha: 0
- _EnvironmentReflections: 1
- _FadeAmount: -0.1
- _FadeBurnGlow: 2
- _FadeBurnTransition: 0.075
- _FadeBurnWidth: 0.025
- _FishEyeUvAmount: 0.35
- _FlickerAlpha: 0
- _FlickerFreq: 0.2
- _FlickerPercent: 0.05
- _GhostBlend: 1
- _GhostColorBoost: 1
- _GhostTransparency: 0
- _GlitchAmount: 3
- _GlitchSize: 1
- _GlossMapScale: 0
- _Glossiness: 0
- _GlossyReflections: 0
- _Glow: 10
- _GlowGlobal: 1
- _GradBlend: 1
- _GradBoostX: 1.2
- _GradBoostY: 1.2
- _GradIsRadial: 0
- _GrassManualAnim: 1
- _GrassManualToggle: 0
- _GrassRadialBend: 0.1
- _GrassSpeed: 2
- _GrassWind: 20
- _GreyscaleBlend: 1
- _GreyscaleLuminosity: 0
- _GreyscaleOutline: 0
- _HandDrawnAmount: 10
- _HandDrawnSpeed: 5
- _HitEffectBlend: 1
- _HitEffectGlow: 5
- _HologramBlend: 1
- _HologramMaxAlpha: 0.75
- _HologramMinAlpha: 0.1
- _HologramStripesAmount: 0.1
- _HologramStripesSpeed: 4.5
- _HologramUnmodAmount: 0
- _HsvBright: 1
- _HsvSaturation: 1
- _HsvShift: 180
- _InnerOutlineAlpha: 1
- _InnerOutlineGlow: 4
- _InnerOutlineThickness: 1
- _MaxXUV: 1
- _MaxYUV: 1
- _Metallic: 0
- _MinXUV: 0
- _MinYUV: 0
- _MotionBlurAngle: 0.1
- _MotionBlurDist: 1.25
- _MyDstMode: 10
- _MySrcMode: 5
- _NegativeAmount: 1
- _NormalStrength: 1
- _OcclusionStrength: 1
- _OffsetUvX: 0
- _OffsetUvY: 0
- _OnlyInnerOutline: 0
- _OnlyOutline: 0
- _OutlineAlpha: 1
- _OutlineDistortAmount: 0.5
- _OutlineDistortTexXSpeed: 5
- _OutlineDistortTexYSpeed: 5
- _OutlineGlow: 1
- _OutlinePixelWidth: 1
- _OutlineTexXSpeed: 10
- _OutlineTexYSpeed: 0
- _OutlineWidth: 0.004
- _OverlayBlend: 1
- _OverlayGlow: 1
- _OverlayTextureScrollXSpeed: 0.25
- _OverlayTextureScrollYSpeed: 0.25
- _Parallax: 0.005
- _PinchUvAmount: 0.35
- _PixelateSize: 32
- _PosterizeGamma: 0.75
- _PosterizeNumColors: 8
- _PosterizeOutline: 0
- _QueueControl: 0
- _QueueOffset: 0
- _RadialClip: 45
- _RadialClip2: 0
- _RadialStartAngle: 90
- _RandomSeed: 0
- _ReceiveShadows: 1
- _RectSize: 1
- _RotateUvAmount: 0
- _RoundWaveSpeed: 2
- _RoundWaveStrength: 0.7
- _ShadowAlpha: 0.5
- _ShadowX: 0.1
- _ShadowY: -0.05
- _ShakeUvSpeed: 1
- _ShakeUvX: 0
- _ShakeUvY: 5
- _ShineGlow: 1
- _ShineLocation: 0.5
- _ShineRotate: 0
- _ShineWidth: 0.1
- _Smoothness: 0.5
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _SrcBlendAlpha: 1
- _Surface: 0
- _TextureScrollXSpeed: 1
- _TextureScrollYSpeed: 0
- _TwistUvAmount: 1
- _TwistUvPosX: 0.5
- _TwistUvPosY: 0.5
- _TwistUvRadius: 0.75
- _WarpScale: 0.5
- _WarpSpeed: 8
- _WarpStrength: 0.025
- _WaveAmount: 7
- _WaveSpeed: 10
- _WaveStrength: 7.5
- _WaveX: 0
- _WaveY: 0.5
- _WindQuality: 0
- _WorkflowMode: 1
- _ZTestMode: 4
- _ZWrite: 1
- _ZoomUvAmount: 0.5
m_Colors:
- _AlphaOutlineColor: {r: 1, g: 1, b: 1, a: 1}
- _BaseColor: {r: 1, g: 1, b: 1, a: 1}
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _ColorChangeNewCol: {r: 1, g: 1, b: 0, a: 1}
- _ColorChangeNewCol2: {r: 1, g: 1, b: 0, a: 1}
- _ColorChangeNewCol3: {r: 1, g: 1, b: 0, a: 1}
- _ColorChangeTarget: {r: 1, g: 0, b: 0, a: 1}
- _ColorChangeTarget2: {r: 1, g: 0, b: 0, a: 1}
- _ColorChangeTarget3: {r: 1, g: 0, b: 0, a: 1}
- _ColorSwapBlue: {r: 1, g: 1, b: 1, a: 1}
- _ColorSwapGreen: {r: 1, g: 1, b: 1, a: 1}
- _ColorSwapRed: {r: 1, g: 1, b: 1, a: 1}
- _Distance_Fade: {r: 0, g: 4, b: 0, a: 0}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _FadeBurnColor: {r: 1, g: 1, b: 0, a: 1}
- _Flip: {r: 1, g: 1, b: 1, a: 1}
- _GlowColor: {r: 1, g: 1, b: 1, a: 1}
- _GradBotLeftCol: {r: 0, g: 0, b: 1, a: 1}
- _GradBotRightCol: {r: 0, g: 1, b: 0, a: 1}
- _GradTopLeftCol: {r: 1, g: 0, b: 0, a: 1}
- _GradTopRightCol: {r: 1, g: 1, b: 0, a: 1}
- _GreyscaleTintColor: {r: 1, g: 1, b: 1, a: 1}
- _Height_Fade: {r: 0, g: 1, b: 0, a: 0}
- _HitEffectColor: {r: 1, g: 1, b: 1, a: 1}
- _HologramStripeColor: {r: 0, g: 1, b: 1, a: 1}
- _HueVariation: {r: 1, g: 0.5, b: 0, a: 0.1}
- _InnerOutlineColor: {r: 1, g: 0, b: 0, a: 1}
- _OutlineColor: {r: 1, g: 1, b: 1, a: 1}
- _OverlayColor: {r: 1, g: 1, b: 1, a: 1}
- _RGBA: {r: 1, g: 1, b: 1, a: 0.8705882}
- _RendererColor: {r: 1, g: 1, b: 1, a: 1}
- _ShadowColor: {r: 0, g: 0, b: 0, a: 1}
- _ShineColor: {r: 1, g: 1, b: 1, a: 1}
- _SpecColor: {r: 0.19999996, g: 0.19999996, b: 0.19999996, a: 1}
m_BuildTextureStacks: []

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: ff3d183ed9fe89044b0695522de0cf66
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 11500000, guid: 625f186215c104763be7675aa2d941aa, type: 3}

View File

@ -20,12 +20,11 @@ namespace BITKit.Scene
if (draw is false || AllowGizmos is false) return;
var position = transform.position;
Gizmos.color = color;
Gizmos.DrawWireSphere(position, size);
if (bounds.Allow)
{
var rotation = transform.rotation;
Gizmos.DrawWireCube(position+rotation*bounds.Value/2, rotation*bounds.Value);
Gizmos.DrawCube(position, rotation*bounds.Value);
}
}
}

View File

@ -22,6 +22,7 @@ namespace BITKit.GameEditor
protected ListView listView { get; private set; }
protected VisualElement container { get; private set; }
protected VisualElement _actionContainer { get; private set; }
protected TextField _newNameField { get; private set; }
private Button _createButton;
protected virtual void OnEnable()
@ -94,11 +95,37 @@ namespace BITKit.GameEditor
{
var newNameContainer = scroll.Create<GroupBox>();
newNameContainer.style.flexDirection = FlexDirection.Row;
var newNameField = newNameContainer.Create<TextField>();
var newNameField =_newNameField = newNameContainer.Create<TextField>();
newNameField.style.flexGrow = 1;
var confirmButton = newNameContainer.Create<Button>();
confirmButton.text = "重命名";
confirmButton.clicked += () =>
{
var newName = newNameField.value;
if (string.IsNullOrEmpty(newName))
{
EditorUtility.DisplayDialog("警告", "文件名不能为空", "OK");
return;
}
var selected = listView.selectedItem as Object;
if(!selected)return;
var path = AssetDatabase.GetAssetPath(selected);
if (EditorUtility.DisplayDialog("询问", $"确定要重命名{Path.GetFileName(path)}为{newName}", "确定", "取消") is false)
{
return;
}
AssetDatabase.RenameAsset(path, newName);
RebuildList();
};
}
@ -148,9 +175,12 @@ namespace BITKit.GameEditor
{
var selected = obj.FirstOrDefault() as Object;
var serializedObject = new SerializedObject(selected);
BITInspectorExtensions.FillDefaultInspector(container,serializedObject, true);
BITInspectorExtensions.FillDefaultInspector(container, serializedObject, true);
container.Bind(serializedObject);
if (selected)
_newNameField.SetValueWithoutNotify(selected.name);
}
protected virtual VisualElement MakeItem()
{
var container = new VisualElement();
@ -187,6 +217,8 @@ namespace BITKit.GameEditor
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
RebuildList();
Debug.Log($"复制成功:{path}");
}
}

View File

@ -0,0 +1,23 @@
using System.Collections;
using System.Collections.Generic;
using BITKit.FPS;
using UnityEngine;
namespace Net.Project.B.FPS
{
public class ScriptableSprint3 : ScriptableObject,ISprint3
{
[SerializeField] private Spring3 spring3;
public Vector3 Value
{
get => spring3.Value;
set => spring3.Value = value;
}
public void Tick(float deltaTime, Vector3 target)
{
spring3.Tick(deltaTime, target);
}
}
}

View File

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9ba2d7b081cfd404b8ed6d3aa19e574f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -4,8 +4,13 @@ using System.Collections.Generic;
using UnityEngine;
namespace BITKit.FPS
{
public interface ISprint3
{
public Vector3 Value { get; set; }
void Tick(float deltaTime, Vector3 target);
}
[Serializable]
public class Spring3
public class Spring3:ISprint3
{
public Vector3 value = Vector2.zero;
[SerializeField] private Vector3 dampValue = Vector2.zero;
@ -21,7 +26,14 @@ namespace BITKit.FPS
this.damp = damp;
this.frequence = frequence;
}
public void Update(float deltaTime, Vector3 target)
public Vector3 Value
{
get=>value;
set=>this.value=value;
}
public void Tick(float deltaTime, Vector3 target)
{
value -= dampValue * deltaTime * frequence;
dampValue = Vector3.Lerp(dampValue, value - target, deltaTime * damp);

View File

@ -1,21 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using LeTai.Asset.TranslucentImage;
using UnityEngine;
namespace BITKit.UX
{
public class TranslucentService : MonoBehaviour
{
public static RenderTexture BlurredScreen;
[SerializeField] private TranslucentImageSource source;
[SerializeField] private RenderTexture blurredScreen;
private void LateUpdate()
{
source.Request();
BlurredScreen = blurredScreen = source.BlurredScreen;
}
}
}

View File

@ -1,34 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace BITKit.UX
{
public class TranslucentVisualElement : VisualElement
{
public new class UxmlFactory : UxmlFactory<TranslucentVisualElement, UxmlTraits> { }
public TranslucentVisualElement()
{
RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
generateVisualContent += DrawCanvas;
}
private void DrawCanvas(MeshGenerationContext obj)
{
}
private void OnGeometryChanged(GeometryChangedEvent evt)
{
#if UNITY_EDITOR
if (BITAppForUnity.IsPlaying is false) return;
#endif
if (style.display.value is not DisplayStyle.Flex) return;
style.backgroundImage = new StyleBackground(Background.FromRenderTexture(TranslucentService.BlurredScreen));
}
}
}

View File

@ -1,38 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace BITKit.UX
{
public class UXTranslucentService : MonoBehaviour
{
[SerializeField] private Image image;
private float alpha;
private void Start()
{
BITAppForUnity.AllowCursor.AddListener(OnCursor);
destroyCancellationToken.Register(Dispose);
}
private void Dispose()
{
BITAppForUnity.AllowCursor.RemoveListener(OnCursor);
}
private void OnCursor(bool obj)
{
image.enabled = obj;
if (obj) alpha = 0;
}
private void LateUpdate()
{
if (BITAppForUnity.AllowCursor.Allow && alpha is not 1)
{
alpha = Mathf.Clamp01(alpha + Time.deltaTime*5);
image.color = new Color(0, 0, 0, alpha);
}
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: c99210a06ff163b4ab4bfce7ebbccbe9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: