diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 0bdbe32..1864051 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -33,7 +33,7 @@ jobs: run: git lfs ls-files -l | cut -d' ' -f1 | sort > .lfs-assets-id - name: Restore LFS cache - uses: actions/cache@v4.0.2 + uses: actions/cache@v4 id: lfs-cache with: path: .git/lfs @@ -46,7 +46,7 @@ jobs: git reset --hard - name: Restore Library cache - uses: actions/cache@v4.0.2 + uses: actions/cache@v4 with: path: RedCatEngineUnityProject/Library key: Library-test-project-${{ matrix.targetPlatform }} @@ -65,12 +65,12 @@ jobs: checkName: ${{ matrix.package }} package test results githubToken: ${{ secrets.GITHUB_TOKEN }} - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: name: Test results (${{ matrix.package }}) path: ${{ steps.testRunner.outputs.artifactsPath }} - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: name: Coverage results (${{ matrix.package }}) path: ${{ steps.testRunner.outputs.coveragePath }} diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/ApplicationRunner.asmdef b/RedCatEngineUnityProject/Packages/ApplicationRunner/ApplicationRunner.asmdef new file mode 100644 index 0000000..678b8ff --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/ApplicationRunner.asmdef @@ -0,0 +1,18 @@ +{ + "name": "ApplicationRunner", + "rootNamespace": "RedCatEngine.ApplicationRunner", + "references": [ + "GUID:59778aa9a8cc64c93bbc14b46fb28511", + "GUID:687b69a268bf4402bb854a43d7732d8a", + "GUID:9c545a6a0a353cd479a317c06bb109b1" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/ApplicationRunner.asmdef.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/ApplicationRunner.asmdef.meta new file mode 100644 index 0000000..eed5177 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/ApplicationRunner.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: a480f689d8e60be478e2cf5590a64325 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure.meta new file mode 100644 index 0000000..c930c8a --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 21cdbeb899354ad48aa45da853d67753 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States.meta new file mode 100644 index 0000000..8e20a23 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a72f343bd6d74758962cc8363ff84da3 +timeCreated: 1726062870 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates.meta new file mode 100644 index 0000000..9514081 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 51bcc98986aa4d38b5ab2f5e6c93a8e8 +timeCreated: 1726064107 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates/BaseInitializeCheatState.cs b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates/BaseInitializeCheatState.cs new file mode 100644 index 0000000..5fa7173 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates/BaseInitializeCheatState.cs @@ -0,0 +1,33 @@ +using RedCatEngine.StateMachine.StateMachines; +using UnityEngine; + +namespace RedCatEngine.ApplicationRunner.Infrastructure.States.CheatSettingsStates +{ + public abstract class BaseInitializeCheatState : IInitializeCheatState + { + private readonly TypeBasedStateMachine _gameStateMachine; + private readonly IInitializeCheatPayload _cheatsPayload; + + protected BaseInitializeCheatState( + TypeBasedStateMachine gameStateMachine, + IInitializeCheatPayload cheatsPayload + ) + { + _gameStateMachine = gameStateMachine; + _cheatsPayload = cheatsPayload; + } + + public void Exit() { } + + public void Enter() + { + Debug.Log("Enter to SpawnCheatConsoleState"); + Object.Instantiate(_cheatsPayload.ConsolePrefab); + + _gameStateMachine + .EnterNextFromQueue(); + } + + protected abstract void AttachCheats(); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates/BaseInitializeCheatState.cs.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates/BaseInitializeCheatState.cs.meta new file mode 100644 index 0000000..a0081d2 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates/BaseInitializeCheatState.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 8f50a771c5eb40dab4087831ab8b4f2d +timeCreated: 1726064275 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates/IInitializeCheatPayload.cs b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates/IInitializeCheatPayload.cs new file mode 100644 index 0000000..7703ac2 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates/IInitializeCheatPayload.cs @@ -0,0 +1,9 @@ +using UnityEngine; + +namespace RedCatEngine.ApplicationRunner.Infrastructure.States.CheatSettingsStates +{ + public interface IInitializeCheatPayload + { + GameObject ConsolePrefab { get; } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates/IInitializeCheatPayload.cs.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates/IInitializeCheatPayload.cs.meta new file mode 100644 index 0000000..d62b327 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates/IInitializeCheatPayload.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7b230843631c4ba280609d03d8dcffd0 +timeCreated: 1726064430 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates/IInitializeCheatState.cs b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates/IInitializeCheatState.cs new file mode 100644 index 0000000..34778e7 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates/IInitializeCheatState.cs @@ -0,0 +1,9 @@ +using RedCatEngine.StateMachine.StateMachines; + +namespace RedCatEngine.ApplicationRunner.Infrastructure.States.CheatSettingsStates +{ + public interface IInitializeCheatState : IState + { + + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates/IInitializeCheatState.cs.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates/IInitializeCheatState.cs.meta new file mode 100644 index 0000000..3490790 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/CheatSettingsStates/IInitializeCheatState.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3b82b4e08e8249f8825c59c9f47414b0 +timeCreated: 1726064130 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates.meta new file mode 100644 index 0000000..00aa6ba --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 505e9c566092417b8ad7312c6b0505b1 +timeCreated: 1726062889 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/BaseInitializeLocalizationState.cs b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/BaseInitializeLocalizationState.cs new file mode 100644 index 0000000..2875de8 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/BaseInitializeLocalizationState.cs @@ -0,0 +1,50 @@ +using Localization; +using RedCatEngine.StateMachine.StateMachines; +using UnityEngine; + +namespace RedCatEngine.ApplicationRunner.Infrastructure.States.InitializeLocalizationStates +{ + public abstract class BaseInitializeLocalizationState : IInitializeLocalizationState + { + private readonly ITypedQueueStateMachine _gameStateMachine; + + protected BaseInitializeLocalizationState(ITypedQueueStateMachine gameStateMachine) + { + _gameStateMachine = gameStateMachine; + } + + public abstract string GetLanguage(); + + public void Enter() + { + var currentLanguage = GetLanguage(); + switch (currentLanguage) + { + case "ru": + LocalizeSystem.Init(SystemLanguage.Russian); + break; + case "en": + LocalizeSystem.Init(SystemLanguage.English); + break; + case "tr": + LocalizeSystem.Init(SystemLanguage.Turkish); + break; + case "fr": + LocalizeSystem.Init(SystemLanguage.French); + break; + case "de": + LocalizeSystem.Init(SystemLanguage.German); + break; + default: + LocalizeSystem.Init(SystemLanguage.English); + break; + } + _gameStateMachine.EnterNextFromQueue(); + } + + public void Exit() + { + + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/BaseInitializeLocalizationState.cs.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/BaseInitializeLocalizationState.cs.meta new file mode 100644 index 0000000..63b1e16 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/BaseInitializeLocalizationState.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: eed66ddd817d4d808ae9821846ca14a3 +timeCreated: 1726063659 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/EditorLocalizationState.cs b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/EditorLocalizationState.cs new file mode 100644 index 0000000..b7af4bb --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/EditorLocalizationState.cs @@ -0,0 +1,19 @@ +using RedCatEngine.DependencyInjection.Containers.Attributes; +using RedCatEngine.StateMachine.StateMachines; + +namespace RedCatEngine.ApplicationRunner.Infrastructure.States.InitializeLocalizationStates +{ + public class EditorLocalizationState : BaseInitializeLocalizationState + { + private readonly string _language; + + [Inject] + public EditorLocalizationState(ITypedQueueStateMachine gameStateMachine, string language = "ru") : base(gameStateMachine) + { + _language = language; + } + + public override string GetLanguage() + => _language; + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/EditorLocalizationState.cs.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/EditorLocalizationState.cs.meta new file mode 100644 index 0000000..a3882e1 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/EditorLocalizationState.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 720953b0f5f3420e9b13ca2ff77da091 +timeCreated: 1727943536 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/IInitializeLocalizationState.cs b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/IInitializeLocalizationState.cs new file mode 100644 index 0000000..8848386 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/IInitializeLocalizationState.cs @@ -0,0 +1,8 @@ +using RedCatEngine.StateMachine.StateMachines; + +namespace RedCatEngine.ApplicationRunner.Infrastructure.States.InitializeLocalizationStates +{ + public interface IInitializeLocalizationState : IState + { + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/IInitializeLocalizationState.cs.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/IInitializeLocalizationState.cs.meta new file mode 100644 index 0000000..425add8 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/IInitializeLocalizationState.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 6b44f4feb8874c75817c75b2f816093e +timeCreated: 1726062917 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/YandexInitializeLocalizationState.cs b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/YandexInitializeLocalizationState.cs new file mode 100644 index 0000000..bfd6dbf --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/YandexInitializeLocalizationState.cs @@ -0,0 +1,19 @@ +#if YANDEX_GAME +using RedCatEngine.DependencyInjection.Containers.Attributes; +using RedCatEngine.StateMachine.StateMachines; +using YG; + +namespace RedCatEngine.ApplicationRunner.Infrastructure.States.InitializeLocalizationStates +{ + public class YandexInitializeLocalizationState : BaseInitializeLocalizationState + { + [Inject] + public YandexInitializeLocalizationState(ITypedQueueStateMachine gameStateMachine) + : base(gameStateMachine) { } + + public override string GetLanguage() + => YandexGame.EnvironmentData.language; + } +} + +#endif \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/YandexInitializeLocalizationState.cs.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/YandexInitializeLocalizationState.cs.meta new file mode 100644 index 0000000..b6ed154 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/InitializeLocalizationStates/YandexInitializeLocalizationState.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: feff1168d7f24a8ebd9d3643f4fdf91e +timeCreated: 1726063826 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/LoadModelStates.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/LoadModelStates.meta new file mode 100644 index 0000000..bde2c47 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/LoadModelStates.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f498a68715ea40f7a4c37f1756e6767f +timeCreated: 1726129949 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/LoadModelStates/ILoadPlayerModelState.cs b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/LoadModelStates/ILoadPlayerModelState.cs new file mode 100644 index 0000000..eddf275 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/LoadModelStates/ILoadPlayerModelState.cs @@ -0,0 +1,9 @@ +using RedCatEngine.StateMachine.StateMachines; + +namespace RedCatEngine.ApplicationRunner.Infrastructure.States.LoadModelStates +{ + public interface ILoadPlayerModelState : IState + { + + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/LoadModelStates/ILoadPlayerModelState.cs.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/LoadModelStates/ILoadPlayerModelState.cs.meta new file mode 100644 index 0000000..b96236c --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/LoadModelStates/ILoadPlayerModelState.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: e6892cfc3322488e8fd43d7cabb9d32a +timeCreated: 1726129980 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/LoadModelStates/LoadPlayerModelState.cs b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/LoadModelStates/LoadPlayerModelState.cs new file mode 100644 index 0000000..b9edd8b --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/LoadModelStates/LoadPlayerModelState.cs @@ -0,0 +1,55 @@ +using RedCatEngine.ApplicationRunner.Meta.PlayerModels; +using RedCatEngine.ApplicationRunner.Meta.PlayerModels.ModelLoaders; +using RedCatEngine.ApplicationRunner.Meta.PlayerModels.SaveTriggers; +using RedCatEngine.DependencyInjection.Containers.Attributes; +using RedCatEngine.DependencyInjection.Containers.Interfaces.Unity; +using RedCatEngine.StateMachine.StateMachines; + +namespace RedCatEngine.ApplicationRunner.Infrastructure.States.LoadModelStates +{ + public class LoadPlayerModelState : ILoadPlayerModelState + where TModelData : class, new() + where TModelLoader : IModelLoader + { + private readonly IUnityGameContainer _applicationContainer; + private readonly ITypedQueueStateMachine _stateMachine; + private IPlayerModelContainer _playerModelContainer; + + [Inject] + public LoadPlayerModelState( + IUnityGameContainer applicationContainer, + ITypedQueueStateMachine stateMachine + ) + { + _applicationContainer = applicationContainer; + _stateMachine = stateMachine; + } + + public void Enter() + { + _applicationContainer.BindType, TModelLoader>(); + _applicationContainer.BindType(); + _playerModelContainer = _applicationContainer + .BindType, PlayerModelContainer>(); + _playerModelContainer.Load(); + if (!_playerModelContainer.IsReady) + _playerModelContainer.ReadyEvent += OnReady; + else + OnSaveLoad(); + } + + private void OnReady() + { + _playerModelContainer.ReadyEvent -= OnReady; + OnSaveLoad(); + } + + private void OnSaveLoad() + { + _applicationContainer.BindAsSingle(_playerModelContainer.Model); + _stateMachine.EnterNextFromQueue(); + } + + public void Exit() { } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/LoadModelStates/LoadPlayerModelState.cs.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/LoadModelStates/LoadPlayerModelState.cs.meta new file mode 100644 index 0000000..381eb14 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/States/LoadModelStates/LoadPlayerModelState.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 818fec00bfe741d09b1feede3fea7190 +timeCreated: 1726130962 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/TypeBasedStateMachine.cs b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/TypeBasedStateMachine.cs new file mode 100644 index 0000000..4d1fd3b --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/TypeBasedStateMachine.cs @@ -0,0 +1,45 @@ +using System; +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application.GenerationBind; +using RedCatEngine.StateMachine.StateMachines; +using UnityEngine; + +namespace RedCatEngine.ApplicationRunner.Infrastructure +{ + public abstract class TypeBasedStateMachine : BaseTypedStateMachine + where TBaseState : class, IExitableState + { + private readonly ICreator _creator; + + protected TypeBasedStateMachine(ICreator creator, string name) : base(name) + { + _creator = creator; + } + + protected void AddState() + where TTagState : TBaseState + where TInstanceState : TTagState + => AddState(_creator.Create()); + + protected void AddState(params object[] context) + where TTagState : TBaseState + where TInstanceState : TTagState + => AddState(_creator.Create(context)); + + protected void AddState() + where TInstanceState : TBaseState + => AddState(); + + protected override TBaseState GetState(Type type) + { + if (_states.TryGetValue(type, out var targetState)) + return targetState; + + var newState = _creator.Create(type); + targetState = newState as TBaseState; + AddState(type, targetState); + if(targetState == null) + Debug.LogError("State is null"); + return targetState; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/TypeBasedStateMachine.cs.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/TypeBasedStateMachine.cs.meta new file mode 100644 index 0000000..79766c7 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Infrastructure/TypeBasedStateMachine.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d739ad615ba14e53b648d36df1913e5f +timeCreated: 1726062128 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta.meta new file mode 100644 index 0000000..30af5a0 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: e94e32fd93bb4546b8b949b0b6215367 +timeCreated: 1726131075 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels.meta new file mode 100644 index 0000000..ed85ffd --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: bcbc1802e87a4aa4a9cc98e81a8678b8 +timeCreated: 1726131083 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/IPlayerModelContainer.cs b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/IPlayerModelContainer.cs new file mode 100644 index 0000000..95ff40b --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/IPlayerModelContainer.cs @@ -0,0 +1,16 @@ +using System; + +namespace RedCatEngine.ApplicationRunner.Meta.PlayerModels +{ + public interface IPlayerModelContainer + { + event Action ReadyEvent; + bool IsReady { get; } + TModelData Model { get; } + void Load(); + void Save(); +#if CHEAT_ENABLE + void ResetModel(); +#endif + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/IPlayerModelContainer.cs.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/IPlayerModelContainer.cs.meta new file mode 100644 index 0000000..3b0d0ba --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/IPlayerModelContainer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: eb006c7b19cd4502a83b4fc5db01e225 +timeCreated: 1726131092 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders.meta new file mode 100644 index 0000000..840673f --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 018916f8a36244a1982488d2f30c3791 +timeCreated: 1726132622 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders/EditorModelLoader.cs b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders/EditorModelLoader.cs new file mode 100644 index 0000000..648893a --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders/EditorModelLoader.cs @@ -0,0 +1,33 @@ +using System; +using RedCatEngine.DependencyInjection.Containers.Attributes; +using UnityEngine; + +namespace RedCatEngine.ApplicationRunner.Meta.PlayerModels.ModelLoaders +{ + public class EditorModelLoader : IModelLoader + where TModelData : class, new() + { + private const string SaveKey = "GameSave"; + + [Inject] + public EditorModelLoader() + { + + } + + public void Save(TModelData modelForSave) + { + var save = JsonUtility.ToJson(modelForSave); + Debug.Log($"Save model: {save}"); + PlayerPrefs.SetString(SaveKey, save); + } + + public void Load(Action callbackLoad) + { + var save = PlayerPrefs.GetString(SaveKey); + if (!string.IsNullOrEmpty(save)) + callbackLoad?.Invoke(JsonUtility.FromJson(save)); + callbackLoad?.Invoke(new TModelData()); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders/EditorModelLoader.cs.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders/EditorModelLoader.cs.meta new file mode 100644 index 0000000..25039d1 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders/EditorModelLoader.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: e4783c4cb0354bf7af619cd0b2c0b413 +timeCreated: 1726132642 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders/IModelLoader.cs b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders/IModelLoader.cs new file mode 100644 index 0000000..c00ccbe --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders/IModelLoader.cs @@ -0,0 +1,11 @@ +using System; + +namespace RedCatEngine.ApplicationRunner.Meta.PlayerModels.ModelLoaders +{ + public interface IModelLoader + where TModelData : class, new() + { + void Save(TModelData modelForSave); + void Load(Action callbackLoad); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders/IModelLoader.cs.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders/IModelLoader.cs.meta new file mode 100644 index 0000000..8dcceeb --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders/IModelLoader.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3bd10ebc9651482fba6a351bb53a8b20 +timeCreated: 1726131529 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders/YandexModelLoader.cs b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders/YandexModelLoader.cs new file mode 100644 index 0000000..3dd020b --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders/YandexModelLoader.cs @@ -0,0 +1,52 @@ +#if YANDEX_GAME +using System; +using RedCatEngine.DependencyInjection.Containers.Attributes; +using UnityEngine; +using YG; + +namespace RedCatEngine.ApplicationRunner.Meta.PlayerModels.ModelLoaders +{ + public class YandexModelLoader : IModelLoader, IDisposable + where TModelData : class, new() + { + private Action _onLoadCallBack; + + [Inject] + public YandexModelLoader() + { + + } + + public void Save(TModelData modelForSave) + { + YandexGame.savesData.SavedModel = JsonUtility.ToJson(modelForSave); + YandexGame.SaveProgress(); + } + + public void Load(Action callbackLoad) + { + _onLoadCallBack = callbackLoad; + if (!YandexGame.SDKEnabled) + { + YandexGame.GetDataEvent += OnGetData; + return; + } + + OnGetData(); + } + + private void OnGetData() + { + var save = YandexGame.savesData.SavedModel; + if (!string.IsNullOrEmpty(save)) + _onLoadCallBack?.Invoke(JsonUtility.FromJson(save)); + _onLoadCallBack?.Invoke(new TModelData()); + } + + public void Dispose() + { + YandexGame.GetDataEvent -= OnGetData; + } + } +} +#endif \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders/YandexModelLoader.cs.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders/YandexModelLoader.cs.meta new file mode 100644 index 0000000..106bc38 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/ModelLoaders/YandexModelLoader.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 355cb705d0b24a68b54b08411c78e5a4 +timeCreated: 1726132691 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/PlayerModelContainer.cs b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/PlayerModelContainer.cs new file mode 100644 index 0000000..604904e --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/PlayerModelContainer.cs @@ -0,0 +1,56 @@ +using System; +using JetBrains.Annotations; +using RedCatEngine.ApplicationRunner.Meta.PlayerModels.ModelLoaders; +using RedCatEngine.ApplicationRunner.Meta.PlayerModels.SaveTriggers; +using RedCatEngine.DependencyInjection.Containers.Attributes; + +namespace RedCatEngine.ApplicationRunner.Meta.PlayerModels +{ + public class PlayerModelContainer : IPlayerModelContainer, IDisposable + where TModelData : class, new() + { + public event Action ReadyEvent; + + public bool IsReady + => Model != null; + + private readonly IModelLoader _loader; + private readonly IPlayerModelSaveTrigger _playerModelSaveTrigger; + public TModelData Model { get; private set; } + + [Inject] + [UsedImplicitly] + public PlayerModelContainer(IModelLoader loader, IPlayerModelSaveTrigger playerModelSaveTrigger) + { + _loader = loader; + _playerModelSaveTrigger = playerModelSaveTrigger; + _playerModelSaveTrigger.SaveEvent += Save; + } + + public void Load() + { + _loader.Load(OnSaveLoaded); + } + + public void Save() + { + _loader.Save(Model); + } + + private void OnSaveLoaded(TModelData modelData) + { + Model = modelData; + ReadyEvent?.Invoke(); + } + +#if CHEAT_ENABLE + public void ResetModel() + => _loader.Save(new TModelData()); +#endif + + public void Dispose() + { + _playerModelSaveTrigger.SaveEvent -= Save; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/PlayerModelContainer.cs.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/PlayerModelContainer.cs.meta new file mode 100644 index 0000000..6e8ba85 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/PlayerModelContainer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 556d7d39d1514fedaf294f315f3fbb37 +timeCreated: 1726131370 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/SaveTriggers.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/SaveTriggers.meta new file mode 100644 index 0000000..aa0000a --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/SaveTriggers.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 1d1d944d4c9c450fad4fee087d596f6f +timeCreated: 1726134535 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/SaveTriggers/IPlayerModelSaveTrigger.cs b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/SaveTriggers/IPlayerModelSaveTrigger.cs new file mode 100644 index 0000000..73f58fc --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/SaveTriggers/IPlayerModelSaveTrigger.cs @@ -0,0 +1,10 @@ +using System; + +namespace RedCatEngine.ApplicationRunner.Meta.PlayerModels.SaveTriggers +{ + public interface IPlayerModelSaveTrigger + { + event Action SaveEvent; + void Save(); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/SaveTriggers/IPlayerModelSaveTrigger.cs.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/SaveTriggers/IPlayerModelSaveTrigger.cs.meta new file mode 100644 index 0000000..fbcaf74 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/SaveTriggers/IPlayerModelSaveTrigger.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f2aca029e5c34985b887030b165d6b39 +timeCreated: 1726134547 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/SaveTriggers/PlayerModelSaveTrigger.cs b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/SaveTriggers/PlayerModelSaveTrigger.cs new file mode 100644 index 0000000..d039113 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/SaveTriggers/PlayerModelSaveTrigger.cs @@ -0,0 +1,14 @@ +using System; +using JetBrains.Annotations; + +namespace RedCatEngine.ApplicationRunner.Meta.PlayerModels.SaveTriggers +{ + [UsedImplicitly] + public class PlayerModelSaveTrigger : IPlayerModelSaveTrigger + { + public event Action SaveEvent; + + public void Save() + => SaveEvent?.Invoke(); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/SaveTriggers/PlayerModelSaveTrigger.cs.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/SaveTriggers/PlayerModelSaveTrigger.cs.meta new file mode 100644 index 0000000..847098a --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/Meta/PlayerModels/SaveTriggers/PlayerModelSaveTrigger.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f903afda45f0444fb9cace9684fb55e3 +timeCreated: 1726134573 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/package.json b/RedCatEngineUnityProject/Packages/ApplicationRunner/package.json new file mode 100644 index 0000000..061e46b --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/package.json @@ -0,0 +1,11 @@ +{ + "name": "com.boronnikov.games.red-cat-engine.aplication.runner", + "version": "1.0.0", + "displayName": "Red Cat Engine: Aplication runner", + "description": "Base system for run aplication", + "unity": "2021.3", + "author": { + "name": "Boronnikov Games", + "url": "https://github.com/Red-Cat-Fat" + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/ApplicationRunner/package.json.meta b/RedCatEngineUnityProject/Packages/ApplicationRunner/package.json.meta new file mode 100644 index 0000000..ede80bf --- /dev/null +++ b/RedCatEngineUnityProject/Packages/ApplicationRunner/package.json.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9fd2b307601da794599ff87f02c24147 +timeCreated: 1713125223 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Benchmark/Benchmark.asmdef b/RedCatEngineUnityProject/Packages/Benchmark/Benchmark.asmdef new file mode 100644 index 0000000..949c9b3 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Benchmark/Benchmark.asmdef @@ -0,0 +1,14 @@ +{ + "name": "Benchmark", + "rootNamespace": "RedCatEngine.Benchmark", + "references": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Benchmark/Benchmark.asmdef.meta b/RedCatEngineUnityProject/Packages/Benchmark/Benchmark.asmdef.meta new file mode 100644 index 0000000..cd90735 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Benchmark/Benchmark.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: ba552b006766733498bf26cd2e16c732 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/RedCatEngineUnityProject/Packages/Benchmark/BenchmarkRunner.cs b/RedCatEngineUnityProject/Packages/Benchmark/BenchmarkRunner.cs new file mode 100644 index 0000000..e7f487f --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Benchmark/BenchmarkRunner.cs @@ -0,0 +1,188 @@ +using System; +using System.IO; +using System.Text; +using UnityEngine; + +#if DEVELOPMENT_BUILD +using UnityEngine.Profiling; +#endif + +namespace RedCatEngine.Benchmark +{ + public class BenchmarkRunner : MonoBehaviour + { + [SerializeField] + [Tooltip("Интервал обновления FPS (в секундах)")] + private float _fpsUpdateInterval = 0.5f; + [SerializeField] + [Tooltip( + "Формат имени файла с результатами. " + + "{0} - название продукта, " + + "{1} - имя сценария," + + "{2} - время запуска бенчмарка")] + private string _benchmarkNameFormat = "benchmark_results_{0}_{1}_{2}.txt"; + [SerializeField] + private string _subFolderName = "{0}"; + [SerializeField] + private float _timeWriteInterval = 10f; + [SerializeField] + private Camera _benchmarkCamera; + private float _fpsAccumulator; + private int _fpsFramesCount; + private float _fpsTimeLeft; + private float _currentFPS; + private string _benchmarkFilePath; + + private bool _isRunning; + private float _totalFpsAccumulator; + private int _totalFpsFramesCount; + private float _minFps = float.MaxValue; + private float _maxFps = float.MinValue; + private float _minDeltaTime = float.MaxValue; + private float _maxDeltaTime = float.MinValue; + + private float _startTime; + public bool IsRunning + => _isRunning; + + private string GetBenchmarkFolderPath() + { + var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); + var subFolderName = string.Format(_subFolderName, Application.productName); + var benchmarkFolderPath = Path.Combine(desktopPath, subFolderName); + if (!Directory.Exists(benchmarkFolderPath)) + Directory.CreateDirectory(benchmarkFolderPath); + + return benchmarkFolderPath; + } + + public void StartBenchmark(string scenarioName) + { + _benchmarkCamera.gameObject.SetActive(true); + ResetValues(); + + var benchmarkFileName = string.Format( + _benchmarkNameFormat, + Application.productName, + scenarioName, + DateTime.Now.ToString("yyyy-MM-dd-HH-mm")); + + _benchmarkFilePath = Path.Combine( + GetBenchmarkFolderPath(), + benchmarkFileName); + WriteSystemInfo(); + _fpsTimeLeft = _fpsUpdateInterval; + _isRunning = true; + _startTime = Time.time; + } + + private void ResetValues() + { + _minFps = float.MaxValue; + _maxFps = float.MinValue; + _minDeltaTime = float.MaxValue; + _maxDeltaTime = float.MinValue; + _totalFpsAccumulator = 0; + _totalFpsFramesCount = 0; + _fpsTimeLeft = 0; + _fpsAccumulator = 0f; + _fpsFramesCount = 0; + _currentFPS = 0; + } + + private void Update() + { + if (!_isRunning) + return; + + MeasureFPS(); + _minDeltaTime = Mathf.Min(_minDeltaTime, Time.deltaTime); + _maxDeltaTime = Mathf.Max(_maxDeltaTime, Time.deltaTime); + if (Time.time % _timeWriteInterval < Time.deltaTime) + RecordFPS(); + } + + private void WriteSystemInfo() + { + var sb = new StringBuilder(); + sb.AppendLine("=== SYSTEM INFORMATION ==="); + sb.AppendLine($"Operating System: {SystemInfo.operatingSystem}"); + sb.AppendLine($"Processor: {SystemInfo.processorType}"); + sb.AppendLine($"Processor Cores: {SystemInfo.processorCount}"); + sb.AppendLine($"Graphics Device: {SystemInfo.graphicsDeviceName}"); + sb.AppendLine($"Graphics Memory (MB): {SystemInfo.graphicsMemorySize}"); + sb.AppendLine($"System Memory (MB): {SystemInfo.systemMemorySize}"); + sb.AppendLine($"Unity Version: {Application.unityVersion}"); + sb.AppendLine($"Screen Resolution: {Screen.currentResolution}"); + sb.AppendLine("\n=== BENCHMARK RESULTS ==="); + sb.AppendLine("Time (s)\tFPS"); + + File.WriteAllText(_benchmarkFilePath, sb.ToString()); + } + + private void MeasureFPS() + { + _fpsTimeLeft -= Time.deltaTime; + _fpsAccumulator += Time.timeScale / Time.deltaTime; + _fpsFramesCount++; + + if (_fpsTimeLeft > 0f) + return; + + _currentFPS = _fpsAccumulator / _fpsFramesCount; + _totalFpsAccumulator += _fpsAccumulator; + _totalFpsFramesCount += _fpsFramesCount; + _minFps = Mathf.Min(_minFps, _currentFPS); + _maxFps = Mathf.Max(_maxFps, _currentFPS); + _fpsTimeLeft = _fpsUpdateInterval; + _fpsAccumulator = 0f; + _fpsFramesCount = 0; + } + + private void RecordFPS() + { + var logEntry = $"{(Time.time-_startTime):F1}\t\t{_currentFPS:F1}\n"; + File.AppendAllText(_benchmarkFilePath, logEntry); + } + + public void StopBenchmark(string reasonName) + { + _isRunning = false; + var sb = new StringBuilder(); + sb.AppendLine("=== BENCHMARK COMPLETED ==="); + sb.AppendLine($"Reason stop: {reasonName}"); + sb.AppendLine($"Min FPS: {_minFps:F1}"); + sb.AppendLine($"Max FPS: {_maxFps:F1}"); + sb.AppendLine($"Arranged FPS: {_totalFpsAccumulator / _totalFpsFramesCount:F1}"); + sb.AppendLine($"Min deltaTime: {_minDeltaTime:F1}"); + sb.AppendLine($"Max deltaTime: {_maxDeltaTime:F1}"); + +#if UNITY_EDITOR + Debug.Log("Запущено в редакторе Unity"); + sb.AppendLine( + $"Total Memory Usage (MB): {SystemInfo.systemMemorySize - (SystemInfo.systemMemorySize - (GC.GetTotalMemory(false) / (1024 * 1024)))}"); + sb.AppendLine( + $"Allocated Memory (MB): {UnityEngine.Profiling.Profiler.GetTotalAllocatedMemoryLong() / (1024 * 1024)}"); + sb.AppendLine( + $"Reserved Memory (MB): {UnityEngine.Profiling.Profiler.GetTotalReservedMemoryLong() / (1024 * 1024)}"); + sb.AppendLine( + $"Mono Heap Size (MB): {UnityEngine.Profiling.Profiler.GetMonoHeapSizeLong() / (1024 * 1024)}"); +#elif DEVELOPMENT_BUILD + Debug.Log("Development Build (но не редактор)"); + sb.AppendLine( + $"Total Memory Usage (MB): {SystemInfo.systemMemorySize - (SystemInfo.systemMemorySize - (GC.GetTotalMemory(false) / (1024 * 1024)))}"); + sb.AppendLine( + $"Allocated Memory (MB): {UnityEngine.Profiling.Profiler.GetTotalAllocatedMemoryLong() / (1024 * 1024)}"); + sb.AppendLine( + $"Reserved Memory (MB): {UnityEngine.Profiling.Profiler.GetTotalReservedMemoryLong() / (1024 * 1024)}"); + sb.AppendLine( + $"Mono Heap Size (MB): {UnityEngine.Profiling.Profiler.GetMonoHeapSizeLong() / (1024 * 1024)}"); +#else + Debug.Log("Релизная сборка"); +#endif + Debug.Log("Готово"); + sb.AppendLine("Benchmark completed."); + File.AppendAllText(_benchmarkFilePath, sb.ToString()); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Benchmark/BenchmarkRunner.cs.meta b/RedCatEngineUnityProject/Packages/Benchmark/BenchmarkRunner.cs.meta new file mode 100644 index 0000000..52bd5a2 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Benchmark/BenchmarkRunner.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 52fc7163c04834b42970a7f785f6e201 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Benchmark/CHANGELOG.md b/RedCatEngineUnityProject/Packages/Benchmark/CHANGELOG.md new file mode 100644 index 0000000..a9c61d7 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Benchmark/CHANGELOG.md @@ -0,0 +1,10 @@ +# Changelog + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [1.0.0] - 2025-04-01 + +### Added + +- BenchmarkRunner. \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Benchmark/CHANGELOG.md.meta b/RedCatEngineUnityProject/Packages/Benchmark/CHANGELOG.md.meta new file mode 100644 index 0000000..e95c17c --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Benchmark/CHANGELOG.md.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b721e68668e3d2a45a5da3bef16b214f +timeCreated: 1720700869 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Benchmark/package.json b/RedCatEngineUnityProject/Packages/Benchmark/package.json new file mode 100644 index 0000000..77d1244 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Benchmark/package.json @@ -0,0 +1,11 @@ +{ + "name": "com.boronnikov.games.red-cat-engine.banchmark", + "version": "1.0.0", + "displayName": "Red Cat Engine: Banchmark", + "description": "An extension designed to measure gameplay performance in a specific scenario.", + "unity": "2021.3", + "author": { + "name": "Boronnikov Games", + "url": "https://github.com/Red-Cat-Fat" + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Benchmark/package.json.meta b/RedCatEngineUnityProject/Packages/Benchmark/package.json.meta new file mode 100644 index 0000000..5193d0b --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Benchmark/package.json.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 153faeeb4ab7f4e448ade77476bc7967 +PackageManifestImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/RedCatEngineUnityProject/Packages/Conditions/Base/BaseSingleServiceCondition.cs b/RedCatEngineUnityProject/Packages/Conditions/Base/BaseSingleServiceCondition.cs new file mode 100644 index 0000000..b2b3c24 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Conditions/Base/BaseSingleServiceCondition.cs @@ -0,0 +1,26 @@ +using System; +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; +using UnityEngine; + +namespace RedCatEngine.Conditions.Base +{ + [Serializable] + public abstract class BaseSingleServiceCondition : ICondition + { + [SerializeField] + private bool _invert; + + public bool Check(IGetterApplicationContainer getter) + { + if (!getter.TryGetSingle(out var service)) + throw new Exception("Not found condition checker"); + + var result = DoCheck(service); + if (_invert) + return !result; + return result; + } + + protected abstract bool DoCheck(TServiceCheck service); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Conditions/Base/BaseSingleServiceCondition.cs.meta b/RedCatEngineUnityProject/Packages/Conditions/Base/BaseSingleServiceCondition.cs.meta new file mode 100644 index 0000000..27a8197 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Conditions/Base/BaseSingleServiceCondition.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 5533a75c765748689695885a67eb6920 +timeCreated: 1718201649 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Conditions/Base/ConditionConfig.cs b/RedCatEngineUnityProject/Packages/Conditions/Base/ConditionConfig.cs index eff4776..2e4cbb8 100644 --- a/RedCatEngineUnityProject/Packages/Conditions/Base/ConditionConfig.cs +++ b/RedCatEngineUnityProject/Packages/Conditions/Base/ConditionConfig.cs @@ -12,7 +12,7 @@ public abstract class ConditionConfig : BaseConfig [SerializeReference] private ICondition _condition; - public bool Check(IApplicationContainer applicationContainer) - => _condition.Check(applicationContainer); + public bool Check(IGetterApplicationContainer getter) + => _condition.Check(getter); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Conditions/Base/ICondition.cs b/RedCatEngineUnityProject/Packages/Conditions/Base/ICondition.cs index cb70a89..75bade3 100644 --- a/RedCatEngineUnityProject/Packages/Conditions/Base/ICondition.cs +++ b/RedCatEngineUnityProject/Packages/Conditions/Base/ICondition.cs @@ -4,6 +4,6 @@ namespace RedCatEngine.Conditions.Base { public interface ICondition { - bool Check(IApplicationContainer applicationContainer); + bool Check(IGetterApplicationContainer getter); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Conditions/ConditionCheckerService.cs b/RedCatEngineUnityProject/Packages/Conditions/ConditionCheckerService.cs index 9bb543d..cabd2de 100644 --- a/RedCatEngineUnityProject/Packages/Conditions/ConditionCheckerService.cs +++ b/RedCatEngineUnityProject/Packages/Conditions/ConditionCheckerService.cs @@ -1,13 +1,17 @@ -using RedCatEngine.Conditions.Base; +using JetBrains.Annotations; +using RedCatEngine.Conditions.Base; +using RedCatEngine.DependencyInjection.Containers.Attributes; using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; using UnityEngine; namespace RedCatEngine.Conditions { + [UsedImplicitly] public class ConditionCheckerService : IConditionCheckerService { private readonly IApplicationContainer _applicationContainer; + [Inject] public ConditionCheckerService(IApplicationContainer applicationContainer) { _applicationContainer = applicationContainer; diff --git a/RedCatEngineUnityProject/Packages/Conditions/Contents/ConditionValue.cs b/RedCatEngineUnityProject/Packages/Conditions/Contents/ConditionValue.cs index cf0877c..812aee2 100644 --- a/RedCatEngineUnityProject/Packages/Conditions/Contents/ConditionValue.cs +++ b/RedCatEngineUnityProject/Packages/Conditions/Contents/ConditionValue.cs @@ -1,21 +1,21 @@ using System; using RedCatEngine.Conditions.Base; using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; -using RedCatEngine.Values.Base; +using RedCatEngine.Values.Base.Interfaces; using SerializeReferenceEditor; using UnityEngine; namespace RedCatEngine.Conditions.Contents { [Serializable] - [SRName("Condition")] + [SRName("Common/Condition value")] public class ConditionValue : IBoolValue { [SR] [SerializeReference] private ICondition _condition; - public bool GetValue(IApplicationContainer applicationContainer) - => _condition.Check(applicationContainer); + public bool GetValue(IGetterApplicationContainer getterContainer) + => _condition.Check(getterContainer); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Conditions/Tests/ConditionsTests.asmdef b/RedCatEngineUnityProject/Packages/Conditions/Tests/ConditionsTests.asmdef index 7bb16ed..5bfd8a9 100644 --- a/RedCatEngineUnityProject/Packages/Conditions/Tests/ConditionsTests.asmdef +++ b/RedCatEngineUnityProject/Packages/Conditions/Tests/ConditionsTests.asmdef @@ -5,7 +5,9 @@ "UnityEngine.TestRunner", "UnityEditor.TestRunner", "Conditions", - "DependencyInjection" + "DependencyInjection", + "Configs", + "Values" ], "includePlatforms": [ "Editor" diff --git a/RedCatEngineUnityProject/Packages/Conditions/Variants/ReValueCondition.cs b/RedCatEngineUnityProject/Packages/Conditions/Variants/CheckValueCondition.cs similarity index 58% rename from RedCatEngineUnityProject/Packages/Conditions/Variants/ReValueCondition.cs rename to RedCatEngineUnityProject/Packages/Conditions/Variants/CheckValueCondition.cs index 7bd9b1f..4f2e35b 100644 --- a/RedCatEngineUnityProject/Packages/Conditions/Variants/ReValueCondition.cs +++ b/RedCatEngineUnityProject/Packages/Conditions/Variants/CheckValueCondition.cs @@ -1,21 +1,21 @@ using System; using RedCatEngine.Conditions.Base; using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; -using RedCatEngine.Values.Base; +using RedCatEngine.Values.Base.Interfaces; using SerializeReferenceEditor; using UnityEngine; namespace RedCatEngine.Conditions.Variants { [Serializable] - [SRName("Value Condition")] - public class ReValueCondition : ICondition + [SRName("Logic Value Condition")] + public class CheckValueCondition : ICondition { [SR] [SerializeReference] private IBoolValue _resultValue; - public bool Check(IApplicationContainer applicationContainer) - => _resultValue.GetValue(applicationContainer); + public bool Check(IGetterApplicationContainer getter) + => _resultValue.GetValue(getter); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Conditions/Variants/ReValueCondition.cs.meta b/RedCatEngineUnityProject/Packages/Conditions/Variants/CheckValueCondition.cs.meta similarity index 100% rename from RedCatEngineUnityProject/Packages/Conditions/Variants/ReValueCondition.cs.meta rename to RedCatEngineUnityProject/Packages/Conditions/Variants/CheckValueCondition.cs.meta diff --git a/RedCatEngineUnityProject/Packages/Conditions/Variants/ConditionConfigLink.cs b/RedCatEngineUnityProject/Packages/Conditions/Variants/ConditionConfigLink.cs index 6a3ad54..ba4f354 100644 --- a/RedCatEngineUnityProject/Packages/Conditions/Variants/ConditionConfigLink.cs +++ b/RedCatEngineUnityProject/Packages/Conditions/Variants/ConditionConfigLink.cs @@ -13,9 +13,9 @@ public class ConditionConfigLink : ICondition [SerializeField] private ConditionConfig _conditionConfig; - public bool Check(IApplicationContainer applicationContainer) + public bool Check(IGetterApplicationContainer getter) { - return _conditionConfig.Check(applicationContainer); + return _conditionConfig.Check(getter); } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Conditions/Variants/ForceCondition.cs b/RedCatEngineUnityProject/Packages/Conditions/Variants/ForceCondition.cs index 81ba9b2..d93ccea 100644 --- a/RedCatEngineUnityProject/Packages/Conditions/Variants/ForceCondition.cs +++ b/RedCatEngineUnityProject/Packages/Conditions/Variants/ForceCondition.cs @@ -18,7 +18,14 @@ public static ICondition False [SerializeField] private bool _forceValue; - public bool Check(IApplicationContainer applicationContainer) + public ForceCondition() { } + + public ForceCondition(bool value) + { + _forceValue = value; + } + + public bool Check(IGetterApplicationContainer getter) => _forceValue; } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Conditions/Variants/Logic/AndCondition.cs b/RedCatEngineUnityProject/Packages/Conditions/Variants/Logic/AndCondition.cs index dcf9e9d..e3aefa7 100644 --- a/RedCatEngineUnityProject/Packages/Conditions/Variants/Logic/AndCondition.cs +++ b/RedCatEngineUnityProject/Packages/Conditions/Variants/Logic/AndCondition.cs @@ -15,9 +15,9 @@ public class AndCondition : ICondition [SerializeReference] public ICondition[] Conditions; - public bool Check(IApplicationContainer applicationContainer) + public bool Check(IGetterApplicationContainer getter) { - return Conditions.All(condition => condition.Check(applicationContainer)); + return Conditions.All(condition => condition.Check(getter)); } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Conditions/Variants/Logic/NotCondition.cs b/RedCatEngineUnityProject/Packages/Conditions/Variants/Logic/NotCondition.cs index 0034331..13e04a0 100644 --- a/RedCatEngineUnityProject/Packages/Conditions/Variants/Logic/NotCondition.cs +++ b/RedCatEngineUnityProject/Packages/Conditions/Variants/Logic/NotCondition.cs @@ -14,9 +14,9 @@ public class NotCondition : ICondition [SerializeReference] public ICondition Condition; - public bool Check(IApplicationContainer applicationContainer) + public bool Check(IGetterApplicationContainer getter) { - return !Condition.Check(applicationContainer); + return !Condition.Check(getter); } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Conditions/Variants/Logic/OrCondition.cs b/RedCatEngineUnityProject/Packages/Conditions/Variants/Logic/OrCondition.cs index 8996e33..68ccb33 100644 --- a/RedCatEngineUnityProject/Packages/Conditions/Variants/Logic/OrCondition.cs +++ b/RedCatEngineUnityProject/Packages/Conditions/Variants/Logic/OrCondition.cs @@ -15,9 +15,9 @@ public class OrCondition : ICondition [SerializeReference] public ICondition[] Conditions; - public bool Check(IApplicationContainer applicationContainer) + public bool Check(IGetterApplicationContainer getter) { - return Conditions.Any(condition => condition.Check(applicationContainer)); + return Conditions.Any(condition => condition.Check(getter)); } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Configs/BaseConfig.cs b/RedCatEngineUnityProject/Packages/Configs/BaseConfig.cs index 22c6f50..47b8121 100644 --- a/RedCatEngineUnityProject/Packages/Configs/BaseConfig.cs +++ b/RedCatEngineUnityProject/Packages/Configs/BaseConfig.cs @@ -12,7 +12,7 @@ public abstract class BaseConfig : ScriptableObject public int ID => _id; - private void OnValidate() + public void OnValidate() { #if UNITY_EDITOR if (!EditorUtility.IsPersistent(this)) diff --git a/RedCatEngineUnityProject/Packages/Configs/BaseSingleConfig.cs b/RedCatEngineUnityProject/Packages/Configs/BaseSingleConfig.cs new file mode 100644 index 0000000..42930cc --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Configs/BaseSingleConfig.cs @@ -0,0 +1,40 @@ +using UnityEngine; + +namespace RedCatEngine.Configs +{ + public class BaseSingleConfig : BaseConfig where TConfig : BaseConfig + { + private static TConfig _instance; + + public static TConfig Instance + { + get + { + if (_instance != null) + return _instance; + _instance = Resources.Load(nameof(TConfig)); + +#if UNITY_EDITOR + if (_instance != null) + return _instance; + + _instance = CreateInstance(); + UnityEditor.AssetDatabase.CreateAsset( + _instance, + $"Assets/Resources/Configs/{nameof(TConfig)}.asset"); + UnityEditor.AssetDatabase.SaveAssets(); +#endif + return _instance; + } + } + + protected override void DoValidate() + { + var otherConfigs = Resources.FindObjectsOfTypeAll(); + if (otherConfigs.Length > 1) + { + Debug.LogError("There are more than one instance of " + nameof(TConfig)); + } + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Configs/BaseSingleConfig.cs.meta b/RedCatEngineUnityProject/Packages/Configs/BaseSingleConfig.cs.meta new file mode 100644 index 0000000..29c5a65 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Configs/BaseSingleConfig.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 24cf3c25d15544658d36031000ada2a6 +timeCreated: 1757323267 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Configs/ConfigID.cs b/RedCatEngineUnityProject/Packages/Configs/ConfigID.cs index 2874294..10b4f74 100644 --- a/RedCatEngineUnityProject/Packages/Configs/ConfigID.cs +++ b/RedCatEngineUnityProject/Packages/Configs/ConfigID.cs @@ -9,21 +9,31 @@ public sealed class ConfigID IComparable> where TBaseConfig : BaseConfig { - private const int InvalidId = 0; - public static ConfigID Invalid - => new(InvalidId); + public const int InvalidId = 0; [SerializeField] private int _id; - public string ID - => _id.ToString(); - private ConfigID(int id) => _id = id; public ConfigID(TBaseConfig config) => _id = config.ID; + public static ConfigID Invalid + => new(InvalidId); + + public string ID + => _id.ToString(); + + public int CompareTo(ConfigID other) + { + if (ReferenceEquals(this, other)) + return 0; + if (ReferenceEquals(null, other)) + return 1; + return _id.CompareTo(other._id); + } + public bool Equals(ConfigID other) => _id == (other != null ? other._id : InvalidId); @@ -57,15 +67,6 @@ public static explicit operator int(ConfigID configId) public static implicit operator ConfigID(TBaseConfig config) => config != null ? new ConfigID(config.ID) : Invalid; - public int CompareTo(ConfigID other) - { - if (ReferenceEquals(this, other)) - return 0; - if (ReferenceEquals(null, other)) - return 1; - return _id.CompareTo(other._id); - } - #if UNITY_EDITOR public static ConfigID MakeForTest(int id) => new(id); diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/ApplicationContainer.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/ApplicationContainer.cs index 5f846ec..7fc7a00 100644 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/ApplicationContainer.cs +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/ApplicationContainer.cs @@ -5,23 +5,45 @@ using RedCatEngine.DependencyInjection.Containers.Attributes; using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; using RedCatEngine.DependencyInjection.Exceptions; +using RedCatEngine.DependencyInjection.Specials; using RedCatEngine.DependencyInjection.Specials.Providers; -using RedCatEngine.DependencyInjection.Utils; namespace RedCatEngine.DependencyInjection.Containers { public class ApplicationContainer : IApplicationContainer { - private readonly Dictionary _objects = new(); + private readonly IApplicationContainer _parent; private readonly CashContainer _cashContainer; - protected readonly ProviderService _providerService; + private readonly Dictionary _objects = new(); + private readonly ProviderService _providerService; + private readonly List _chilContainers = new(); + + private bool _isDisposed; public ApplicationContainer() { _cashContainer = new CashContainer(); _providerService = new ProviderService(); + Injector = new Injector(this, _providerService); + } + + protected ApplicationContainer(IApplicationContainer parent) + { + _parent = parent; + _cashContainer = new CashContainer(); + _providerService = new ProviderService(); + Injector = new Injector(this, _providerService); + } + + public virtual IApplicationContainer CreateChildContainer() + { + var childContainer = new ApplicationContainer(this); + _chilContainers.Add(childContainer); + return childContainer; } + public Injector Injector { get; } + public ISingleProvider RegisterProvider() where TProvideType : class => _providerService.RegisterProvider(); @@ -36,20 +58,41 @@ public object RegisterArrayProvider(Type providerType) public bool TryGetSingle(out T data) { - var type = typeof(T); + if (TryGetSingle(typeof(T), out var obj) + && obj is T typedObj) + { + data = typedObj; + return true; + } + + data = default; + return false; + } + + + public bool TryGetSingle(Type type, out object data) + { if (_objects.TryGetValue(type, out var instance)) { - data = (T)instance; + data = instance; return true; } - if (_cashContainer.TryFindFirstChildByType(_objects, out var parent)) + if (_cashContainer.TryFindFirstChildByType( + type, + _objects, + out var parent) && + parent != null && + type.IsAssignableFrom(parent.GetType())) { data = parent; return true; } - data = default; + if (_parent != null) + return _parent.TryGetSingle(type, out data); + + data = null; return false; } @@ -59,10 +102,15 @@ public bool TryGetArray(out IEnumerable data) return _cashContainer.TryGetAndCachedArrayByOtherKeys(out data) || _cashContainer.TryGetAndCachedArrayByParenFromSingle(_objects, out data); - data = instances.Select(instance => (T)instance); - return true; + data = instances.OfType().ToList(); + + if (!data.Any() && _parent != null) + return _parent.TryGetArray(out data); + + return data.Any(); } + public IEnumerable GetArray() { if (_cashContainer.ArrayObjects.TryGetValue(typeof(T), out var instanceEnumerable)) @@ -74,6 +122,9 @@ public IEnumerable GetArray() if (_cashContainer.TryGetAndCachedArrayByParenFromSingle(_objects, out var singleVariants)) return singleVariants; + if (_parent != null) + return _parent.GetArray(); + throw new NotFoundInstanceOrCreateException(typeof(T)); } @@ -96,7 +147,7 @@ public object Create(Type type, params object[] context) null) continue; - return InjectContextToConstructor( + return Injector.InjectContextToConstructor( type, constructor, context); @@ -105,43 +156,17 @@ public object Create(Type type, params object[] context) if (emptyParameterConstructor != default) return Activator.CreateInstance(type); - throw new NotFountInjectAttributeForConstructorException(type); + throw new NotFountInjectAttributeForConstructorException(type); } - private object InjectContextToConstructor( - Type type, - MethodBase constructor, - object[] context - ) + public T GetSingle(params object[] context) { - var parameters = new List(); - - foreach (var parameterInfo in constructor.GetParameters()) - { - if (typeof(ISingleProvider<>).IsAssignableFromGeneric( - parameterInfo.ParameterType, - out var expectedSingleWaiterGenericType)) - { - parameters.Add(_providerService.RegisterProvider(expectedSingleWaiterGenericType[0])); - continue; - } - - if (typeof(IArrayProvider<>).IsAssignableFromGeneric( - parameterInfo.ParameterType, - out var expectedArrayWaiterGenericType)) - { - parameters.Add(_providerService.RegisterArrayProvider(expectedArrayWaiterGenericType[0])); - continue; - } + if (GetSingle(typeof(T), context) is T result) + return result; - parameters.Add(GetSingle(parameterInfo.ParameterType, context)); - } - - return Activator.CreateInstance(type, parameters.ToArray()); + throw new InvalidCastException($"Object of type {typeof(T)} could not be cast."); } - public T GetSingle(params object[] context) - => (T)GetSingle(typeof(T), context); public object GetSingle( Type type, @@ -171,32 +196,18 @@ params object[] context out var typedInstance)) return typedInstance; + if (_parent != null && _parent.TryGetSingle(type, out var parentInstance)) + return parentInstance; + if (TryCreate( type, - out instance, - context)) - return instance; + out var createdInstance, + context) && type.IsInstanceOfType(createdInstance)) + return createdInstance; throw new NotFoundInstanceOrCreateException(type); } - private bool TryCreate( - Type type, - out object instance, - params object[] context - ) - { - if (type.IsAbstract || type.IsInterface) - { - instance = default; - return false; - } - - instance = Create(type, context); - BindAsSingle(type, instance); - return true; - } - public TInstanceBindType BindDummy(params object[] context) where TDummyType : TInstanceBindType { @@ -228,13 +239,13 @@ public object BindArrayType(Type type, params object[] context) public TBindType BindAsSingle(TBindType instance) => BindAsSingle(typeof(TBindType), instance); - protected TBindType BindAsSingle(Type typeKey, TBindType instance) + public TBindType ReBindAsSingle(TBindType newInstance) { - if (_objects.TryGetValue(typeKey, out var alreadyInstance)) - throw new BindDuplicateWithoutArrayMarkException(typeof(TBindType), alreadyInstance); - - _objects.Add(typeKey, instance); - return _providerService.BindAsSingle(instance); + var typeKey = typeof(TBindType); + if (!_objects.TryGetValue(typeKey, out _)) + return BindAsSingle(newInstance); + _objects[typeKey] = newInstance; + return _providerService.ReBindAsSingle(newInstance); } public TBindType BindAsArray(TBindType instance) @@ -247,6 +258,32 @@ public TBindType BindAsArray(TBindType instance) return _providerService.BindAsArray(instance); } + private bool TryCreate( + Type type, + out object instance, + params object[] context + ) + { + if (type.IsAbstract || type.IsInterface) + { + instance = default; + return false; + } + + instance = Create(type, context); + BindAsSingle(type, instance); + return true; + } + + protected TBindType BindAsSingle(Type typeKey, TBindType instance) + { + if (_objects.TryGetValue(typeKey, out var alreadyInstance)) + throw new BindDuplicateWithoutArrayMarkException(typeof(TBindType), alreadyInstance); + + _objects.Add(typeKey, instance); + return _providerService.BindAsSingle(instance); + } + protected TBindType BindAsArray(Type typeKey, TBindType instance) { if (!_cashContainer.ArrayObjects.ContainsKey(typeKey)) @@ -255,5 +292,30 @@ protected TBindType BindAsArray(Type typeKey, TBindType instance) _cashContainer.ArrayObjects[typeKey].Add(instance); return _providerService.BindAsArray(instance); } + + public void Dispose() + { + if (_isDisposed) + return; + + for (var index = 0; index < _chilContainers.Count; index++) + _chilContainers[index].Dispose(); + + var disposablesSingleObjects = _objects.Values + .OfType() + .ToList(); + foreach (var disposable in disposablesSingleObjects) + { + disposable.Dispose(); + } + + if (!_cashContainer.TryGetAndCachedArrayByOtherKeys( + out var disposablesArrays)) + return; + foreach (var disposable in disposablesArrays) + disposable.Dispose(); + + _isDisposed = true; + } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Attributes/InjectAttribute.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Attributes/InjectAttribute.cs index 56ea0ed..20aa710 100644 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Attributes/InjectAttribute.cs +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Attributes/InjectAttribute.cs @@ -1,8 +1,10 @@ using System; +using JetBrains.Annotations; namespace RedCatEngine.DependencyInjection.Containers.Attributes { [AttributeUsage(AttributeTargets.Constructor)] + [MeansImplicitUse] public class InjectAttribute : Attribute { diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Attributes/MonoInjectAttribute.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Attributes/MonoInjectAttribute.cs index 05dd51e..754e494 100644 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Attributes/MonoInjectAttribute.cs +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Attributes/MonoInjectAttribute.cs @@ -1,8 +1,10 @@ using System; +using JetBrains.Annotations; namespace RedCatEngine.DependencyInjection.Containers.Attributes { [AttributeUsage(AttributeTargets.Method)] + [MeansImplicitUse] public class MonoInjectAttribute : Attribute { diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/Binders/ISingleBinderApplicationContainer.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/Binders/ISingleBinderApplicationContainer.cs index 855d244..f7e435f 100644 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/Binders/ISingleBinderApplicationContainer.cs +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/Binders/ISingleBinderApplicationContainer.cs @@ -8,5 +8,6 @@ public interface ISingleBinderApplicationContainer ISingleProvider RegisterProvider() where TProvideType : class; object RegisterProvider(Type providerType); TBindType BindAsSingle(TBindType instance); + TBindType ReBindAsSingle(TBindType newInstance); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/GenerationBind/ICreator.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/GenerationBind/ICreator.cs index 334a1a0..ff1d86d 100644 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/GenerationBind/ICreator.cs +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/GenerationBind/ICreator.cs @@ -1,11 +1,32 @@ using System; +using RedCatEngine.DependencyInjection.Specials; namespace RedCatEngine.DependencyInjection.Containers.Interfaces.Application.GenerationBind { + /// + /// Интерфейс механизма создания экземпляров классов + /// public interface ICreator { + /// + /// Экземпляр инжектора, который используется для создания объектов + /// + Injector Injector { get; } + + /// + /// Создаёт экземпляр класса, без биндинга к контейнеру + /// + /// Тип объекта, который необходимо создать + /// Контекст, необходимый для инициализации объекта указанного класса + /// object Create(Type type, params object[] context); + /// + /// Создаёт экземпляр класса, без биндинга к контейнеру + /// + /// Контекст, необходимый для инициализации объекта указанного класса + /// Тип объекта, который необходимо создать + /// T Create(params object[] context); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/GenerationBind/ITypeBinderApplicationContainer.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/GenerationBind/ITypeBinderApplicationContainer.cs index 4f4a199..96e4857 100644 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/GenerationBind/ITypeBinderApplicationContainer.cs +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/GenerationBind/ITypeBinderApplicationContainer.cs @@ -2,19 +2,131 @@ namespace RedCatEngine.DependencyInjection.Containers.Interfaces.Application.GenerationBind { + /// + /// Интерфейс контейнера, который предоставляет методы для регистрации и создания экземпляров. + /// public interface ITypeBinderApplicationContainer { + /// + /// Привязывает "Dummy" тип к контейнеру, если нормальный тип не найден в текущем контексте. + /// Используется для обеспечения возможности работы системы при отсутствии нужного реального объекта. + /// + /// + /// Тип, к которому будет привязан созданный экземпляр. Это тот тип, который ожидается потребителем. + /// + /// + /// Тип реализации dummy, который должен наследовать или реализовывать . + /// + /// + /// Параметры, необходимые для инициализации экземпляра . + /// Передаются в конструктор dummy-класса, если требуется инъекция данных. + /// + /// + /// Возвращает созданный и зарегистрированный экземпляр типа . + /// TInstanceBindType BindDummy(params object[] context) where TDummyType : TInstanceBindType; + /// + /// Регистрирует и возвращает уникальный экземпляр , привязанный к типу . + /// + /// + /// Массив объектов, передаваемый в конструктор для его инициализации. + /// Может использоваться для внедрения зависимостей или параметров при создании экземпляра. + /// + /// + /// Тип, к которому будет произведена привязка. Это тип, который будет запрашиваться из контейнера. + /// + /// + /// Тип реализации, который создаётся и связывается с . + /// Должен быть наследником или реализацией . + /// + /// + /// Созданный и зарегистрированный экземпляр типа , + /// доступный по интерфейсу . + /// TBindType BindType(params object[] context) where TInstanceType : TBindType; + + /// + /// Регистрирует и возвращает экземпляр + /// как один из элементов массива экземпляров + /// + /// + /// Массив объектов, передаваемый в конструктор для его инициализации. + /// Может использоваться для внедрения зависимостей или параметров при создании экземпляра. + /// + /// + /// Тип, к массиву экземпляров которому будет произведена привязка. Это тип массива, который будет запрашиваться из контейнера. + /// + /// + /// Тип реализации, который создаётся и связывается с . + /// Должен быть наследником или реализацией . + /// + /// + /// Созданный и зарегистрированный экземпляр типа . + /// TBindArrayType BindArrayType(params object[] context) where TInstanceType : TBindArrayType; + /// + /// Регистрирует и возвращает новый уникальный экземпляр типа . + /// + /// + /// Массив объектов, передаваемый в конструктор для его инициализации. + /// Может использоваться для внедрения зависимостей или параметров при создании экземпляра. + /// + /// + /// Тип, экземпляр которого создаётся и регистрируется в контейнере. + /// + /// + /// Созданный экземпляр типа . + /// TInstanceBindType BindType(params object[] context); + + /// + /// Регистрирует и возвращает новый уникальный экземпляр указанного типа. + /// + /// + /// Тип, экземпляр которого нужно создать и зарегистрировать. + /// + /// + /// Массив объектов, передаваемый в конструктор указанного типа для его инициализации. + /// Может использоваться для внедрения зависимостей или параметров при создании экземпляра. + /// + /// + /// Созданный экземпляр указанного типа в виде объекта . + /// object BindType(Type type, params object[] context); + + /// + /// Регистрирует как элемент массива экземпляров и привязывает его к типу . + /// + /// + /// Массив объектов, передаваемый в конструктор экземпляров для их инициализации. + /// Может использоваться для внедрения зависимостей или параметров при создании экземпляра. + /// + /// + /// Тип массива, к которому будет привязан созданный экземпляр. + /// + /// + /// Созданный и зарегистрированный экземпляр типа . + /// TInstanceBindType BindArrayType(params object[] context); + + /// + /// Регистрирует как элемент массива экземпляров и привязывает его к типу, указанному в качестве переменной . + /// + /// + /// Тип, экземпляр которого будет создан и зарегистрирован в качестве элемента массива. + /// + /// + /// Массив объектов, передаваемый в конструктор экземпляров для их инициализации. + /// Может использоваться для внедрения зависимостей или параметров при создании экземпляра. + /// + /// + /// Созданный и зарегистрированный экземпляр в виде объекта . + /// object BindArrayType(Type type, params object[] context); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/IApplicationContainer.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/IApplicationContainer.cs index 37af9ad..4018538 100644 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/IApplicationContainer.cs +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/IApplicationContainer.cs @@ -1,3 +1,4 @@ +using System; using RedCatEngine.DependencyInjection.Containers.Interfaces.Application.Binders; using RedCatEngine.DependencyInjection.Containers.Interfaces.Application.GenerationBind; @@ -7,7 +8,9 @@ public interface IApplicationContainer : IBinderApplicationContainer, ITypeBinderApplicationContainer, IGetterApplicationContainer, - ICreator + ICreator, + IDisposable { + IApplicationContainer CreateChildContainer(); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/IGetterApplicationContainer.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/IGetterApplicationContainer.cs index cad9665..c851af9 100644 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/IGetterApplicationContainer.cs +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Application/IGetterApplicationContainer.cs @@ -6,6 +6,7 @@ namespace RedCatEngine.DependencyInjection.Containers.Interfaces.Application public interface IGetterApplicationContainer { bool TryGetSingle(out T data); + bool TryGetSingle(Type type, out object data); bool TryGetArray(out IEnumerable data); T GetSingle(params object[] context); object GetSingle(Type type, params object[] context); diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/IGetterApplicationContainer.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/IGetterApplicationContainer.cs deleted file mode 100644 index 94b1d81..0000000 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/IGetterApplicationContainer.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Collections.Generic; - -namespace RedCatEngine.DependencyInjection.Containers.Interfaces -{ - public interface IGetterApplicationContainer - { - bool TryGetSingle(out T data); - bool TryGetArray(out IEnumerable data); - T GetSingle(params object[] context); - IEnumerable GetArray(); - } -} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/IGetterApplicationContainer.cs.meta b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/IGetterApplicationContainer.cs.meta deleted file mode 100644 index 111fd22..0000000 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/IGetterApplicationContainer.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: f891f8de43834d349b52dd6e2136b4c7 -timeCreated: 1719517743 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IMonoBindInstance.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IMonoBindInstance.cs index b2b02a1..f0a0c33 100644 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IMonoBindInstance.cs +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IMonoBindInstance.cs @@ -38,7 +38,7 @@ TMonoConstruct BindAsSingleInstance( Quaternion rotation, Transform parent, params object[] context - ) where TMonoConstruct : MonoConstruct; + ) where TMonoConstruct : IMonoConstruct; TMonoConstruct BindAsArrayInstance( GameObject prefab, @@ -46,6 +46,6 @@ TMonoConstruct BindAsArrayInstance( Quaternion rotation, Transform parent, params object[] context - ) where TMonoConstruct : MonoConstruct; + ) where TMonoConstruct : IMonoConstruct; } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IMonoConstructCreator.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IMonoConstructCreator.cs new file mode 100644 index 0000000..30d38ca --- /dev/null +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IMonoConstructCreator.cs @@ -0,0 +1,16 @@ +using RedCatEngine.DependencyInjection.Specials.Components; +using UnityEngine; + +namespace RedCatEngine.DependencyInjection.Containers.Interfaces.Unity +{ + public interface IMonoConstructCreator + { + void MonoConstruct(TMonoBehaviour gameView, params object[] context) + where TMonoBehaviour : IMonoConstruct; + + GameObject MonoConstruct( + GameObject gameObject, + params object[] context + ); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IMonoConstructor.cs.meta b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IMonoConstructCreator.cs.meta similarity index 100% rename from RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IMonoConstructor.cs.meta rename to RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IMonoConstructCreator.cs.meta diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IMonoConstructor.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IMonoConstructor.cs deleted file mode 100644 index d6bc137..0000000 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IMonoConstructor.cs +++ /dev/null @@ -1,10 +0,0 @@ -using UnityEngine; - -namespace RedCatEngine.DependencyInjection.Containers.Interfaces.Unity -{ - public interface IMonoConstructor - { - MonoBehaviour MonoConstruct(MonoBehaviour gameView, params object[] context); - GameObject MonoConstruct(GameObject gameObject, bool constructChildren = false, params object[] context); - } -} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IMonoCreator.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IMonoCreator.cs index 6e6ce99..6195331 100644 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IMonoCreator.cs +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IMonoCreator.cs @@ -8,7 +8,6 @@ public interface IMonoCreator GameObject Create( GameObject prefab, Transform parent, - bool constructChildren = false, params object[] context ); @@ -17,14 +16,12 @@ GameObject Create( Vector3 position, Quaternion rotation, Transform parent, - bool constructChildren = false, params object[] context ); TBindType CreateAndGetComponent( GameObject prefab, Transform parent, - bool constructChildren = false, params object[] context ) where TBindType : Component; @@ -33,7 +30,6 @@ TBindType CreateAndGetComponent( Vector3 position, Quaternion rotation, Transform parent, - bool constructChildren = false, params object[] context ) where TBindType : Component; @@ -41,7 +37,6 @@ object CreateAndGetComponent( Type componentType, GameObject prefab, Transform parent, - bool constructChildren = false, params object[] context ); object CreateAndGetComponent( @@ -50,7 +45,6 @@ object CreateAndGetComponent( Vector3 position, Quaternion rotation, Transform parent, - bool constructChildren = false, params object[] context ); } diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IUnityGameContainer.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IUnityGameContainer.cs index fa1aa44..e157018 100644 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IUnityGameContainer.cs +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/Interfaces/Unity/IUnityGameContainer.cs @@ -1,7 +1,18 @@ using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; +using UnityEngine; namespace RedCatEngine.DependencyInjection.Containers.Interfaces.Unity { public interface - IUnityGameContainer : IApplicationContainer, IMonoConstructor, IMonoBindInstance, IMonoCreator { } + IUnityGameContainer : IApplicationContainer, IMonoConstructCreator, IMonoBindInstance, IMonoCreator + { + new IUnityGameContainer CreateChildContainer(); + TMonoBehaviorType CreateAndBindComponentAsSingle( + GameObject prefab, + Vector3 position, + Quaternion rotation, + Transform parent, + params object[] context + ) where TMonoBehaviorType : Component; + } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/UnityGameContainer.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/UnityGameContainer.cs index 89fa08c..530c2b7 100644 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/UnityGameContainer.cs +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Containers/UnityGameContainer.cs @@ -1,13 +1,10 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Reflection; using RedCatEngine.DependencyInjection.Containers.Attributes; +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; using RedCatEngine.DependencyInjection.Containers.Interfaces.Unity; using RedCatEngine.DependencyInjection.Exceptions; using RedCatEngine.DependencyInjection.Specials.Components; -using RedCatEngine.DependencyInjection.Specials.Providers; -using RedCatEngine.DependencyInjection.Utils; using UnityEngine; using Object = UnityEngine.Object; @@ -15,37 +12,32 @@ namespace RedCatEngine.DependencyInjection.Containers { public class UnityGameContainer : ApplicationContainer, IUnityGameContainer { - public MonoBehaviour MonoConstruct(MonoBehaviour monoBehaviour, params object[] context) + public UnityGameContainer() { - var type = monoBehaviour.GetType(); - var methods = type.GetMethods(); - foreach (var method in methods) - { - if (Attribute.GetCustomAttribute( - method, - typeof(MonoInjectAttribute), - true) == - null) - continue; - - return InjectContextToMonoConstructor( - monoBehaviour, - method, - context); - } - - throw new NotFountInjectAttributeForConstructorException(type); + + } + + private UnityGameContainer(UnityGameContainer unityGameContainer) : base(unityGameContainer) + { + } + + public new IUnityGameContainer CreateChildContainer() + => new UnityGameContainer(this); + + public void MonoConstruct(TMonoBehaviour monoBehaviour, params object[] context) + where TMonoBehaviour : IMonoConstruct + { + Injector.InjectContextToMethodsWithAttribute(monoBehaviour, context); + monoBehaviour.FinishInitialize(); } public GameObject MonoConstruct( GameObject gameObject, - bool constructChildren = false, params object[] context ) { ConstructComponents( gameObject, - constructChildren, context); return gameObject; @@ -53,62 +45,26 @@ params object[] context private void ConstructComponents( GameObject gameObject, - bool constructChildren, object[] context ) { - var components = constructChildren - ? gameObject.GetComponentsInChildren(typeof(MonoConstruct)) - .Union(gameObject.GetComponents(typeof(MonoConstruct))) - : gameObject.GetComponents(typeof(MonoConstruct)); + var components = gameObject.GetComponentsInChildren(typeof(IMonoConstruct)); - foreach (var component in components) - MonoConstruct((MonoConstruct)component, context); + foreach (var component in components.Cast()) + MonoConstruct(component, context); } - private MonoBehaviour InjectContextToMonoConstructor( - MonoBehaviour monoBehaviour, - MethodBase method, - object[] context - ) - { - var parameters = new List(); - - foreach (var parameterInfo in method.GetParameters()) - { - if (typeof(ISingleProvider<>).IsAssignableFromGeneric( - parameterInfo.ParameterType, - out var expectedSingleWaiterGenericType)) - { - parameters.Add(_providerService.RegisterProvider(expectedSingleWaiterGenericType[0])); - continue; - } - - if (typeof(IArrayProvider<>).IsAssignableFromGeneric( - parameterInfo.ParameterType, - out var expectedArrayWaiterGenericType)) - { - parameters.Add(_providerService.RegisterArrayProvider(expectedArrayWaiterGenericType[0])); - continue; - } - - parameters.Add(GetSingle(parameterInfo.ParameterType, context)); - } - - method.Invoke(monoBehaviour, parameters.ToArray()); - return monoBehaviour; - } - private MonoConstruct GetComponent(Type type, GameObject gameObject) + private IMonoConstruct GetComponent(Type type, GameObject gameObject) { - if (gameObject.TryGetComponent(type, out var component) && component is MonoConstruct monoConstruct) + if (gameObject.TryGetComponent(type, out var component) && component is IMonoConstruct monoConstruct) return monoConstruct; throw new GameObjectNotContainComponentException(type, gameObject); } private TMonoBehaviour GetComponent(GameObject gameObject) - where TMonoBehaviour : MonoConstruct + where TMonoBehaviour : IMonoConstruct { return (TMonoBehaviour)GetComponent(typeof(TMonoBehaviour), gameObject); } @@ -130,7 +86,6 @@ var go ConstructComponents( go, - true, context); return BindAsArray(go); @@ -153,7 +108,6 @@ params object[] context ConstructComponents( go, - true, context); var component = GetComponent(bindType, go); return BindAsSingle(bindType, component); @@ -176,7 +130,6 @@ params object[] context ConstructComponents( go, - true, context); var component = GetComponent(bindType, go); @@ -189,7 +142,7 @@ public TBindType BindAsSingleInstance( Quaternion rotation, Transform parent, params object[] context - ) where TBindType : MonoConstruct + ) where TBindType : IMonoConstruct { var go = Object.Instantiate( prefab, @@ -199,7 +152,6 @@ params object[] context ConstructComponents( go, - false, context); var component = GetComponent(go); MonoConstruct(component, context); @@ -213,7 +165,7 @@ public TBindType BindAsArrayInstance( Quaternion rotation, Transform parent, params object[] context - ) where TBindType : MonoConstruct + ) where TBindType : IMonoConstruct { var go = Object.Instantiate( prefab, @@ -223,7 +175,6 @@ params object[] context ConstructComponents( go, - false, context); var component = GetComponent(go); @@ -235,7 +186,6 @@ public GameObject Create( Vector3 position, Quaternion rotation, Transform parent, - bool constructChildren = false, params object[] context ) { @@ -247,7 +197,6 @@ var go parent); ConstructComponents( go, - constructChildren, context); return go; } @@ -255,27 +204,23 @@ var go public GameObject Create( GameObject prefab, Transform parent, - bool constructChildren = false, params object[] context ) { var go = Object.Instantiate( prefab, - parent);; + parent); ConstructComponents( go, - constructChildren, context); return go; } - public TMonoBehaviorType CreateAndGetComponent( GameObject prefab, Transform parent, - bool constructChildren = false, params object[] context ) where TMonoBehaviorType : Component { @@ -283,7 +228,6 @@ params object[] context typeof(TMonoBehaviorType), prefab, parent, - constructChildren, context) as TMonoBehaviorType; } @@ -292,7 +236,6 @@ public TMonoBehaviorType CreateAndGetComponent( Vector3 position, Quaternion rotation, Transform parent, - bool constructChildren = false, params object[] context ) where TMonoBehaviorType : Component { @@ -302,18 +245,43 @@ params object[] context position, rotation, parent, - constructChildren, context) as TMonoBehaviorType; //todo: error for not contain component } + public TMonoBehaviorType CreateAndBindComponentAsSingle( + GameObject prefab, + Vector3 position, + Quaternion rotation, + Transform parent, + params object[] context + ) where TMonoBehaviorType : Component + { + var go + = Object.Instantiate( + prefab, + position, + rotation, + parent); + + var component = go.GetComponent(); + if (component is MonoConstruct monoConstruct) + MonoConstruct(monoConstruct, context); + + BindAsSingle(component); + ConstructComponents( + go, + context); + + return component; + } + public object CreateAndGetComponent( Type componentType, GameObject prefab, Vector3 position, Quaternion rotation, Transform parent, - bool constructChildren = false, params object[] context ) { @@ -322,7 +290,6 @@ params object[] context position, rotation, parent, - constructChildren, context); return go.GetComponent(componentType); @@ -332,14 +299,12 @@ public object CreateAndGetComponent( Type componentType, GameObject prefab, Transform parent, - bool constructChildren = false, params object[] context ) { var go = Create( prefab, parent, - constructChildren, context); return go.GetComponent(componentType); diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Exceptions/NotFountInjectAttributeForConstructorException.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Exceptions/NotFountInjectAttributeForConstructorException.cs index 65bfeb1..6c00575 100644 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Exceptions/NotFountInjectAttributeForConstructorException.cs +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Exceptions/NotFountInjectAttributeForConstructorException.cs @@ -2,14 +2,16 @@ namespace RedCatEngine.DependencyInjection.Exceptions { - public class NotFountInjectAttributeForConstructorException : Exception + public class NotFountInjectAttributeForConstructorException : Exception where TAttribute : Attribute { - private const string ErrorMessageFormat = "Not found InjectAttribute for construcor in Type {0}"; - public Type NotFoundType { get; } + private const string ErrorMessageFormat = "Type {0} not contain InjectAttribute {1} for construcor"; + public NotFountInjectAttributeForConstructorException(Type notFoundType) - : base(string.Format(ErrorMessageFormat, notFoundType)) + : base(string.Format(ErrorMessageFormat, notFoundType, typeof(TAttribute))) { NotFoundType = notFoundType; } + + public Type NotFoundType { get; } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Components/IMonoConstruct.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Components/IMonoConstruct.cs new file mode 100644 index 0000000..7de1c47 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Components/IMonoConstruct.cs @@ -0,0 +1,7 @@ +namespace RedCatEngine.DependencyInjection.Specials.Components +{ + public interface IMonoConstruct + { + public void FinishInitialize(); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Components/IMonoConstruct.cs.meta b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Components/IMonoConstruct.cs.meta new file mode 100644 index 0000000..0c8f6ad --- /dev/null +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Components/IMonoConstruct.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 18f23309641b4d6b93524b024d67ec05 +timeCreated: 1726745973 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Components/MonoConstruct.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Components/MonoConstruct.cs index 3a21031..a4a66bd 100644 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Components/MonoConstruct.cs +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Components/MonoConstruct.cs @@ -4,8 +4,10 @@ namespace RedCatEngine.DependencyInjection.Specials.Components { - public abstract class MonoConstruct : MonoBehaviour + public abstract class MonoConstruct : MonoBehaviour, IMonoConstruct, IDisposable { + private bool _isInitialize; + private void OnValidate() { #if UNITY_EDITOR @@ -17,13 +19,13 @@ private void OnValidate() foreach (var method in methods) { if (Attribute.GetCustomAttribute( - method, - typeof(MonoInjectAttribute), - true) != - null) - { - isHasInjectMethod = true; - } + method, + typeof(MonoInjectAttribute), + true) == + null) + continue; + + isHasInjectMethod = true; } if (!isHasInjectMethod) @@ -31,6 +33,41 @@ private void OnValidate() #endif } - protected virtual void DoValidate() { } + protected virtual void DoValidate() + { + } + + private void OnDisable() + { + Dispose(); + } + + protected virtual void DoInitialize() + { + } + + protected virtual void DoDisposable() + { + } + + public void Dispose() + { + if (!_isInitialize) + { +#if UNITY_EDITOR + Debug.LogWarningFormat("Not initialize element try to dispose in {0}", gameObject.name); +#endif + return; + } + + _isInitialize = false; + DoDisposable(); + } + + public void FinishInitialize() + { + DoInitialize(); + _isInitialize = true; + } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Injector.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Injector.cs new file mode 100644 index 0000000..34c8f7f --- /dev/null +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Injector.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; +using RedCatEngine.DependencyInjection.Exceptions; +using RedCatEngine.DependencyInjection.Specials.Providers; +using RedCatEngine.DependencyInjection.Utils; + +namespace RedCatEngine.DependencyInjection.Specials +{ + public class Injector + { + private readonly IGetterApplicationContainer _getter; + private readonly ProviderService _providerService; + + public Injector(IGetterApplicationContainer getter, ProviderService providerService) + { + _getter = getter; + _providerService = providerService; + } + + public object InjectContextToConstructor( + Type type, + MethodBase constructor, + object[] context + ) + { + var parameters = GetParametersForMethod(constructor, context); + return Activator.CreateInstance(type, parameters); + } + + public void InjectContextToMethodsWithAttribute(object objectToInject, params object[] context) + where TAttribute : Attribute + { + var type = objectToInject.GetType(); + var methods = type.GetMethods(); + var findConstructor = false; + foreach (var method in methods) + { + if (Attribute.GetCustomAttribute( + method, + typeof(TAttribute), + true) + == null) + continue; + + var parameters = GetParametersForMethod(method, context); + method.Invoke(objectToInject, parameters); + findConstructor = true; + } + if (findConstructor) + return; + throw new NotFountInjectAttributeForConstructorException(type); + } + + private object[] GetParametersForMethod(MethodBase method, object[] context) + { + var parameters = new List(); + + foreach (var parameterInfo in method.GetParameters()) + { + if (typeof(ISingleProvider<>).IsAssignableFromGeneric( + parameterInfo.ParameterType, + out var expectedSingleWaiterGenericType)) + { + parameters.Add(_providerService.RegisterProvider(expectedSingleWaiterGenericType[0])); + continue; + } + + if (typeof(IArrayProvider<>).IsAssignableFromGeneric( + parameterInfo.ParameterType, + out var expectedArrayWaiterGenericType)) + { + parameters.Add(_providerService.RegisterArrayProvider(expectedArrayWaiterGenericType[0])); + continue; + } + + parameters.Add(_getter.GetSingle(parameterInfo.ParameterType, context)); + } + return parameters.ToArray(); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Injector.cs.meta b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Injector.cs.meta new file mode 100644 index 0000000..b354112 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Injector.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 0a7e05fe35294a1ea204ccd8cd51a24d +timeCreated: 1734609063 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/ArrayProvider.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/ArrayProvider.cs index a5a2255..deca353 100644 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/ArrayProvider.cs +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/ArrayProvider.cs @@ -1,8 +1,11 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; +using RedCatEngine.DependencyInjection.Specials.Providers.Waiters; namespace RedCatEngine.DependencyInjection.Specials.Providers { - public class ArrayProvider : IArrayProvider, IArrayWaiter where TTypeProvide : class + public class ArrayProvider : IArrayProvider, IArrayWaiter + where TTypeProvide : class { private readonly List _instances = new(); @@ -12,6 +15,9 @@ public bool TryGet(out TTypeProvide[] instance) return instance.Length > 0; } + public Type[] ExpectedTypes + => new[] { typeof(TTypeProvide) }; + public void Attach(TTypeProvide waitType) => _instances.Add(waitType); diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/ISingleWaiter.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/ISingleWaiter.cs deleted file mode 100644 index 1dfb157..0000000 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/ISingleWaiter.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Collections.Generic; - -namespace RedCatEngine.DependencyInjection.Specials.Providers -{ - public interface IWaiter - { - void Attach(object waitType); - } - - public interface ISingleWaiter : IWaiter where TWaitType : class - { - void Attach(TWaitType waitType); - - void IWaiter.Attach(object waitType) - { - if (waitType is TWaitType typed) - Attach(typed); - } - } - - public interface IArrayWaiter : ISingleWaiter where TWaitType : class - { - void Attach(IEnumerable waitTypes); - - void IWaiter.Attach(object waitType) - { - if (waitType is TWaitType[] typed) - Attach(typed); - if(waitType is TWaitType type) - Attach(type); - } - } -} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/ProviderService.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/ProviderService.cs index 52981d4..9976bc6 100644 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/ProviderService.cs +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/ProviderService.cs @@ -1,28 +1,14 @@ using System; using System.Collections.Generic; using RedCatEngine.DependencyInjection.Containers.Interfaces.Application.Binders; +using RedCatEngine.DependencyInjection.Specials.Providers.Waiters; namespace RedCatEngine.DependencyInjection.Specials.Providers { public class ProviderService : IBinderApplicationContainer { - private readonly Dictionary> _singleWaits = new(); private readonly Dictionary> _arrayWaits = new(); - - private void AddWaiter( - IDictionary> waitersCashList, - Type key, - IWaiter provider - ) - { - if (!waitersCashList.TryGetValue(key, out var waiterList)) - { - waiterList = new List(); - waitersCashList.Add(key, waiterList); - } - - waiterList.Add(provider); - } + private readonly Dictionary> _singleWaits = new(); public ISingleProvider RegisterProvider() where TProvideType : class { @@ -30,7 +16,8 @@ public ISingleProvider RegisterProvider() where TPro AddWaiter( _singleWaits, typeof(TProvideType), - provider); + provider + ); return provider; } @@ -40,7 +27,8 @@ public object RegisterArrayProvider(Type providerType) AddWaiter( _arrayWaits, providerType, - (IWaiter)arrayProvider); + (IWaiter)arrayProvider + ); return arrayProvider; } @@ -50,7 +38,8 @@ public object RegisterProvider(Type providerType) AddWaiter( _singleWaits, providerType, - (IWaiter)provider); + (IWaiter)provider + ); return provider; } @@ -60,12 +49,31 @@ public IArrayProvider RegisterArrayProvider() where AddWaiter( _arrayWaits, typeof(TProvideType), - provider); + provider + ); return provider; } public TBindType BindAsSingle(TBindType instance) { + if (instance is IWaiter instanceWaiter) + { + if (instanceWaiter is ISingleWaiter singleWaiter) + foreach (var expectedType in singleWaiter.ExpectedTypes) + AddWaiter( + _singleWaits, + expectedType, + singleWaiter + ); + if (instanceWaiter is IArrayWaiter arrayWaiter) + foreach (var expectedType in arrayWaiter.ExpectedTypes) + AddWaiter( + _arrayWaits, + expectedType, + arrayWaiter + ); + } + if (!_singleWaits.TryGetValue(typeof(TBindType), out var waiterList)) return instance; @@ -74,6 +82,11 @@ public TBindType BindAsSingle(TBindType instance) return instance; } + public TBindType ReBindAsSingle(TBindType newInstance) + { + return BindAsArray(newInstance); + } + public TBindType BindAsArray(TBindType instance) { if (!_arrayWaits.TryGetValue(typeof(TBindType), out var waiterList)) @@ -83,5 +96,20 @@ public TBindType BindAsArray(TBindType instance) waiter.Attach(instance); return instance; } + + private void AddWaiter( + IDictionary> waitersCashList, + Type key, + IWaiter provider + ) + { + if (!waitersCashList.TryGetValue(key, out var waiterList)) + { + waiterList = new List(); + waitersCashList.Add(key, waiterList); + } + + waiterList.Add(provider); + } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/SingleProvider.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/SingleProvider.cs index 34b2479..cfabaf2 100644 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/SingleProvider.cs +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/SingleProvider.cs @@ -1,6 +1,10 @@ +using System; +using RedCatEngine.DependencyInjection.Specials.Providers.Waiters; + namespace RedCatEngine.DependencyInjection.Specials.Providers { - public class SingleProvider : ISingleProvider, ISingleWaiter where TTypeProvide : class + public class SingleProvider : ISingleProvider, ISingleWaiter + where TTypeProvide : class { private TTypeProvide _instance; @@ -10,6 +14,9 @@ public bool TryGet(out TTypeProvide instance) return instance != null; } + public Type[] ExpectedTypes + => new[] { typeof(TTypeProvide) }; + public void Attach(TTypeProvide waitType) { _instance = waitType; diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters.meta b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters.meta new file mode 100644 index 0000000..1559403 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b5f66e627ee24e3dbcadc3edef6e63d1 +timeCreated: 1729787435 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters/IArrayWaiter.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters/IArrayWaiter.cs new file mode 100644 index 0000000..da41eb9 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters/IArrayWaiter.cs @@ -0,0 +1,29 @@ +using System.Collections.Generic; + +namespace RedCatEngine.DependencyInjection.Specials.Providers.Waiters +{ + /// + /// Если кто-то реализует данный интерфейс, то он будет получать объекты указанных типов в случае регистрации их в контейнере как часть элементов массива + /// + public interface IArrayWaiter : IWaiter + { + } + + /// + /// Если кто-то реализует данный интерфейс, то он будет получать объекты указанных типов в случае регистрации их в контейнере как часть элементов массива + /// + public interface IArrayWaiter : IArrayWaiter where TWaitType : class + { + void IWaiter.Attach(object waitType) + { + if (waitType is TWaitType[] typed) + Attach(typed); + if (waitType is TWaitType type) + Attach(type); + } + + void Attach(IEnumerable waitTypes); + + void Attach(TWaitType waitType); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters/IArrayWaiter.cs.meta b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters/IArrayWaiter.cs.meta new file mode 100644 index 0000000..4e4ad6b --- /dev/null +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters/IArrayWaiter.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 90a520bbdc824f1c9b6608f7fb343fdc +timeCreated: 1729787445 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters/ISingleWaiter.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters/ISingleWaiter.cs new file mode 100644 index 0000000..9c7f480 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters/ISingleWaiter.cs @@ -0,0 +1,23 @@ +namespace RedCatEngine.DependencyInjection.Specials.Providers.Waiters +{ + /// + /// Если кто-то реализует данный интерфейс, то он будет получать объекты указанных типов в случае регистрации их в контейнере как Single-объект + /// + public interface ISingleWaiter : IWaiter + { + } + + /// + /// Если кто-то реализует данный интерфейс, то он будет получать объекты указанных типов в случае регистрации их в контейнере как Single-объект + /// + public interface ISingleWaiter : ISingleWaiter where TWaitType : class + { + void IWaiter.Attach(object waitType) + { + if (waitType is TWaitType typed) + Attach(typed); + } + + void Attach(TWaitType waitType); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/ISingleWaiter.cs.meta b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters/ISingleWaiter.cs.meta similarity index 100% rename from RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/ISingleWaiter.cs.meta rename to RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters/ISingleWaiter.cs.meta diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters/IWaiter.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters/IWaiter.cs new file mode 100644 index 0000000..5290a98 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters/IWaiter.cs @@ -0,0 +1,13 @@ +using System; + +namespace RedCatEngine.DependencyInjection.Specials.Providers.Waiters +{ + /// + /// Если кто-то реализует данный интерфейс, то он будет получать объекты указанных типов в случае регистрации их в контейнере + /// + public interface IWaiter + { + Type[] ExpectedTypes { get; } + void Attach(object waitType); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters/IWaiter.cs.meta b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters/IWaiter.cs.meta new file mode 100644 index 0000000..cb7a841 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Specials/Providers/Waiters/IWaiter.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: efc9141be4724dd497075d9a67f94f69 +timeCreated: 1729787445 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/DependencyInjection/Tests/ExceptionDiContainerTests.cs b/RedCatEngineUnityProject/Packages/DependencyInjection/Tests/ExceptionDiContainerTests.cs index 2861021..066d9fc 100644 --- a/RedCatEngineUnityProject/Packages/DependencyInjection/Tests/ExceptionDiContainerTests.cs +++ b/RedCatEngineUnityProject/Packages/DependencyInjection/Tests/ExceptionDiContainerTests.cs @@ -1,6 +1,7 @@ using System; using NUnit.Framework; using RedCatEngine.DependencyInjection.Containers; +using RedCatEngine.DependencyInjection.Containers.Attributes; using RedCatEngine.DependencyInjection.Exceptions; using RedCatEngine.DependencyInjection.Tests.SpecialSubClasses; @@ -19,9 +20,9 @@ public void GivenApplicationContainer_WhenGetNotContainInstance_ThenCatchNotFoun } catch (Exception exception) { - Assert.IsTrue(exception is NotFountInjectAttributeForConstructorException, "Incorrect error"); + Assert.IsTrue(exception is NotFountInjectAttributeForConstructorException, "Incorrect error"); Assert.IsTrue( - ((NotFountInjectAttributeForConstructorException)exception).NotFoundType == typeof(SimpleDemoSecondDataChildClass), + ((NotFountInjectAttributeForConstructorException)exception).NotFoundType == typeof(SimpleDemoSecondDataChildClass), "Incorrect type"); return; } diff --git a/RedCatEngineUnityProject/Packages/GameSettings/GameSettings.asmdef b/RedCatEngineUnityProject/Packages/GameSettings/GameSettings.asmdef new file mode 100644 index 0000000..89d2a3d --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/GameSettings.asmdef @@ -0,0 +1,17 @@ +{ + "name": "GameSettings", + "rootNamespace": "RedCatEngine.GameSettings", + "references": [ + "GUID:bc1a77b6bbee94316b30d47e73c29c41", + "GUID:79ad2193969254fbd829729521e3eee3" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/GameSettings.asmdef.meta b/RedCatEngineUnityProject/Packages/GameSettings/GameSettings.asmdef.meta new file mode 100644 index 0000000..a136217 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/GameSettings.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: cc52e4f89a357459b9813bd922ffcd33 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts.meta b/RedCatEngineUnityProject/Packages/GameSettings/Scripts.meta new file mode 100644 index 0000000..f5e26bf --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 217c5bd898964c11a13fcdce07a40604 +timeCreated: 1757322817 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/GameSettingService.cs b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/GameSettingService.cs new file mode 100644 index 0000000..4956f19 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/GameSettingService.cs @@ -0,0 +1,46 @@ +using System; +using RedCatEngine.GameSettings.TypeSettings; + +namespace RedCatEngine.GameSettings +{ + public class GameSettingService + { + public event Action GameSettingChangeEvent; + + private readonly OverrideSettingsData _overrideSettingsData; + + public void OverrideGameSetting(BaseGameSetting gameSetting) + { + _overrideSettingsData.AddOverride(gameSetting); + ApplySettingChange(gameSetting); + GameSettingChangeEvent?.Invoke(gameSetting); + } + + private void ApplySettingChange(BaseGameSetting gameSetting) + { + gameSetting.Apply(); + } + + public void LoadGameSetting() + { + var settingsConfig = GameSettingsConfig.Instance; + foreach (var baseSetting in settingsConfig.BaseSettings) + ApplySettingChange(baseSetting); + + _overrideSettingsData.Load(); + foreach (var baseSetting in _overrideSettingsData.Overrides) + ApplySettingChange(baseSetting); + } + + public void SaveSettings() + { + _overrideSettingsData.Save(); + } + + public void ResetSettings() + { + _overrideSettingsData.Reset(); + LoadGameSetting(); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/GameSettingService.cs.meta b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/GameSettingService.cs.meta new file mode 100644 index 0000000..18013d1 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/GameSettingService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: de1700243ae544959fddbfe065719ac8 +timeCreated: 1757322837 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/GameSettingsConfig.cs b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/GameSettingsConfig.cs new file mode 100644 index 0000000..d7e4960 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/GameSettingsConfig.cs @@ -0,0 +1,14 @@ +using RedCatEngine.Configs; +using RedCatEngine.GameSettings.TypeSettings; +using SerializeReferenceEditor; +using UnityEngine; + +namespace RedCatEngine.GameSettings +{ + [CreateAssetMenu(fileName = nameof(GameSettingsConfig), menuName = "Configs/Common/Game Settings Config")] + public class GameSettingsConfig : BaseSingleConfig + { + [SR][SerializeReference] + public BaseGameSetting[] BaseSettings; + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/GameSettingsConfig.cs.meta b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/GameSettingsConfig.cs.meta new file mode 100644 index 0000000..c03ea79 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/GameSettingsConfig.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ceab11a572804df49b0adcae9d756137 +timeCreated: 1757322983 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/Help.meta b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/Help.meta new file mode 100644 index 0000000..a8024c0 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/Help.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2b771fa3215f4c068cd07e2afaba6645 +timeCreated: 1757324514 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/Help/GraphicsSettingsApplier.cs b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/Help/GraphicsSettingsApplier.cs new file mode 100644 index 0000000..be3e9bd --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/Help/GraphicsSettingsApplier.cs @@ -0,0 +1,90 @@ +using UnityEngine; + +namespace RedCatEngine.GameSettings.Help +{ + /// + /// Класс для настройки графических параметров игры (разрешение, качество, FPS и т.д.) + /// + internal static class GraphicsSettingsApplier + { + /// + /// Установка разрешения экрана и режима окна. + /// + /// Ширина экрана в пикселях. + /// Высота экрана в пикселях. + /// Режим отображения: FullScreen, Windowed, MaximizedWindow и др. + /// Частота обновления экрана (в Гц). + public static void SetResolution( + int width, + int height, + FullScreenMode mode, + RefreshRate refreshRate + ) + { + Screen.SetResolution( + width, + height, + mode, + refreshRate); + } + + /// Индекс уровня качества из списка Quality Settings. + /// Применять ли дорогостоящие изменения (например, изменение теней). + public static void SetQualityLevel(int level, bool applyExpensiveChanges = true) + { + QualitySettings.SetQualityLevel(level, applyExpensiveChanges); + } + + /// + /// Включение или выключение отрисовки теней. + /// + /// Если true — включает тени, если false — отключает. + public static void SetShadows(bool enabled) + { + QualitySettings.shadows = enabled ? ShadowQuality.All : ShadowQuality.Disable; + } + + /// + /// Установка уровня антиалиасинга. + /// + /// Уровень MSAA: 0 — отключено, 2, 4, 8 — количество сэмплов. + public static void SetAntiAliasing(int level) + { + QualitySettings.antiAliasing = level; + } + + /// + /// Включение или выключение VSync (синхронизация вертикального сканирования). + /// + /// Если true — включает VSync, если false — отключает. + public static void SetVSync(bool enabled) + { + QualitySettings.vSyncCount = enabled ? 1 : 0; + } + + /// + /// Ограничение максимального количества кадров в секунду (FPS). + /// + /// Целевое количество кадров в секунду. Если меньше 0 — ограничение отключается. + public static void SetFrameRateCap(int targetFps) + { + Application.targetFrameRate = targetFps > 0 + ? targetFps + : -1; // -1 = без лимита + } + + /// + /// Включение или выключение эффекта Motion Blur (движущегося размытия). + /// + /// Если true — включает Motion Blur, если false — отключает. + /// + /// Реализация зависит от используемой системы постобработки (URP/HDRP или PostProcessing Stack). + /// Обычно требуется получить VolumeProfile и включить/выключить соответствующий компонент. + /// + public static void SetMotionBlur(bool enabled) + { + // Здесь зависит от твоего постпроцессинга (URP/HDRP или PostProcessing Stack) + // Обычно ищешь VolumeProfile и включаешь/выключаешь компонент + } + } +} diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/Help/GraphicsSettingsApplier.cs.meta b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/Help/GraphicsSettingsApplier.cs.meta new file mode 100644 index 0000000..8d868e0 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/Help/GraphicsSettingsApplier.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f0477d3b8f434de28414e022473fa6f9 +timeCreated: 1757335006 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/Help/SettingsSerializer.cs b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/Help/SettingsSerializer.cs new file mode 100644 index 0000000..8ed4f9c --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/Help/SettingsSerializer.cs @@ -0,0 +1,43 @@ +using System.IO; +using UnityEngine; + +namespace RedCatEngine.GameSettings.Help +{ + public class SettingsSerializer where TSerializedData : new() + { + private readonly string _projectName = Application.productName; + private readonly string _settingsFilePath; + + public SettingsSerializer(string settingsFilePath, string fileName) + { + _settingsFilePath = Path.Combine(settingsFilePath, $"{_projectName}_{fileName}.json"); + } + + public bool TryLoadDataFrom(out TSerializedData data) + { + if (!File.Exists(_settingsFilePath)) + { + data = new TSerializedData(); + Save(data); + return true; + } + + var json = File.ReadAllText(_settingsFilePath); + data = LoadDataFrom(json); + return data != null; + } + + public void Save(TSerializedData data) + { + File.WriteAllText(_settingsFilePath, GetDataFrom(data)); + } + + private string GetDataFrom(TSerializedData data) + => JsonUtility.ToJson(data); + + private TSerializedData LoadDataFrom(string json) + => string.IsNullOrEmpty(json) + ? new TSerializedData() + : JsonUtility.FromJson(json); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/Help/SettingsSerializer.cs.meta b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/Help/SettingsSerializer.cs.meta new file mode 100644 index 0000000..73d09f5 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/Help/SettingsSerializer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 37749e72a3544b5faf6813eda8b88596 +timeCreated: 1757324521 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/OverrideSettingsData.cs b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/OverrideSettingsData.cs new file mode 100644 index 0000000..c920242 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/OverrideSettingsData.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using RedCatEngine.GameSettings.Help; +using RedCatEngine.GameSettings.TypeSettings; +using UnityEngine; + +namespace RedCatEngine.GameSettings +{ + [Serializable] + public class OverrideSettingsData + { + [SerializeField] + private List _overrides = new(); + + private readonly SettingsSerializer _overrideSettingsSaver + = new( + Application.persistentDataPath, + "overrideSettingsData"); + + public IReadOnlyList Overrides + => _overrides; + + public void Save() + { + _overrideSettingsSaver.Save(this); + } + + public void Load() + { + if (!_overrideSettingsSaver.TryLoadDataFrom(out var data)) + { + Debug.LogError("OverrideSettingsData could not be loaded."); + return; + } + + _overrides.Clear(); + _overrides.AddRange(data._overrides); + } + + public void AddOverride(BaseGameSetting gameSetting) + { + _overrides.Add(gameSetting); + } + + public void Reset() + { + _overrides.Clear(); + Save(); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/OverrideSettingsData.cs.meta b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/OverrideSettingsData.cs.meta new file mode 100644 index 0000000..6b65899 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/OverrideSettingsData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: fa95f7b812a74c79a618e848d1eebac0 +timeCreated: 1757324601 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings.meta b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings.meta new file mode 100644 index 0000000..d1eaee4 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d2d4af9ff21748fc840656be97a88283 +timeCreated: 1757322928 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/BaseGameSetting.cs b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/BaseGameSetting.cs new file mode 100644 index 0000000..820243f --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/BaseGameSetting.cs @@ -0,0 +1,25 @@ +using System; + +namespace RedCatEngine.GameSettings.TypeSettings +{ + [Serializable] + public abstract class BaseGameSetting + { + public abstract string SaveKey { get; } + public int Id + => SaveKey.GetHashCode(); + + protected virtual bool IsCanApply() + { + return true; + } + + public void Apply() + { + if (IsCanApply()) + DoApply(); + } + + protected abstract void DoApply(); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/BaseGameSetting.cs.meta b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/BaseGameSetting.cs.meta new file mode 100644 index 0000000..a262d0c --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/BaseGameSetting.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ff52861d32cf4fedab539a499dd3dcd2 +timeCreated: 1757322938 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/BoolGameSettings.cs b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/BoolGameSettings.cs new file mode 100644 index 0000000..8c1bb89 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/BoolGameSettings.cs @@ -0,0 +1,12 @@ +namespace RedCatEngine.GameSettings.TypeSettings +{ + public abstract class BoolGameSettings : BaseGameSetting + { + public bool Value; + + protected BoolGameSettings(bool value) + { + Value = value; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/BoolGameSettings.cs.meta b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/BoolGameSettings.cs.meta new file mode 100644 index 0000000..e827036 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/BoolGameSettings.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a5c2ae57dc4e41aeade62776fb53e7a3 +timeCreated: 1757337703 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics.meta b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics.meta new file mode 100644 index 0000000..64c0956 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 08449912e46c45ebb3fdfc520ddefb2a +timeCreated: 1757334883 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/FrameRateCapGameSettings.cs b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/FrameRateCapGameSettings.cs new file mode 100644 index 0000000..f0883a9 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/FrameRateCapGameSettings.cs @@ -0,0 +1,30 @@ +using System; +using RedCatEngine.GameSettings.Help; +using SerializeReferenceEditor; + +namespace RedCatEngine.GameSettings.TypeSettings.Graphics +{ + [Serializable] + [SRName("Graphics/Frame Rate Cap")] + public class FrameRateCapGameSettings : BaseGameSetting + { + public override string SaveKey + => nameof(TargetFrameRate); + + public int TargetFrameRate = -1; + + public FrameRateCapGameSettings() + { + } + + public FrameRateCapGameSettings(int targetFrameRate) + { + TargetFrameRate = targetFrameRate; + } + + protected override void DoApply() + { + GraphicsSettingsApplier.SetFrameRateCap(TargetFrameRate); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/FrameRateCapGameSettings.cs.meta b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/FrameRateCapGameSettings.cs.meta new file mode 100644 index 0000000..468a5cd --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/FrameRateCapGameSettings.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 571391e27013497b92a76905caf79182 +timeCreated: 1757336462 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/QualityLevelGameSettings.cs b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/QualityLevelGameSettings.cs new file mode 100644 index 0000000..2b68ea6 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/QualityLevelGameSettings.cs @@ -0,0 +1,32 @@ +using System; +using RedCatEngine.GameSettings.Help; +using SerializeReferenceEditor; + +namespace RedCatEngine.GameSettings.TypeSettings.Graphics +{ + [Serializable] + [SRName("Graphics/Quality Level")] + public class QualityLevelGameSettings : BaseGameSetting + { + public override string SaveKey + => nameof(QualityLevelGameSettings); + + public int Level; + + public QualityLevelGameSettings() + { + } + + public QualityLevelGameSettings( + int level + ) + { + Level = level; + } + + protected override void DoApply() + { + GraphicsSettingsApplier.SetQualityLevel(Level, true); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/QualityLevelGameSettings.cs.meta b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/QualityLevelGameSettings.cs.meta new file mode 100644 index 0000000..aa8b02e --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/QualityLevelGameSettings.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a9170fa430e643b08d5af19a0fa6bf66 +timeCreated: 1757336139 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/ResolutionGameSetting.cs b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/ResolutionGameSetting.cs new file mode 100644 index 0000000..d3ed579 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/ResolutionGameSetting.cs @@ -0,0 +1,50 @@ +using System; +using RedCatEngine.GameSettings.Help; +using SerializeReferenceEditor; +using UnityEngine; + +namespace RedCatEngine.GameSettings.TypeSettings.Graphics +{ + [Serializable] + [SRName("Graphics/Resolution")] + public class ResolutionGameSetting : BaseGameSetting + { + public override string SaveKey + => nameof(ResolutionGameSetting); + + public int Width = 1920; + public int Height = 1080; + public FullScreenMode Mode = FullScreenMode.ExclusiveFullScreen; + public RefreshRate RefreshRate = new() + { + numerator = 1, + denominator = 60 + }; + + public ResolutionGameSetting() + { + } + + public ResolutionGameSetting( + int width, + int height, + FullScreenMode mode, + RefreshRate refreshRate + ) + { + Width = width; + Height = height; + Mode = mode; + RefreshRate = refreshRate; + } + + protected override void DoApply() + { + GraphicsSettingsApplier.SetResolution( + Width, + Height, + Mode, + RefreshRate); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/ResolutionGameSetting.cs.meta b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/ResolutionGameSetting.cs.meta new file mode 100644 index 0000000..082057b --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/ResolutionGameSetting.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 46e4dd4158a04a0691a7048bbd63bc7d +timeCreated: 1757335482 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/ShadowsGameSettings.cs b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/ShadowsGameSettings.cs new file mode 100644 index 0000000..ad04ac8 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/ShadowsGameSettings.cs @@ -0,0 +1,28 @@ +using System; +using RedCatEngine.GameSettings.Help; +using SerializeReferenceEditor; + +namespace RedCatEngine.GameSettings.TypeSettings.Graphics +{ + [Serializable] + [SRName("Graphics/Shadows Game Settings")] + public class ShadowsGameSettings : BoolGameSettings + { + public override string SaveKey + => nameof(ShadowsGameSettings); + + + public ShadowsGameSettings() : base(true) + { + } + + public ShadowsGameSettings(bool shadowsEnabled) : base(shadowsEnabled) + { + } + + protected override void DoApply() + { + GraphicsSettingsApplier.SetShadows(Value); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/ShadowsGameSettings.cs.meta b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/ShadowsGameSettings.cs.meta new file mode 100644 index 0000000..8a74702 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/ShadowsGameSettings.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 84535e4286224caea15d22d6e6fe5d82 +timeCreated: 1757336260 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/VSyncGameSettings.cs b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/VSyncGameSettings.cs new file mode 100644 index 0000000..dc29a8d --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/VSyncGameSettings.cs @@ -0,0 +1,28 @@ +using System; +using RedCatEngine.GameSettings.Help; +using SerializeReferenceEditor; + +namespace RedCatEngine.GameSettings.TypeSettings.Graphics +{ + [Serializable] + [SRName("Graphics/VSync")] + public class VSyncGameSettings : BoolGameSettings + { + public override string SaveKey + => nameof(VSyncGameSettings); + + + public VSyncGameSettings() : base(false) + { + } + + public VSyncGameSettings(bool vSyncValue) : base(vSyncValue) + { + } + + protected override void DoApply() + { + GraphicsSettingsApplier.SetVSync(Value); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/VSyncGameSettings.cs.meta b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/VSyncGameSettings.cs.meta new file mode 100644 index 0000000..cb912a3 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/Scripts/TypeSettings/Graphics/VSyncGameSettings.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7e7b8b81a1b14646a54315279efa947f +timeCreated: 1757336388 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/package.json b/RedCatEngineUnityProject/Packages/GameSettings/package.json new file mode 100644 index 0000000..552a562 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/package.json @@ -0,0 +1,11 @@ +{ + "name": "com.boronnikov.games.red-cat-engine.gamesettings", + "version": "1.0.0", + "displayName": "Red Cat Engine: Game Settings", + "description": "Simple game settings", + "unity": "6000.0", + "author": { + "name": "Boronnikov Games", + "url": "https://github.com/Red-Cat-Fat" + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/GameSettings/package.json.meta b/RedCatEngineUnityProject/Packages/GameSettings/package.json.meta new file mode 100644 index 0000000..f9e4388 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/GameSettings/package.json.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 991efce096132499fae249d88221d0d6 +timeCreated: 1713125223 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers.meta b/RedCatEngineUnityProject/Packages/Pools/Containers.meta new file mode 100644 index 0000000..5e80420 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: bf7212741c86a4d48a9cf594dde33b4c +timeCreated: 1726235041 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/Creators.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators.meta new file mode 100644 index 0000000..e645c4f --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 776a1beacaa843fcb7643fa7bca32330 +timeCreated: 1731065797 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/Factories.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/Factories.meta new file mode 100644 index 0000000..48d48e1 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/Factories.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 012398c2a16746a5905d1db23ca8c101 +timeCreated: 1731077506 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/Factories/IPoolInstanceCreatorFactory.cs b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/Factories/IPoolInstanceCreatorFactory.cs new file mode 100644 index 0000000..d0a7fc5 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/Factories/IPoolInstanceCreatorFactory.cs @@ -0,0 +1,10 @@ +using RedCatEngine.Pools.Containers.Creators.InstanceCreator; +using UnityEngine; + +namespace RedCatEngine.Pools.Containers.Creators.Factories +{ + public interface IPoolInstanceCreatorFactory + { + IInstanceCreator Make(GameObject prefab, Transform parent); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/Factories/IPoolInstanceCreatorFactory.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/Factories/IPoolInstanceCreatorFactory.cs.meta new file mode 100644 index 0000000..4d71f22 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/Factories/IPoolInstanceCreatorFactory.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 140db60bf6a449dfa82bd78c811fa73d +timeCreated: 1731076633 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/Factories/SimpleUnityPoolInstanceCreatorFactory.cs b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/Factories/SimpleUnityPoolInstanceCreatorFactory.cs new file mode 100644 index 0000000..e9fcb75 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/Factories/SimpleUnityPoolInstanceCreatorFactory.cs @@ -0,0 +1,11 @@ +using RedCatEngine.Pools.Containers.Creators.InstanceCreator; +using UnityEngine; + +namespace RedCatEngine.Pools.Containers.Creators.Factories +{ + public class SimpleUnityPoolInstanceCreatorFactory : IPoolInstanceCreatorFactory + { + public IInstanceCreator Make(GameObject prefab, Transform parent) + => new SimpleUnityInstanceCreator(prefab, parent); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/Factories/SimpleUnityPoolInstanceCreatorFactory.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/Factories/SimpleUnityPoolInstanceCreatorFactory.cs.meta new file mode 100644 index 0000000..c234cfa --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/Factories/SimpleUnityPoolInstanceCreatorFactory.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b916e1eb80434c0db3ebfcda4d77a958 +timeCreated: 1731076681 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/InstanceCreator.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/InstanceCreator.meta new file mode 100644 index 0000000..e49eb33 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/InstanceCreator.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2996da430f824265a9c32bb498e39f96 +timeCreated: 1731077491 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/InstanceCreator/IInstanceCreator.cs b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/InstanceCreator/IInstanceCreator.cs new file mode 100644 index 0000000..110db34 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/InstanceCreator/IInstanceCreator.cs @@ -0,0 +1,9 @@ +using RedCatEngine.Pools.Pools; + +namespace RedCatEngine.Pools.Containers.Creators.InstanceCreator +{ + public interface IInstanceCreator + { + IPooledObject Create(params object[] context); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/InstanceCreator/IInstanceCreator.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/InstanceCreator/IInstanceCreator.cs.meta new file mode 100644 index 0000000..2a583a8 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/InstanceCreator/IInstanceCreator.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3a33ff4a4f014340b7289c0e36a66c4b +timeCreated: 1731073926 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/InstanceCreator/SimpleUnityInstanceCreator.cs b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/InstanceCreator/SimpleUnityInstanceCreator.cs new file mode 100644 index 0000000..1ca0e0b --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/InstanceCreator/SimpleUnityInstanceCreator.cs @@ -0,0 +1,29 @@ +using RedCatEngine.Pools.Pools; +using UnityEngine; + +namespace RedCatEngine.Pools.Containers.Creators.InstanceCreator +{ + public class SimpleUnityInstanceCreator : IInstanceCreator + { + private readonly GameObject _prefab; + private readonly Transform _parent; + + public SimpleUnityInstanceCreator(GameObject prefab, Transform parent) + { + _prefab = prefab; + _parent = parent; + } + + public IPooledObject Create(params object[] context) + { + var instance = Object.Instantiate(_prefab, _parent); + if (instance.TryGetComponent(out var pooledObject)) + return pooledObject; + + var programApplier = instance.AddComponent(); + programApplier.CollectPooledComponents(); + + return programApplier; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/InstanceCreator/SimpleUnityInstanceCreator.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/InstanceCreator/SimpleUnityInstanceCreator.cs.meta new file mode 100644 index 0000000..7fd048e --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/Creators/InstanceCreator/SimpleUnityInstanceCreator.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 05c76429cf1f441aaa9025ff2af056fa +timeCreated: 1731073992 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/Enumerators.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/Enumerators.meta new file mode 100644 index 0000000..a02c033 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/Enumerators.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f2a73ef674b37634188564639371fa90 +timeCreated: 1728468067 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/Enumerators/GameObjectsEnumerator.cs b/RedCatEngineUnityProject/Packages/Pools/Containers/Enumerators/GameObjectsEnumerator.cs new file mode 100644 index 0000000..965d45d --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/Enumerators/GameObjectsEnumerator.cs @@ -0,0 +1,12 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace RedCatEngine.Pools.Containers.Enumerators +{ + public class GameObjectsEnumerator : PooledObjectTypedEnumerator + { + public GameObjectsEnumerator(IEnumerable collection) : base(collection) + { + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/Enumerators/GameObjectsEnumerator.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/Enumerators/GameObjectsEnumerator.cs.meta new file mode 100644 index 0000000..3c5a95d --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/Enumerators/GameObjectsEnumerator.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b66c9fa64e11f0c42aca7d11b36af91d +timeCreated: 1728468084 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/Enumerators/PooledObjectTypedEnumerator.cs b/RedCatEngineUnityProject/Packages/Pools/Containers/Enumerators/PooledObjectTypedEnumerator.cs new file mode 100644 index 0000000..e138067 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/Enumerators/PooledObjectTypedEnumerator.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace RedCatEngine.Pools.Containers.Enumerators +{ + public class PooledObjectTypedEnumerator : IEnumerator + { + private readonly TReturnEnumeratorType[] _collection; + private int _index = -1; + + public PooledObjectTypedEnumerator(IEnumerable collection) + { + _collection = collection.ToArray(); + } + + private TReturnEnumeratorType TypedCurrent + { + get + { + try + { + return _collection[_index]; + } + catch (IndexOutOfRangeException) + { + throw new InvalidOperationException(); + } + } + } + + TReturnEnumeratorType IEnumerator.Current + => TypedCurrent; + + public object Current + => TypedCurrent; + + public bool MoveNext() + { + _index++; + return _index < _collection.Length; + } + + public void Reset() + { + _index = -1; + } + + public void Dispose() + { + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/Enumerators/PooledObjectTypedEnumerator.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/Enumerators/PooledObjectTypedEnumerator.cs.meta new file mode 100644 index 0000000..60dc0a3 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/Enumerators/PooledObjectTypedEnumerator.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: aa3d5928a538de04fa9d70fdaca2f77a +timeCreated: 1728467568 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/IPoolComponentsContainer.cs b/RedCatEngineUnityProject/Packages/Pools/Containers/IPoolComponentsContainer.cs new file mode 100644 index 0000000..ad47e15 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/IPoolComponentsContainer.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using RedCatEngine.Pools.Pools; +using UnityEngine; + +namespace RedCatEngine.Pools.Containers +{ + public interface IPoolComponentsContainer + : IEnumerable, IPoolContainer + where TComponent : IPooledObject + { + TComponent this[int currentSelectIndex] { get; } + int Length { get; } + new IEnumerator GetEnumerator(); + TComponent InstantiateComponent(params object[] context); + TComponent InstantiateComponent(Vector3 position, params object[] context); + TComponent InstantiateComponentAsLastSibling(params object[] context); + void KillAll(Action callbackBeforeKill); + GameObject InstantiateAsLastSibling(params object[] context); + GameObject Instantiate(params object[] context); + GameObject Instantiate( + Vector3 position, + params object[] context + ); + GameObject Instantiate( + Vector3 position, + Quaternion rotation, + params object[] context + ); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/IPoolComponentsContainer.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/IPoolComponentsContainer.cs.meta new file mode 100644 index 0000000..8b86111 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/IPoolComponentsContainer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 17ef1d76a1284192aff11257a2861723 +timeCreated: 1753787125 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/IPoolContainer.cs b/RedCatEngineUnityProject/Packages/Pools/Containers/IPoolContainer.cs new file mode 100644 index 0000000..42f6e76 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/IPoolContainer.cs @@ -0,0 +1,12 @@ +using System; +using UnityEngine; + +namespace RedCatEngine.Pools.Containers +{ + public interface IPoolContainer + { + void SetBeforeDisableCallback(Action callbackBeforeDisable); + void SetAfterEnableCallback(Action callbackAfterEnable); + void KillAll(Action callbackBeforeKill = null); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/IPoolContainer.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/IPoolContainer.cs.meta new file mode 100644 index 0000000..3e25ac9 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/IPoolContainer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b89bb11a32fc42cdb38909900865be3e +timeCreated: 1730467712 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/IPoolObjectsContainer.cs b/RedCatEngineUnityProject/Packages/Pools/Containers/IPoolObjectsContainer.cs new file mode 100644 index 0000000..a655b87 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/IPoolObjectsContainer.cs @@ -0,0 +1,9 @@ +using UnityEngine; + +namespace RedCatEngine.Pools.Containers +{ + public interface IPoolObjectsContainer : IPoolContainer + { + public GameObject Instantiate(params object[] context); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/IPoolObjectsContainer.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/IPoolObjectsContainer.cs.meta new file mode 100644 index 0000000..7a242cb --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/IPoolObjectsContainer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 6d15cb5e87585474ea837094c7edf56d +timeCreated: 1726234846 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers.meta new file mode 100644 index 0000000..fabe841 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 99ec006d461149f194e393842a3045dd +timeCreated: 1730467626 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/IKeyPoolComponentsContainer.cs b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/IKeyPoolComponentsContainer.cs new file mode 100644 index 0000000..9ad00e1 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/IKeyPoolComponentsContainer.cs @@ -0,0 +1,25 @@ +using System; +using JetBrains.Annotations; +using RedCatEngine.Pools.Containers.KeyContainers.Rules; +using RedCatEngine.Pools.Pools; + +namespace RedCatEngine.Pools.Containers.KeyContainers +{ + public interface IKeyPoolComponentsContainer : IKeyPoolContainer + where TKey : IKeyRuleGameObjectSelector where TComponent : IPooledObject + { + /// + /// Создаёт объект и возвращает экземпляр компонента с этого объекта, который соответствующий указанному ключу. + /// + /// Ключ, определяющий пул для создаваемого объекта. + /// Дополнительные параметры для передачи в конструктор объекта (если требуется). + /// Созданный экземпляр компонента . + TComponent InstantiateComponent(TKey key, params object[] context); + + /// + /// Уничтожает все активные объекты в пуле, вызывая указанный коллбэк перед уничтожением каждого компонента. + /// + /// Действие, которое будет выполнено перед уничтожением каждого компонента. + void KillAll([CanBeNull] Action callbackBeforeKill); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/IKeyPoolComponentsContainer.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/IKeyPoolComponentsContainer.cs.meta new file mode 100644 index 0000000..df5c18f --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/IKeyPoolComponentsContainer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d40b7bbecb5f4f42a303013517b49bcf +timeCreated: 1753793230 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/IKeyPoolContainer.cs b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/IKeyPoolContainer.cs new file mode 100644 index 0000000..f484cf0 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/IKeyPoolContainer.cs @@ -0,0 +1,45 @@ +using RedCatEngine.Pools.Containers.KeyContainers.Rules; +using RedCatEngine.Pools.Pools; +using UnityEngine; + +namespace RedCatEngine.Pools.Containers.KeyContainers +{ + /// + /// Интерфейс, предоставляющий функциональность пула игровых объектов, организованного по ключам. + /// Позволяет создавать экземпляры игровых объектов на основе заданного ключа. + /// + /// Тип ключа, используемого для группировки объектов в пуле. + /// Должен реализовывать . + public interface IKeyPoolContainer : IPoolContainer where TKey : IKeyRuleGameObjectSelector + { + /// + /// Создаёт и возвращает новый игровой объект из пула, соответствующего указанному ключу. + /// + /// Ключ, определяющий тип объекта в пуле. + /// Дополнительные параметры, передаваемые при создании объекта. + /// Созданный игровой объект. + GameObject Instantiate(TKey key, params object[] additionalContext); + + /// + /// Создаёт и возвращает новый игровой объект из пула, соответствующего указанному ключу. + /// + /// Ключ, определяющий тип объекта в пуле. + /// Позиция, куда создать объект + /// Поворот с которым создать объект + /// Дополнительные параметры, передаваемые при создании объекта. + /// Созданный игровой объект. + GameObject Instantiate(TKey key, Vector3 transformPosition, Quaternion transformRotation, params object[] additionalContext); + + /// + /// Создаёт новый игровой объект из пула, и возвращает компонент типа из пула, + /// соответствующего указанному ключу. + /// + /// Тип компонента, который должен быть привязан к игровому объекту. + /// Должен реализовывать . + /// Ключ, определяющий тип объекта в пуле. + /// Дополнительные параметры, передаваемые при создании объекта. + /// Созданный компонент типа . + TComponent Instantiate(TKey key, params object[] additionalContext) + where TComponent : IPooledObject; + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/IKeyPoolContainer.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/IKeyPoolContainer.cs.meta new file mode 100644 index 0000000..6d3bc28 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/IKeyPoolContainer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2c38e81018894f40b5c14f9a2592d7f6 +timeCreated: 1730467643 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/KeyPoolComponentsContainer.cs b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/KeyPoolComponentsContainer.cs new file mode 100644 index 0000000..a4e0f42 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/KeyPoolComponentsContainer.cs @@ -0,0 +1,52 @@ +using System; +using RedCatEngine.Pools.Containers.Creators.Factories; +using RedCatEngine.Pools.Containers.KeyContainers.Rules; +using RedCatEngine.Pools.Pools; +using UnityEngine; + +namespace RedCatEngine.Pools.Containers.KeyContainers +{ + /// + /// Контейнер пула компонентов, разделённый по ключам. + /// Позволяет работать не просто с пулом GameObjects, а с пулом компонентов , которые берутся с созданных объектов. + /// + /// Тип ключа, используемого для группировки объектов в пуле. Должен реализовывать , который будет возвращать объект для пула. + /// Тип компонента, который создаётся и управляется внутри пула. Должен реализовывать . + public class KeyPoolComponentsContainer : KeyPoolContainer, IKeyPoolComponentsContainer + where TKey : IKeyRuleGameObjectSelector + where TComponent : IPooledObject + { + /// + /// Инициализирует новый экземпляр . + /// + /// Фабрика, отвечающая за создание инстансов игровых объектов. + /// Родительский трансформ, к которому будут добавляться игровые объекты. + public KeyPoolComponentsContainer(IPoolInstanceCreatorFactory creatorFactory, Transform parentTransform) + : base(creatorFactory, parentTransform) + { + } + + /// + /// Создаёт объект и возвращает экземпляр компонента с этого объекта, который соответствующий указанному ключу. + /// + /// Ключ, определяющий пул для создаваемого объекта. + /// Дополнительные параметры для передачи в конструктор объекта (если требуется). + /// Созданный экземпляр компонента . + public TComponent InstantiateComponent(TKey key, params object[] context) + => Instantiate(key, context); + + /// + /// Уничтожает все активные объекты в пуле, вызывая указанный коллбэк перед уничтожением каждого компонента. + /// + /// Действие, которое будет выполнено перед уничтожением каждого компонента. + public void KillAll(Action callbackBeforeKill) + { + base.KillAll(go => + { + if (go.TryGetComponent(out var component)) + callbackBeforeKill?.Invoke(component); + } + ); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/KeyPoolComponentsContainer.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/KeyPoolComponentsContainer.cs.meta new file mode 100644 index 0000000..896c2b4 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/KeyPoolComponentsContainer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 0f3aada437f24bbfb409c2a33c6e9c63 +timeCreated: 1730468434 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/KeyPoolContainer.cs b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/KeyPoolContainer.cs new file mode 100644 index 0000000..ba17bdf --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/KeyPoolContainer.cs @@ -0,0 +1,148 @@ +using System; +using System.Collections.Generic; +using RedCatEngine.Pools.Containers.Creators.Factories; +using RedCatEngine.Pools.Containers.KeyContainers.Rules; +using RedCatEngine.Pools.Containers.SimpleContainers; +using RedCatEngine.Pools.Pools; +using UnityEngine; + +namespace RedCatEngine.Pools.Containers.KeyContainers +{ + /// + /// Контейнер пула игровых объектов, разделённых по ключам. + /// Позволяет создавать, управлять и уничтожать игровые объекты на основе ключа . + /// + /// Тип ключа, используемого для группировки объектов в пуле. + /// Должен реализовывать интерфейс . + public class KeyPoolContainer : IKeyPoolContainer where TKey : IKeyRuleGameObjectSelector + { + /// + /// Фабрика для создания инстансов игровых объектов. + /// + private readonly IPoolInstanceCreatorFactory _creatorFactory; + + /// + /// Родительский трансформ, к которому будут добавляться игровые объекты. + /// + private readonly Transform _parentTransform; + + /// + /// Словарь, хранящий пул объектов, индексированный по ключу . + /// + private readonly Dictionary _pools = new(); + + /// + /// Коллбэк, вызываемый после активации игрового объекта из пула. + /// + private Action _callbackAfterEnable; + + /// + /// Коллбэк, вызываемый перед деактивацией игрового объекта в пуле. + /// + private Action _callbackBeforeDisable; + + /// + /// Инициализирует новый экземпляр класса . + /// + /// Фабрика для создания инстансов игровых объектов. + /// Родительский трансформ для позиционирования объектов. + public KeyPoolContainer(IPoolInstanceCreatorFactory creatorFactory, Transform parentTransform) + { + _creatorFactory = creatorFactory; + _parentTransform = parentTransform; + } + + /// + /// Получает или создаёт при отсутствии пул игровых объектов для указанного ключа. + /// + /// Ключ, определяющий тип объекта в пуле. + /// Пул объектов, связанных с данным ключом. + private PoolObjectsContainer GetOrCreatePoolObject(TKey key) + { + if (_pools.TryGetValue(key, out var pool)) + return pool; + + var creator = _creatorFactory.Make(key.GetGameObjectForPool(), _parentTransform); + pool = new PoolObjectsContainer(creator); + pool.SetAfterEnableCallback(_callbackAfterEnable); + pool.SetBeforeDisableCallback(_callbackBeforeDisable); + _pools.Add(key, pool); + return pool; + } + + /// + /// Создаёт и возвращает новый игровой объект из пула, соответствующего указанному ключу. + /// + /// Ключ, определяющий тип объекта в пуле. + /// Позиция, в которой будет создан объект. + /// Поворот, в котором будет создан объект. + /// Дополнительные параметры для передачи в конструктор объекта. + /// Созданный игровой объект. + public GameObject Instantiate( + TKey key, + Vector3 position, + Quaternion rotation, + params object[] additionalContext + ) + { + var pool = GetOrCreatePoolObject(key); + return pool.Instantiate(position, rotation, additionalContext); + } + + /// + /// Устанавливает коллбэк, который будет вызван после активации каждого игрового объекта из пула. + /// + /// Действие, которое выполняется после активации объекта. + public void SetAfterEnableCallback(Action callbackAfterEnable) + { + _callbackAfterEnable = callbackAfterEnable; + foreach (var poolKey in _pools.Keys) + _pools[poolKey].SetAfterEnableCallback(callbackAfterEnable); + } + + /// + /// Уничтожает все активные объекты во всех пулах. + /// + /// Действие, выполняемое перед уничтожением каждого объекта. + public void KillAll(Action callbackBeforeKill = null) + { + foreach (var pool in _pools.Values) + pool.KillAll(callbackBeforeKill); + } + + /// + /// Устанавливает коллбэк, который будет вызван перед деактивацией каждого игрового объекта в пуле. + /// + /// Действие, которое выполняется перед деактивацией объекта. + public void SetBeforeDisableCallback(Action callbackBeforeDisable) + { + _callbackBeforeDisable = callbackBeforeDisable; + foreach (var poolKey in _pools.Keys) + _pools[poolKey].SetBeforeDisableCallback(callbackBeforeDisable); + } + + /// + /// Создаёт и возвращает новый игровой объект из пула, соответствующего указанному ключу. + /// + /// Ключ, определяющий тип объекта в пуле. + /// Дополнительные параметры для передачи в конструктор объекта. + /// Созданный игровой объект. + public GameObject Instantiate(TKey key, params object[] additionalContext) + { + var pool = GetOrCreatePoolObject(key); + return pool.Instantiate(additionalContext); + } + + /// + /// Создаёт и возвращает новый объект типа из пула, + /// соответствующего указанному ключу. + /// + /// Тип компонента, который должен быть привязан к игровому объекту. + /// Ключ, определяющий тип объекта в пуле. + /// Дополнительные параметры для передачи в конструктор объекта. + /// Созданный компонент типа . + public TComponent Instantiate(TKey key, params object[] additionalContext) + where TComponent : IPooledObject + => Instantiate(key, additionalContext).GetComponent(); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/KeyPoolContainer.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/KeyPoolContainer.cs.meta new file mode 100644 index 0000000..8b78575 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/KeyPoolContainer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 8bb59dc33ef04010998f28d06113dad5 +timeCreated: 1730467848 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/Rules.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/Rules.meta new file mode 100644 index 0000000..072f4fb --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/Rules.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7d92f6a65a4246c18c0d1c424890a319 +timeCreated: 1730468079 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/Rules/IKeyRuleGameObjectSelector.cs b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/Rules/IKeyRuleGameObjectSelector.cs new file mode 100644 index 0000000..98d697d --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/Rules/IKeyRuleGameObjectSelector.cs @@ -0,0 +1,19 @@ +using UnityEngine; + +namespace RedCatEngine.Pools.Containers.KeyContainers.Rules +{ + /// + /// Интерфейс, определяющий правило выбора игрового объекта для пула на основе ключа. + /// Реализации этого интерфейса используются для создания шаблонных объектов (префабов) в пуле, + /// соответствующих конкретному типу или конфигурации. + /// + public interface IKeyRuleGameObjectSelector + { + /// + /// Возвращает префаб (или игровой объект), который будет использоваться как основа + /// при создании экземпляров в пуле. + /// + /// Префаб игрового объекта. + GameObject GetGameObjectForPool(); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/Rules/IKeyRuleGameObjectSelector.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/Rules/IKeyRuleGameObjectSelector.cs.meta new file mode 100644 index 0000000..d80c215 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/KeyContainers/Rules/IKeyRuleGameObjectSelector.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 5b2136b2460e46c0a9e7dabc72ae6aed +timeCreated: 1730468104 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/SimpleContainers.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/SimpleContainers.meta new file mode 100644 index 0000000..edddb40 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/SimpleContainers.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 250b924d1a2b4cd2b27219a0a078f66e +timeCreated: 1730467603 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/SimpleContainers/PoolComponentsContainer.cs b/RedCatEngineUnityProject/Packages/Pools/Containers/SimpleContainers/PoolComponentsContainer.cs new file mode 100644 index 0000000..c0267a3 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/SimpleContainers/PoolComponentsContainer.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RedCatEngine.Pools.Containers.Creators.InstanceCreator; +using RedCatEngine.Pools.Containers.Enumerators; +using RedCatEngine.Pools.Pools; +using UnityEngine; + +namespace RedCatEngine.Pools.Containers.SimpleContainers +{ + public class PoolComponentsContainer + : PoolObjectsContainer, + IPoolComponentsContainer + where TComponent : IPooledObject + { + public PoolComponentsContainer(IInstanceCreator creator) + : base(creator) + { + } + + public TComponent this[int currentSelectIndex] + => CreatedPooledObjects[currentSelectIndex].GameObject.GetComponent(); + + public new IEnumerator GetEnumerator() + { + return new PooledObjectTypedEnumerator( + CreatedPooledObjects.Select(pooledObject => pooledObject.GameObject.GetComponent()) + ); + } + + public TComponent InstantiateComponent(params object[] context) + { + var instantiate = Instantiate(context); + return instantiate.GetComponent(); + } + + public TComponent InstantiateComponent(Vector3 position, params object[] context) + { + var instantiate = Instantiate(position, context); + return instantiate.GetComponent(); + } + + public TComponent InstantiateComponentAsLastSibling(params object[] context) + { + var instantiate = InstantiateAsLastSibling(context); + return instantiate.GetComponent(); + } + + public void KillAll(Action callbackBeforeKill) + { + base.KillAll(go => + { + if (go.TryGetComponent(out var component)) + callbackBeforeKill?.Invoke(component); + } + ); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/SimpleContainers/PoolComponentsContainer.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/SimpleContainers/PoolComponentsContainer.cs.meta new file mode 100644 index 0000000..cab33a2 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/SimpleContainers/PoolComponentsContainer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: dca820e5cbfdf9f4cbb57a8602f4749f +timeCreated: 1726236527 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/SimpleContainers/PoolObjectsContainer.cs b/RedCatEngineUnityProject/Packages/Pools/Containers/SimpleContainers/PoolObjectsContainer.cs new file mode 100644 index 0000000..7b6b959 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/SimpleContainers/PoolObjectsContainer.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using JetBrains.Annotations; +using RedCatEngine.Pools.Containers.Creators.InstanceCreator; +using RedCatEngine.Pools.Containers.Enumerators; +using RedCatEngine.Pools.Pools; +using UnityEngine; + +namespace RedCatEngine.Pools.Containers.SimpleContainers +{ + public class PoolObjectsContainer : IPoolObjectsContainer, IEnumerable + { + private readonly IInstanceCreator _creator; + private readonly Stack _inactiveStack = new(); + protected readonly List CreatedPooledObjects = new(); + private Action _callbackBeforeKill; + private Action _callbackAfterEnable; + + public int Length + => CreatedPooledObjects.Count; + + public PoolObjectsContainer( + IInstanceCreator creator + ) + { + _creator = creator; + } + + public virtual IEnumerator GetEnumerator() + => new GameObjectsEnumerator(CreatedPooledObjects.Select(pool => pool.GameObject)); + + private void OnDead(IPooledObject pooledObject) + { + _callbackBeforeKill?.Invoke(pooledObject.GameObject); + + if (CreatedPooledObjects.Contains(pooledObject)) + CreatedPooledObjects.Remove(pooledObject); + + pooledObject.DeadEvent -= OnDead; + _inactiveStack.Push(pooledObject); + } + + public void SetAfterEnableCallback(Action callbackAfterEnable) + { + _callbackAfterEnable = callbackAfterEnable; + } + + public void KillAll([CanBeNull] Action callbackBeforeKill = null) + { + var countCreatedObjects = CreatedPooledObjects.Count; + var countRemove = 0; + while (countCreatedObjects > countRemove + && CreatedPooledObjects.Count > 0) + { + var createdObjectForRemove = CreatedPooledObjects[0]; + callbackBeforeKill?.Invoke(createdObjectForRemove.GameObject); + createdObjectForRemove.Disable(); + countRemove++; + } + } + + public void SetBeforeDisableCallback(Action callbackBeforeDisable) + { + _callbackBeforeKill = callbackBeforeDisable; + } + + public GameObject InstantiateAsLastSibling(params object[] context) + { + var instance = Instantiate(context); + instance.transform.SetAsLastSibling(); + return instance; + } + + public GameObject Instantiate(params object[] context) + { + IPooledObject pooledComponent; + if (_inactiveStack.Count > 0) + { + pooledComponent = _inactiveStack.Pop(); + pooledComponent.Reset(); + } + else + { + pooledComponent = _creator.Create(context); + } + + pooledComponent.DeadEvent += OnDead; + pooledComponent.Enable(); + + if (!CreatedPooledObjects.Contains(pooledComponent)) + CreatedPooledObjects.Add(pooledComponent); + + _callbackAfterEnable?.Invoke(pooledComponent.GameObject); + return pooledComponent.GameObject; + } + + public GameObject Instantiate( + Vector3 position, + params object[] context + ) + { + return Instantiate(position, Quaternion.identity, context); + } + + public GameObject Instantiate( + Vector3 position, + Quaternion rotation, + params object[] context + ) + { + var instance = Instantiate(context); + var pooledObject = instance.GetComponent(); + pooledObject.TeleportTo(position, rotation); + return instance; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Containers/SimpleContainers/PoolObjectsContainer.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Containers/SimpleContainers/PoolObjectsContainer.cs.meta new file mode 100644 index 0000000..e095c40 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Containers/SimpleContainers/PoolObjectsContainer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b7dc6c7e365479648816ee43eeb926f8 +timeCreated: 1726235060 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Objects.meta b/RedCatEngineUnityProject/Packages/Pools/Objects.meta new file mode 100644 index 0000000..2653e2a --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Objects.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4c47e4e6c3ba4658b93726d089b47977 +timeCreated: 1726235041 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Objects/Enumerators.meta b/RedCatEngineUnityProject/Packages/Pools/Objects/Enumerators.meta new file mode 100644 index 0000000..ccbaba3 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Objects/Enumerators.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 74cd1ade253a462abdf98e15ae97aa19 +timeCreated: 1728468067 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Objects/Enumerators/GameObjectsEnumerator.cs b/RedCatEngineUnityProject/Packages/Pools/Objects/Enumerators/GameObjectsEnumerator.cs new file mode 100644 index 0000000..895af1e --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Objects/Enumerators/GameObjectsEnumerator.cs @@ -0,0 +1,12 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace RedCatEngine.Pools.Objects.Enumerators +{ + public class GameObjectsEnumerator : PooledObjectTypedEnumerator + { + public GameObjectsEnumerator(IEnumerable collection) : base(collection) + { + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Objects/Enumerators/GameObjectsEnumerator.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Objects/Enumerators/GameObjectsEnumerator.cs.meta new file mode 100644 index 0000000..f1b1a40 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Objects/Enumerators/GameObjectsEnumerator.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d4a075feabd64ce0b60963c1c62a0d58 +timeCreated: 1728468084 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Objects/Enumerators/PooledObjectTypedEnumerator.cs b/RedCatEngineUnityProject/Packages/Pools/Objects/Enumerators/PooledObjectTypedEnumerator.cs new file mode 100644 index 0000000..be94833 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Objects/Enumerators/PooledObjectTypedEnumerator.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace RedCatEngine.Pools.Objects +{ + public class PooledObjectTypedEnumerator : IEnumerator + { + private readonly TReturnEnumeratorType[] _collection; + private int _index = -1; + + public PooledObjectTypedEnumerator(IEnumerable collection) + { + _collection = collection.ToArray(); + } + + private TReturnEnumeratorType TypedCurrent + { + get + { + try + { + return _collection[_index]; + } + catch (IndexOutOfRangeException) + { + throw new InvalidOperationException(); + } + } + } + + TReturnEnumeratorType IEnumerator.Current + => TypedCurrent; + + public object Current + => TypedCurrent; + + public bool MoveNext() + { + _index++; + return _index < _collection.Length; + } + + public void Reset() + { + _index = -1; + } + + public void Dispose() + { + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Objects/Enumerators/PooledObjectTypedEnumerator.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Objects/Enumerators/PooledObjectTypedEnumerator.cs.meta new file mode 100644 index 0000000..40fd2a6 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Objects/Enumerators/PooledObjectTypedEnumerator.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d8b9740f187245a1b166279ce7b5f197 +timeCreated: 1728467568 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Objects/IObjectsPool.cs b/RedCatEngineUnityProject/Packages/Pools/Objects/IObjectsPool.cs new file mode 100644 index 0000000..6657540 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Objects/IObjectsPool.cs @@ -0,0 +1,15 @@ +using System; +using RedCatEngine.Pools.Pools; +using UnityEngine; + +namespace RedCatEngine.Pools.Objects +{ + public interface IObjectsPool + { + GameObject Instantiate(out TComponent component) + where TComponent : IPooledObject; + + void OnDead(IPooledObject pooledObject); + void KillAll(Action callbackBeforeKill); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Objects/IObjectsPool.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Objects/IObjectsPool.cs.meta new file mode 100644 index 0000000..59d877f --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Objects/IObjectsPool.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: deb5f81fbb9e48f893d3f01a475d8b37 +timeCreated: 1726234846 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Objects/ObjectComponentPull.cs b/RedCatEngineUnityProject/Packages/Pools/Objects/ObjectComponentPull.cs new file mode 100644 index 0000000..2cb83b6 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Objects/ObjectComponentPull.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using RedCatEngine.Pools.Pools; +using UnityEngine; + +namespace RedCatEngine.Pools.Objects +{ + public class ObjectComponentPull : ObjectsPool, IEnumerable where TComponent : IPooledObject + { + public ObjectComponentPull(GameObject prefab, Transform parentTransform) + : base(prefab, parentTransform) + { + } + + public TComponent this[int currentSelectIndex] + => CreatedPooledObjects[currentSelectIndex].GameObject.GetComponent(); + + public new IEnumerator GetEnumerator() + { + return new PooledObjectTypedEnumerator( + CreatedPooledObjects.Select(pooledObject => pooledObject.GameObject.GetComponent())); + } + + public TComponent InstantiateComponent() + { + Instantiate(out var component); + return component; + } + + public TComponent InstantiateComponentAsLastSibling() + { + InstantiateComponentAsLastSibling(out var component); + return component; + } + + public void KillAll(Action callbackBeforeKill) + { + base.KillAll( + go => + { + if (go.TryGetComponent(out var component)) + callbackBeforeKill?.Invoke(component); + }); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Objects/ObjectComponentPull.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Objects/ObjectComponentPull.cs.meta new file mode 100644 index 0000000..655d1d6 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Objects/ObjectComponentPull.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c80e5213791b452f86a9e85c5503fca5 +timeCreated: 1726236527 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Objects/ObjectsPool.cs b/RedCatEngineUnityProject/Packages/Pools/Objects/ObjectsPool.cs new file mode 100644 index 0000000..9d5b94b --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Objects/ObjectsPool.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using RedCatEngine.Pools.Objects.Enumerators; +using RedCatEngine.Pools.Pools; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace RedCatEngine.Pools.Objects +{ + public class ObjectsPool : IObjectsPool, IEnumerable + { + private readonly Stack _inactiveStack = new(); + private readonly Transform _parentTransform; + private readonly GameObject _prefab; + protected readonly List CreatedPooledObjects = new(); + + public ObjectsPool(GameObject prefab, Transform parentTransform) + { + _prefab = prefab; + _parentTransform = parentTransform; + if (!_prefab.TryGetComponent(out _)) + throw new Exception("Object not contain pooled component"); + } + + public int Length + => CreatedPooledObjects.Count; + + public virtual IEnumerator GetEnumerator() + => new GameObjectsEnumerator(CreatedPooledObjects.Select(pool => pool.GameObject)); + + public GameObject Instantiate(out TComponent component) + where TComponent : IPooledObject + { + GameObject instance; + if (_inactiveStack.Count > 0) + { + instance = _inactiveStack.Pop(); + component = instance.GetComponent(); + component.Reset(); + } + else + { + instance = Object.Instantiate(_prefab, _parentTransform); + component = instance.GetComponent(); + } + + component.DeadEvent += OnDead; + component.Enable(); + + if (!CreatedPooledObjects.Contains(component)) + CreatedPooledObjects.Add(component); + + return instance; + } + + public void OnDead(IPooledObject pooledObject) + { + if (CreatedPooledObjects.Contains(pooledObject)) + CreatedPooledObjects.Remove(pooledObject); + + pooledObject.DeadEvent -= OnDead; + _inactiveStack.Push(pooledObject.GameObject); + } + + public void KillAll(Action callbackBeforeKill = null) + { + var countCreatedObjects = CreatedPooledObjects.Count; + var countRemove = 0; + while (countCreatedObjects > countRemove && CreatedPooledObjects.Count > 0) + { + var createdObjectForRemove = CreatedPooledObjects[0]; + callbackBeforeKill?.Invoke(createdObjectForRemove.GameObject); + createdObjectForRemove.Disable(); + countRemove++; + } + } + + public GameObject InstantiateComponentAsLastSibling(out TComponent component) + where TComponent : IPooledObject + { + GameObject instance = Instantiate(out component); + instance.transform.SetAsLastSibling(); + return instance; + } + + public GameObject Instantiate( + Vector3 position, + Quaternion rotation, + out TComponent component + ) + where TComponent : IPooledObject + { + var instance = Instantiate(out component); + instance.transform.position = position; + instance.transform.rotation = rotation; + return instance; + } + + public GameObject Instantiate( + Vector3 position, + Quaternion rotation, + out IPooledObject component + ) + { + return Instantiate( + position, + rotation, + out component); + } + + public GameObject Instantiate( + Vector2 position, + Quaternion rotation, + out TComponent component + ) + where TComponent : IPooledObject + { + var instance = Instantiate(out component); + instance.transform.position = position; + instance.transform.rotation = rotation; + return instance; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Objects/ObjectsPool.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Objects/ObjectsPool.cs.meta new file mode 100644 index 0000000..ea338c7 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Objects/ObjectsPool.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 59b4b137f68f4aa69b8033466b09a525 +timeCreated: 1726235060 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/PoolExtensions.cs b/RedCatEngineUnityProject/Packages/Pools/PoolExtensions.cs new file mode 100644 index 0000000..5dcd973 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/PoolExtensions.cs @@ -0,0 +1,15 @@ +using RedCatEngine.Pools.Pools; + +namespace RedCatEngine.Pools +{ + public static class PoolExtensions + { + public static void SetActive(this IPooledObject pooledObject, bool state) + { + if (state) + pooledObject.Enable(); + else + pooledObject.Disable(); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/PoolExtensions.cs.meta b/RedCatEngineUnityProject/Packages/Pools/PoolExtensions.cs.meta new file mode 100644 index 0000000..1f76c95 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/PoolExtensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: bf5a2476e7e14fb5b56e6c241b7d5e32 +timeCreated: 1726234928 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools.asmdef b/RedCatEngineUnityProject/Packages/Pools/Pools.asmdef new file mode 100644 index 0000000..f6ce254 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools.asmdef @@ -0,0 +1,14 @@ +{ + "name": "Pools", + "rootNamespace": "RedCatEngine.Pools", + "references": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools.asmdef.meta b/RedCatEngineUnityProject/Packages/Pools/Pools.asmdef.meta new file mode 100644 index 0000000..0683f87 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: f8db481d96857fd478a6ffb797500869 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools.meta b/RedCatEngineUnityProject/Packages/Pools/Pools.meta new file mode 100644 index 0000000..b9c9d70 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ae1498a979e949a19d4ad81cea71a43f +timeCreated: 1726235024 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/BasePooledObject.cs b/RedCatEngineUnityProject/Packages/Pools/Pools/BasePooledObject.cs new file mode 100644 index 0000000..550282b --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/BasePooledObject.cs @@ -0,0 +1,64 @@ +using System; +using UnityEngine; + +namespace RedCatEngine.Pools.Pools +{ + public abstract class BasePooledObject : MonoBehaviour, IPooledObject + { + public event Action DeadEvent; + + public GameObject GameObject + => gameObject; + + public void Enable() + { + DoEnable(); + gameObject.SetActive(true); + } + + public void Disable() + { + DoDisable(); + if (this == null || gameObject == null) + return; + gameObject.SetActive(false); + DeadEvent?.Invoke(this); + } + + public void Reset() + => DoReset(); + + public void TeleportTo(Vector3 position, Quaternion rotation) + { + DoDisableLogicBeforeTeleport(); + DoTeleportTo(position, rotation); + DoEnableLogicAfterTeleport(); + } + + protected virtual void DoTeleportTo(Vector3 position, Quaternion rotation) + { + transform.position = position; + transform.rotation = rotation; + } + + protected virtual void DoEnable() + { + } + + protected virtual void DoDisable() + { + } + + protected virtual void DoReset() + { + } + + protected virtual void DoDisableLogicBeforeTeleport() + { + } + + protected virtual void DoEnableLogicAfterTeleport() + { + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/BasePooledObject.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Pools/BasePooledObject.cs.meta new file mode 100644 index 0000000..0514e39 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/BasePooledObject.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 88f048e66d911b347940718c29753cac +timeCreated: 1726235782 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/CollectorComponentsPoolObject.cs b/RedCatEngineUnityProject/Packages/Pools/Pools/CollectorComponentsPoolObject.cs new file mode 100644 index 0000000..b624418 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/CollectorComponentsPoolObject.cs @@ -0,0 +1,85 @@ +using System; +using RedCatEngine.Pools.Pools.Interfaces; +using UnityEngine; + +namespace RedCatEngine.Pools.Pools +{ + public class CollectorComponentsPoolObject : MonoBehaviour, IPooledObject + { + public event Action DeadEvent; + + private IPooledEnable[] _enabledComponents = Array.Empty(); + private IPooledDisable[] _disabledComponents = Array.Empty(); + private IPooledReset[] _resetsComponents = Array.Empty(); + private IPooledTeleportedLogic[] _teleportedLogicComponents = Array.Empty(); + private IPooledCustomTeleported _customTeleported; + + public GameObject GameObject + => gameObject; + + public void Enable() + { + _enabledComponents.Enable(); + gameObject.SetActive(true); + } + + public void Disable() + { + _disabledComponents.Disable(); + gameObject.SetActive(false); + DeadEvent?.Invoke(this); + } + + public void Reset() + { + _resetsComponents.Reset(); + } + + public void TeleportTo(Vector3 position, Quaternion rotation) + { + _teleportedLogicComponents.DisableLogicBeforeTeleport(); + if (_customTeleported != null) + { + _customTeleported.TeleportTo(position, rotation); + } + else + { + transform.position = position; + transform.rotation = rotation; + } + + _teleportedLogicComponents.EnableLogicAfterTeleport(); + } + + public void CollectPooledComponents() + { + _enabledComponents = GetComponentsInChildren(); + _disabledComponents = GetComponentsInChildren(); + _resetsComponents = GetComponentsInChildren(); + _teleportedLogicComponents = GetComponentsInChildren(); + _customTeleported = GetComponent(); + } + +#if UNITY_EDITOR + private void OnValidate() + { + var enabledComponents = GetComponents(); + var disabledComponents = GetComponents(); + var resetsComponents = GetComponents(); + var teleportedLogicComponents = GetComponents(); + var customTeleported = GetComponent(); + + if (!enabledComponents.GetHashCode().Equals(_enabledComponents.GetHashCode())) + _enabledComponents = enabledComponents; + if (!disabledComponents.GetHashCode().Equals(_disabledComponents.GetHashCode())) + _disabledComponents = disabledComponents; + if (!resetsComponents.GetHashCode().Equals(_resetsComponents.GetHashCode())) + _resetsComponents = resetsComponents; + if (!teleportedLogicComponents.GetHashCode().Equals(_teleportedLogicComponents.GetHashCode())) + _teleportedLogicComponents = teleportedLogicComponents; + if (!Equals(_customTeleported, customTeleported)) + _customTeleported = customTeleported; + } +#endif + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/CollectorComponentsPoolObject.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Pools/CollectorComponentsPoolObject.cs.meta new file mode 100644 index 0000000..b82f5c5 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/CollectorComponentsPoolObject.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 799fd8f89ece4cf3bc492028143283b8 +timeCreated: 1731058035 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/IPooledObject.cs b/RedCatEngineUnityProject/Packages/Pools/Pools/IPooledObject.cs new file mode 100644 index 0000000..4ee3b6b --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/IPooledObject.cs @@ -0,0 +1,15 @@ +using System; +using UnityEngine; + +namespace RedCatEngine.Pools.Pools +{ + public interface IPooledObject + { + event Action DeadEvent; + GameObject GameObject { get; } + void Enable(); + void Disable(); + void Reset(); + void TeleportTo(Vector3 position, Quaternion rotation); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/IPooledObject.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Pools/IPooledObject.cs.meta new file mode 100644 index 0000000..0cc7ffc --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/IPooledObject.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 69cf42182d3770246a937368e4c90d0a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces.meta b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces.meta new file mode 100644 index 0000000..8733811 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 17b50ce9aa2c455a9ccf00f581cc2150 +timeCreated: 1731052328 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/ArrayOfPooledInterfacesExtensions.cs b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/ArrayOfPooledInterfacesExtensions.cs new file mode 100644 index 0000000..62cc310 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/ArrayOfPooledInterfacesExtensions.cs @@ -0,0 +1,35 @@ +namespace RedCatEngine.Pools.Pools.Interfaces +{ + public static class ArrayOfPooledInterfacesExtensions + { + public static void Enable(this IPooledEnable[] enables) + { + foreach (var enable in enables) + enable.DoEnable(); + } + + public static void Disable(this IPooledDisable[] disables) + { + foreach (var disabled in disables) + disabled.DoDisable(); + } + + public static void Reset(this IPooledReset[] resets) + { + foreach (var reset in resets) + reset.Reset(); + } + + public static void DisableLogicBeforeTeleport(this IPooledTeleportedLogic[] teleportedArray) + { + foreach (var teleported in teleportedArray) + teleported.DisableLogicBeforeTeleport(); + } + + public static void EnableLogicAfterTeleport(this IPooledTeleportedLogic[] teleportedArray) + { + foreach (var teleported in teleportedArray) + teleported.EnableLogicAfterTeleport(); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/ArrayOfPooledInterfacesExtensions.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/ArrayOfPooledInterfacesExtensions.cs.meta new file mode 100644 index 0000000..1da4188 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/ArrayOfPooledInterfacesExtensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d86e6af406894f4c82b5e85595829160 +timeCreated: 1731057540 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledCustomTeleported.cs b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledCustomTeleported.cs new file mode 100644 index 0000000..008e399 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledCustomTeleported.cs @@ -0,0 +1,9 @@ +using UnityEngine; + +namespace RedCatEngine.Pools.Pools.Interfaces +{ + public interface IPooledCustomTeleported : IPooledTeleportedLogic + { + void TeleportTo(Vector3 position, Quaternion rotation); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledCustomTeleported.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledCustomTeleported.cs.meta new file mode 100644 index 0000000..c9a28ff --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledCustomTeleported.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3e437c9265de468298b4ce75777706c7 +timeCreated: 1731057772 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledDisable.cs b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledDisable.cs new file mode 100644 index 0000000..baaa70a --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledDisable.cs @@ -0,0 +1,7 @@ +namespace RedCatEngine.Pools.Pools.Interfaces +{ + public interface IPooledDisable + { + void DoDisable(); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledDisable.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledDisable.cs.meta new file mode 100644 index 0000000..5370259 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledDisable.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 56764ac139a7403a85430c8a67756f38 +timeCreated: 1731052355 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledEnable.cs b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledEnable.cs new file mode 100644 index 0000000..f5e7b9d --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledEnable.cs @@ -0,0 +1,7 @@ +namespace RedCatEngine.Pools.Pools.Interfaces +{ + public interface IPooledEnable + { + void DoEnable(); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledEnable.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledEnable.cs.meta new file mode 100644 index 0000000..60ca32f --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledEnable.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7d155914daf046c69901a717a438ee27 +timeCreated: 1731052348 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledReset.cs b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledReset.cs new file mode 100644 index 0000000..bfb40a7 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledReset.cs @@ -0,0 +1,7 @@ +namespace RedCatEngine.Pools.Pools.Interfaces +{ + public interface IPooledReset + { + void Reset(); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledReset.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledReset.cs.meta new file mode 100644 index 0000000..0bd30f1 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledReset.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3369d68cca6f40bf912c84fac9afe34c +timeCreated: 1731057483 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledTeleportedLogic.cs b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledTeleportedLogic.cs new file mode 100644 index 0000000..e1ceb0f --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledTeleportedLogic.cs @@ -0,0 +1,8 @@ +namespace RedCatEngine.Pools.Pools.Interfaces +{ + public interface IPooledTeleportedLogic + { + void DisableLogicBeforeTeleport(); + void EnableLogicAfterTeleport(); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledTeleportedLogic.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledTeleportedLogic.cs.meta new file mode 100644 index 0000000..34d79a0 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Pools/Interfaces/IPooledTeleportedLogic.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 91923600f9dd4e44b77ccc8868ef5da7 +timeCreated: 1731057454 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Serializable.meta b/RedCatEngineUnityProject/Packages/Pools/Serializable.meta new file mode 100644 index 0000000..e11f573 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Serializable.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d6489d549ed4427a9d3b383cdc6991d3 +timeCreated: 1728646885 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Serializable/UnityComponentPoolSerializable.cs b/RedCatEngineUnityProject/Packages/Pools/Serializable/UnityComponentPoolSerializable.cs new file mode 100644 index 0000000..f05a201 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Serializable/UnityComponentPoolSerializable.cs @@ -0,0 +1,93 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using RedCatEngine.Pools.Containers; +using RedCatEngine.Pools.Containers.Creators.InstanceCreator; +using RedCatEngine.Pools.Containers.SimpleContainers; +using RedCatEngine.Pools.Pools; +using UnityEngine; + +namespace RedCatEngine.Pools.Serializable +{ + /// + /// Обёртка над пулом объектов в Unity, позволяющая управлять созданием и хранением экземпляров, + /// реализующих интерфейс . + /// + /// Тип объекта, который должен реализовывать интерфейс . + [Serializable] + public class UnityComponentPoolSerializable : IPoolObjectsContainer, IPoolComponentsContainer + where TComponent : IPooledObject + { + /// + /// Префаб из которого создаются объекты в пул. + /// + [SerializeField] private GameObject _prefab; + + /// + /// Родительский объект, к которому будут привязаны созданные объекты. + /// + [SerializeField] private Transform _parent; + + /// + /// Получает родительский объект для позиционирования инстансов. + /// + public Transform Parent => _parent; + + /// + /// Контейнер пула, в котором хранятся и управляются объекты типа . + /// + private IPoolComponentsContainer _hiddenPool; + + /// + /// Получает контейнер пула. При первом обращении инициализирует его, используя указанный префаб и родителя. + /// + private IPoolComponentsContainer SafeContainer => + _hiddenPool ??= new PoolComponentsContainer( + new SimpleUnityInstanceCreator(_prefab, _parent) + ); + + public int Length + => SafeContainer.Length; + + public void SetBeforeDisableCallback(Action callbackBeforeDisable) => + SafeContainer.SetBeforeDisableCallback(callbackBeforeDisable); + + public GameObject InstantiateAsLastSibling(params object[] context) + => SafeContainer.InstantiateAsLastSibling(context); + + public void SetAfterEnableCallback(Action callbackAfterEnable) => + SafeContainer.SetAfterEnableCallback(callbackAfterEnable); + + public TComponent this[int currentSelectIndex] + => SafeContainer[currentSelectIndex]; + + public IEnumerator GetEnumerator() + => SafeContainer.GetEnumerator(); + + public TComponent InstantiateComponent(params object[] context) + => SafeContainer.InstantiateComponent(context); + + public TComponent InstantiateComponent(Vector3 position, params object[] context) => + SafeContainer.InstantiateComponent(position, context); + + public TComponent InstantiateComponentAsLastSibling(params object[] context) + => SafeContainer.InstantiateComponentAsLastSibling(context); + + public void KillAll(Action callbackBeforeKill) + => SafeContainer.KillAll(callbackBeforeKill); + + public void KillAll(Action callbackBeforeKill = null) + => SafeContainer.KillAll(callbackBeforeKill); + + public GameObject Instantiate(params object[] context) + => SafeContainer.Instantiate(context); + + public GameObject Instantiate(Vector3 position, params object[] context) => + SafeContainer.Instantiate(position, context); + + public GameObject Instantiate(Vector3 position, Quaternion rotation, params object[] context) => + SafeContainer.Instantiate(position, rotation, context); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Serializable/UnityComponentPoolSerializable.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Serializable/UnityComponentPoolSerializable.cs.meta new file mode 100644 index 0000000..6dbbb9c --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Serializable/UnityComponentPoolSerializable.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 29f5518b9d013784eb62d239e41629cb +timeCreated: 1728646906 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Serializable/UnityKeyComponentsPoolSerializable.cs b/RedCatEngineUnityProject/Packages/Pools/Serializable/UnityKeyComponentsPoolSerializable.cs new file mode 100644 index 0000000..dad5f90 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Serializable/UnityKeyComponentsPoolSerializable.cs @@ -0,0 +1,64 @@ +using System; +using RedCatEngine.Pools.Containers.Creators.Factories; +using RedCatEngine.Pools.Containers.KeyContainers; +using RedCatEngine.Pools.Containers.KeyContainers.Rules; +using RedCatEngine.Pools.Pools; +using UnityEngine; + +namespace RedCatEngine.Pools.Serializable +{ + [Serializable] + public class UnityKeyComponentsPoolSerializable : IKeyPoolComponentsContainer + where TKey : IKeyRuleGameObjectSelector + where TComponent : IPooledObject + { + [SerializeField] private Transform _parentTransform; + + private IKeyPoolComponentsContainer _hiddenPoolContainer; + + private IKeyPoolComponentsContainer Container + => _hiddenPoolContainer ??= new KeyPoolComponentsContainer( + new SimpleUnityPoolInstanceCreatorFactory(), + _parentTransform + ); + + public void SetBeforeDisableCallback(Action callbackBeforeDisable) => + Container.SetBeforeDisableCallback(callbackBeforeDisable); + + public void SetAfterEnableCallback(Action callbackAfterEnable) => + Container.SetAfterEnableCallback(callbackAfterEnable); + + public void KillAll(Action callbackBeforeKill = null) + => Container.KillAll(callbackBeforeKill); + + public GameObject Instantiate(TKey key, params object[] additionalContext) => + Container.Instantiate(key, additionalContext); + + public GameObject Instantiate( + TKey key, + Vector3 transformPosition, + Quaternion transformRotation, + params object[] additionalContext + ) + { + return Container.Instantiate( + key, + transformPosition, + transformRotation, + additionalContext + ); + } + + public TInstanceComponent Instantiate(TKey key, params object[] additionalContext) + where TInstanceComponent : IPooledObject + { + return Container.Instantiate(key, additionalContext); + } + + public TComponent InstantiateComponent(TKey key, params object[] context) => + Container.InstantiateComponent(key, context); + + public void KillAll(Action callbackBeforeKill) + => Container.KillAll(callbackBeforeKill); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/Serializable/UnityKeyComponentsPoolSerializable.cs.meta b/RedCatEngineUnityProject/Packages/Pools/Serializable/UnityKeyComponentsPoolSerializable.cs.meta new file mode 100644 index 0000000..48b0136 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/Serializable/UnityKeyComponentsPoolSerializable.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 1c5b82529c4542a3aa09c672f16eb5c2 +timeCreated: 1753793175 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/package.json b/RedCatEngineUnityProject/Packages/Pools/package.json new file mode 100644 index 0000000..3e68ca4 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/package.json @@ -0,0 +1,11 @@ +{ + "name": "com.boronnikov.games.red-cat-engine.pools", + "version": "1.0.1", + "displayName": "Red Cat Engine: Pools", + "description": "Simple pool system", + "unity": "2021.3", + "author": { + "name": "Boronnikov Games", + "url": "https://github.com/Red-Cat-Fat" + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Pools/package.json.meta b/RedCatEngineUnityProject/Packages/Pools/package.json.meta new file mode 100644 index 0000000..dba5aac --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Pools/package.json.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9349f9e0ee1d2e5408c7e89f73da203c +timeCreated: 1713125223 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Configs/QuestCollections/SimpleQuestCollectionConfig.cs b/RedCatEngineUnityProject/Packages/Quests/Configs/QuestCollections/SimpleQuestCollectionConfig.cs index 941a0f4..0d6b013 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Configs/QuestCollections/SimpleQuestCollectionConfig.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Configs/QuestCollections/SimpleQuestCollectionConfig.cs @@ -7,7 +7,7 @@ namespace RedCatEngine.Quests.Configs.QuestCollections { [CreateAssetMenu( - menuName = "Configs/Quests/QuestCollection/QuestCollectionConfig", + menuName = "Configs/Quests/Quest Groups/QuestCollectionConfig", fileName = nameof(SimpleQuestCollectionConfig))] public class SimpleQuestCollectionConfig : BaseConfig, IQuestCollection { diff --git a/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/AllQuestLinksConfig.cs b/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/AllQuestLinksConfig.cs new file mode 100644 index 0000000..611ebf7 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/AllQuestLinksConfig.cs @@ -0,0 +1,40 @@ +using System.Collections.Generic; +using RedCatEngine.Configs; +using UnityEditor; +using UnityEngine; + +namespace RedCatEngine.Quests.Configs.Quests +{ + [CreateAssetMenu( + fileName = nameof(AllQuestLinksConfig), + menuName = "Configs/Quests/Quest Systems/AllQuestCollection", + order = 0)] + public class AllQuestLinksConfig : BaseConfig + { + public List Quests = new(); + +#if UNITY_EDITOR + protected override void DoValidate() + { + var quests = new List(); + var guids = AssetDatabase.FindAssets("t:" + nameof(QuestConfig)); + for (var i = 0; i < guids.Length; i++) + { + var assetPath = AssetDatabase.GUIDToAssetPath(guids[i]); + var asset = AssetDatabase.LoadAssetAtPath(assetPath); + if (asset != null) + { + quests.Add(asset); + } + } + + if (quests.Count == Quests.Count) + return; + Quests.Clear(); + Quests = quests; + EditorUtility.SetDirty(this); + AssetDatabase.SaveAssets(); + } +#endif + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/AllQuestLinksConfig.cs.meta b/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/AllQuestLinksConfig.cs.meta new file mode 100644 index 0000000..2c4da5f --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/AllQuestLinksConfig.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 6c41b140435a4bd68011e12bc7ffefe9 +timeCreated: 1735040821 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/ConditionalQuestConfig.cs b/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/ConditionalQuestConfig.cs index d593329..515c7f2 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/ConditionalQuestConfig.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/ConditionalQuestConfig.cs @@ -4,7 +4,6 @@ using RedCatEngine.Conditions; using RedCatEngine.Conditions.Base; using RedCatEngine.Conditions.Variants; -using RedCatEngine.DependencyInjection.Containers.Interfaces; using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; using RedCatEngine.Quests.Mechanics.Quests; using SerializeReferenceEditor; @@ -12,27 +11,21 @@ namespace RedCatEngine.Quests.Configs.Quests { - [CreateAssetMenu(menuName = "Configs/Quests/QuestCollection/ConditionalQuestConfig", fileName = nameof(ConditionalQuestConfig))] + [CreateAssetMenu( + menuName = "Configs/Quests/Quest Groups/ConditionalQuestConfig", + fileName = nameof(ConditionalQuestConfig))] public class ConditionalQuestConfig : QuestConfig, IQuestRedirected { public ConditionQuest[] Quests = Array.Empty(); - - [Serializable] - public class ConditionQuest - { - [SR] - [SerializeReference] - public ICondition Condition = ForceCondition.True; - public QuestConfig QuestConfig; - } + public IEnumerable GetAllQuestVariantForLoad() + => Quests.Select(conditionQuest => conditionQuest.QuestConfig); protected override IQuest DoMake(IApplicationContainer applicationContainer) { if (!applicationContainer.TryGetSingle(out var conditionCheckerService)) { - Debug.LogError("Not found ConditionCheckerService"); - conditionCheckerService = new ConditionCheckerService(applicationContainer); + throw new Exception("Not found ConditionCheckerService"); } foreach (var quest in Quests) @@ -44,7 +37,13 @@ protected override IQuest DoMake(IApplicationContainer applicationContainer) return null; } - public IEnumerable GetAllQuestVariantForLoad() - => Quests.Select(conditionQuest => conditionQuest.QuestConfig); + [Serializable] + public class ConditionQuest + { + [SR] + [SerializeReference] + public ICondition Condition = ForceCondition.True; + public QuestConfig QuestConfig; + } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/GroupQuestConfig.cs b/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/GroupQuestConfig.cs index f3cea08..97895f6 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/GroupQuestConfig.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/GroupQuestConfig.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using System.Linq; -using RedCatEngine.DependencyInjection.Containers.Interfaces; using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; using RedCatEngine.Quests.Mechanics.Quests; using UnityEngine; @@ -10,10 +9,11 @@ namespace RedCatEngine.Quests.Configs.Quests public abstract class GroupQuestConfig : QuestConfig, IQuestRedirected where TQuestType : QuestConfig { public TQuestType[] Quests; - protected override IQuest DoMake(IApplicationContainer applicationContainer) - => Quests.Length == 0 ? null : Quests[Random.Range(0, Quests.Length)].Make(applicationContainer); public IEnumerable GetAllQuestVariantForLoad() - => Quests.Select(quest=>(QuestConfig) quest); + => Quests.Select(quest => (QuestConfig)quest); + + protected override IQuest DoMake(IApplicationContainer applicationContainer) + => Quests.Length == 0 ? null : Quests[Random.Range(0, Quests.Length)].Make(applicationContainer); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/IQuestMaker.cs b/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/IQuestMaker.cs index b4ee042..48f026f 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/IQuestMaker.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/IQuestMaker.cs @@ -1,5 +1,4 @@ -using RedCatEngine.DependencyInjection.Containers.Interfaces; -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; using RedCatEngine.Quests.Mechanics.Quests; namespace RedCatEngine.Quests.Configs.Quests diff --git a/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/QuestConfig.cs b/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/QuestConfig.cs index e1a3e80..c60fca5 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/QuestConfig.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/QuestConfig.cs @@ -1,5 +1,4 @@ using RedCatEngine.Configs; -using RedCatEngine.DependencyInjection.Containers.Interfaces; using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; using RedCatEngine.Quests.Mechanics.Quests; using RedCatEngine.Quests.Mechanics.Quests.QuestDatas; @@ -8,7 +7,7 @@ namespace RedCatEngine.Quests.Configs.Quests { public abstract class QuestConfig : BaseConfig { - public IQuest Make(IApplicationContainer applicationContainer) + public IQuest Make(IApplicationContainer applicationContainer) => DoMake(applicationContainer); protected abstract IQuest DoMake(IApplicationContainer applicationContainer); diff --git a/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/RewardedQuestConfig.cs b/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/RewardedQuestConfig.cs deleted file mode 100644 index 2d1ff7f..0000000 --- a/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/RewardedQuestConfig.cs +++ /dev/null @@ -1,13 +0,0 @@ -using RedCatEngine.Rewards.Base; -using SerializeReferenceEditor; -using UnityEngine; - -namespace RedCatEngine.Quests.Configs.Quests -{ - public abstract class RewardedQuestConfig : QuestConfig - { - [SR] - [SerializeReference] - public IReward Reward; - } -} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/RewardedQuestConfig.cs.meta b/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/RewardedQuestConfig.cs.meta deleted file mode 100644 index 8454e80..0000000 --- a/RedCatEngineUnityProject/Packages/Quests/Configs/Quests/RewardedQuestConfig.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: cd21c8c295b34253b21be408e662fb4c -timeCreated: 1721316512 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Configs/Settings/AchievementQuestSystemConfig.cs b/RedCatEngineUnityProject/Packages/Quests/Configs/Settings/AchievementQuestSystemConfig.cs index bc378a0..6304f7c 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Configs/Settings/AchievementQuestSystemConfig.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Configs/Settings/AchievementQuestSystemConfig.cs @@ -1,6 +1,5 @@ using JetBrains.Annotations; using RedCatEngine.Configs; -using RedCatEngine.DependencyInjection.Containers.Interfaces; using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; using RedCatEngine.Quests.Configs.QuestCollections; using RedCatEngine.Quests.Mechanics.Factories; @@ -10,7 +9,10 @@ namespace RedCatEngine.Quests.Configs.Settings { - [CreateAssetMenu(menuName = "Configs/Quests/AchievementQuestSystemConfig", fileName = nameof(AchievementQuestSystemConfig))] + [CreateAssetMenu( + menuName = "Configs/Quests/Quest Systems/AchievementQuestSystemConfig", + fileName = nameof(AchievementQuestSystemConfig), + order = 1)] public class AchievementQuestSystemConfig : BaseConfig { public SimpleQuestCollectionConfig AchievementPack; diff --git a/RedCatEngineUnityProject/Packages/Quests/Configs/Settings/DailyQuestSystemConfig.cs b/RedCatEngineUnityProject/Packages/Quests/Configs/Settings/DailyQuestSystemConfig.cs index 8aa931d..7dc5091 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Configs/Settings/DailyQuestSystemConfig.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Configs/Settings/DailyQuestSystemConfig.cs @@ -1,5 +1,4 @@ using RedCatEngine.Configs; -using RedCatEngine.DependencyInjection.Containers.Interfaces; using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; using RedCatEngine.Quests.Configs.QuestCollections; using RedCatEngine.Quests.Mechanics.Factories; @@ -9,7 +8,10 @@ namespace RedCatEngine.Quests.Configs.Settings { - [CreateAssetMenu(menuName = "Configs/Quests/DailyQuestSystemConfig", fileName = nameof(DailyQuestSystemConfig))] + [CreateAssetMenu( + menuName = "Configs/Quests/Quest Systems/DailyQuestSystemConfig", + fileName = nameof(DailyQuestSystemConfig), + order = 2)] public class DailyQuestSystemConfig : BaseConfig { public SimpleQuestCollectionConfig DailySimpleQuestPack; diff --git a/RedCatEngineUnityProject/Packages/Quests/Exceptions/CantLoadFromDataException.cs b/RedCatEngineUnityProject/Packages/Quests/Exceptions/CantLoadFromDataException.cs index 2165515..c4f98a6 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Exceptions/CantLoadFromDataException.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Exceptions/CantLoadFromDataException.cs @@ -6,7 +6,14 @@ namespace RedCatEngine.Quests.Exceptions { public class CantLoadFromDataException : Exception { + public CantLoadFromDataException(IQuestData questData) + : base($"Cant load {questData} data") + { + } + public CantLoadFromDataException(IQuestData questData, IQuestSelector questSelector) - : base($"Cant load {questData} data from {questSelector.Name} selector") { } + : base($"Cant load {questData} data from {questSelector.Name} selector") + { + } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Exceptions/NotFoundQuestException.cs b/RedCatEngineUnityProject/Packages/Quests/Exceptions/NotFoundQuestException.cs index a3f3431..827911c 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Exceptions/NotFoundQuestException.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Exceptions/NotFoundQuestException.cs @@ -1,10 +1,22 @@ using System; +using RedCatEngine.Configs; +using RedCatEngine.Quests.Configs.Quests; using RedCatEngine.Quests.Mechanics.QuestGenerators; namespace RedCatEngine.Quests.Exceptions { public class NotFoundQuestException : Exception { + public NotFoundQuestException() + : base($"Not found quest.") + { + } + + public NotFoundQuestException(ConfigID questConfig) + : base($"In collection selector not found quest (id:{questConfig})") + { + } + public NotFoundQuestException(IQuestSelector randomQuestSelectorSelector) : base($"In {randomQuestSelectorSelector.Name} selector not found quest") { diff --git a/RedCatEngineUnityProject/Packages/Quests/Mechanics/Factories/CollectionSelectorQuestFactory.cs b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Factories/CollectionSelectorQuestFactory.cs index 79f98f2..96d85cd 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Mechanics/Factories/CollectionSelectorQuestFactory.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Factories/CollectionSelectorQuestFactory.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using RedCatEngine.Configs; -using RedCatEngine.DependencyInjection.Containers.Interfaces; using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; using RedCatEngine.Quests.Configs.Quests; using RedCatEngine.Quests.Exceptions; @@ -21,9 +20,9 @@ public CollectionSelectorQuestFactory(IApplicationContainer applicationContainer _randomQuestSelector = selector; } - public IQuest MakeFromConfig(ConfigID questConfig) + public IQuest MakeFromConfig(ConfigID questId) { - _randomQuestSelector.TryLoad(questConfig, out var quest); + _randomQuestSelector.TryLoad(questId, out var quest); return quest.Make(_applicationContainer); } diff --git a/RedCatEngineUnityProject/Packages/Quests/Mechanics/Factories/IQuestFactory.cs b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Factories/IQuestFactory.cs index bde0ef9..bd343ee 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Mechanics/Factories/IQuestFactory.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Factories/IQuestFactory.cs @@ -8,7 +8,7 @@ namespace RedCatEngine.Quests.Mechanics.Factories { public interface IQuestFactory { - IQuest MakeFromConfig(ConfigID questConfig); + IQuest MakeFromConfig(ConfigID questId); IQuest MakeNewQuest(List currentActiveQuests); IQuest LoadFrom(IQuestData saveData); bool TryLoad(ConfigID questId, out QuestConfig questConfig); diff --git a/RedCatEngineUnityProject/Packages/Quests/Mechanics/Factories/StoryQuestFactory.cs b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Factories/StoryQuestFactory.cs new file mode 100644 index 0000000..a8c7aa7 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Factories/StoryQuestFactory.cs @@ -0,0 +1,65 @@ +using System.Collections.Generic; +using System.Linq; +using RedCatEngine.Configs; +using RedCatEngine.DependencyInjection.Containers.Attributes; +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; +using RedCatEngine.Quests.Configs.Quests; +using RedCatEngine.Quests.Exceptions; +using RedCatEngine.Quests.Mechanics.Quests; +using RedCatEngine.Quests.Mechanics.Quests.QuestDatas; + +namespace RedCatEngine.Quests.Mechanics.Factories +{ + public class StoryQuestFactory : IQuestFactory + { + private readonly List _allQuests; + private readonly IApplicationContainer _applicationContainer; + + [Inject] + public StoryQuestFactory(IApplicationContainer applicationContainer, AllQuestLinksConfig allQuests) + { + _applicationContainer = applicationContainer; + _allQuests = allQuests.Quests; + } + + public IQuest MakeFromConfig(ConfigID questId) + { + if (!TryLoad(questId, out var quest)) + throw new NotFoundQuestException(questId); + return quest.Make(_applicationContainer); + } + + public IQuest MakeNewQuest(List currentActiveQuests) + { + foreach (var storyLineQuest in _allQuests) + { + if (currentActiveQuests.All(quest => quest.Config != storyLineQuest)) + { + return storyLineQuest.Make(_applicationContainer); + } + } + throw new NotFoundQuestException(); + } + + public IQuest LoadFrom(IQuestData saveData) + { + if (!TryLoad(saveData.GetConfig(), out var quest)) + throw new CantLoadFromDataException(saveData); + return quest.Make(_applicationContainer, saveData); + } + + public bool TryLoad(ConfigID questId, out QuestConfig questConfig) + { + foreach (var quest in _allQuests) + { + if (quest == questId) + { + questConfig = quest; + return true; + } + } + questConfig = null; + return false; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Mechanics/Factories/StoryQuestFactory.cs.meta b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Factories/StoryQuestFactory.cs.meta new file mode 100644 index 0000000..93e68da --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Factories/StoryQuestFactory.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d4bce8223f374bfa93db5e0b18b38cf2 +timeCreated: 1734960907 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Mechanics/QuestSystems/AchievementQuestSystem.cs b/RedCatEngineUnityProject/Packages/Quests/Mechanics/QuestSystems/AchievementQuestSystem.cs index f1b674e..edee5b6 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Mechanics/QuestSystems/AchievementQuestSystem.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Mechanics/QuestSystems/AchievementQuestSystem.cs @@ -24,7 +24,7 @@ protected sealed override void DoAfterLoadData() if (ActiveQuests.Any(quest => quest.Config == questConfig)) continue; - var quest = QuestFactory.MakeFromConfig(questConfig); + var quest = QuestQuestFactory.MakeFromConfig(questConfig); quest.Start(CurrentTime); ActiveQuests.Add(quest); } diff --git a/RedCatEngineUnityProject/Packages/Quests/Mechanics/QuestSystems/BaseQuestSystem.cs b/RedCatEngineUnityProject/Packages/Quests/Mechanics/QuestSystems/BaseQuestSystem.cs index 6fd28ea..d1b34db 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Mechanics/QuestSystems/BaseQuestSystem.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Mechanics/QuestSystems/BaseQuestSystem.cs @@ -10,20 +10,28 @@ namespace RedCatEngine.Quests.Mechanics.QuestSystems { public abstract class BaseQuestSystem : IDisposable { - public event Action ChangeStateQuest; - public event Action NewQuestEvent; protected readonly List ActiveQuests = new(); + protected readonly IQuestFactory QuestQuestFactory; + + protected BaseQuestSystem(IQuestFactory questQuestFactory) + { + QuestQuestFactory = questQuestFactory; + } + protected static DateTime CurrentTime => DateTime.UtcNow; //todo: make time service - protected readonly IQuestFactory QuestFactory; - - protected BaseQuestSystem(IQuestFactory questFactory) + public void Dispose() { - QuestFactory = questFactory; + foreach (var quest in ActiveQuests) + quest.ChangeQuestStateEvent -= OnChangeQuestState; + Clear(); } + public event Action ChangeStateQuest; + public event Action NewQuestEvent; + public void LoadData(QuestsDataContainer questsDataContainer) { if (questsDataContainer == QuestsDataContainer.Empty) @@ -36,7 +44,7 @@ public void LoadData(QuestsDataContainer questsDataContainer) var savedQuest = questsDataContainer.GetQuests(); foreach (var questData in savedQuest) { - var loadQuest = QuestFactory.LoadFrom(questData); + var loadQuest = QuestQuestFactory.LoadFrom(questData); if (loadQuest == null) continue; @@ -78,12 +86,12 @@ private bool TryGetQuest(ConfigID config, out IQuest quest) return false; } - public List GetActiveQuest() + public List GetActiveQuests() => ActiveQuests; protected IQuest CreateAndStartNewQuest() { - var newQuest = QuestFactory.MakeNewQuest(ActiveQuests); + var newQuest = QuestQuestFactory.MakeNewQuest(ActiveQuests); newQuest.Start(CurrentTime); NewQuestEvent?.Invoke(newQuest); return newQuest; @@ -91,7 +99,7 @@ protected IQuest CreateAndStartNewQuest() protected IQuest CreateAndStartNewQuest(ConfigID questConfig) { - var newQuest = QuestFactory.MakeFromConfig(questConfig); + var newQuest = QuestQuestFactory.MakeFromConfig(questConfig); newQuest.Start(CurrentTime); NewQuestEvent?.Invoke(newQuest); return newQuest; @@ -105,18 +113,16 @@ private void Clear() protected abstract void DoClear(); - public void Dispose() + protected void OnChangeQuestState(IQuest quest) { - foreach (var quest in ActiveQuests) - quest.ChangeQuestStateEvent -= OnChangeQuestState; - Clear(); + DoChangeQuestState(quest); + ChangeStateQuest?.Invoke(quest); } - private void OnChangeQuestState(IQuest quest) + protected virtual void DoChangeQuestState(IQuest quest) { - ChangeStateQuest?.Invoke(quest); } - + protected abstract void DoAfterLoadData(); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Mechanics/QuestSystems/DailyQuestSystem.cs b/RedCatEngineUnityProject/Packages/Quests/Mechanics/QuestSystems/DailyQuestSystem.cs index 40ba70b..1078448 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Mechanics/QuestSystems/DailyQuestSystem.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Mechanics/QuestSystems/DailyQuestSystem.cs @@ -48,7 +48,7 @@ Func PredicateForRemoveQuests() var toRemove = ActiveQuests.Where(PredicateForRemoveQuests()).ToArray(); foreach (var quest in toRemove) { - quest.Close(); + quest.Disable(); quest.ChangeQuestStateEvent -= OnChangeQuestState; ActiveQuests.Remove(quest); } diff --git a/RedCatEngineUnityProject/Packages/Quests/Mechanics/QuestSystems/StoryQuestSystem.cs b/RedCatEngineUnityProject/Packages/Quests/Mechanics/QuestSystems/StoryQuestSystem.cs new file mode 100644 index 0000000..e3fa0dd --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Quests/Mechanics/QuestSystems/StoryQuestSystem.cs @@ -0,0 +1,38 @@ +using RedCatEngine.DependencyInjection.Containers.Attributes; +using RedCatEngine.Quests.Configs.Quests; +using RedCatEngine.Quests.Mechanics.Factories; + +namespace RedCatEngine.Quests.Mechanics.QuestSystems +{ + public class StoryQuestSystem : BaseQuestSystem + { + [Inject] + public StoryQuestSystem(StoryQuestFactory questQuestFactory) : base(questQuestFactory) + { + } + + protected override void DoAfterLoadData() + { + } + + public void StartQuest(QuestConfig quest) + { + var newQuest = CreateAndStartNewQuest(quest); + newQuest.ChangeQuestStateEvent += OnChangeQuestState; + ActiveQuests.Add(newQuest); + } + + public void FinishedQuest(QuestConfig quest) + { + foreach (var activeQuest in ActiveQuests) + if (activeQuest.Config == quest) + activeQuest.SuccessFinished(); + } + + protected override void DoClear() + { + foreach (var quest in ActiveQuests) + quest.ChangeQuestStateEvent -= OnChangeQuestState; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Mechanics/QuestSystems/StoryQuestSystem.cs.meta b/RedCatEngineUnityProject/Packages/Quests/Mechanics/QuestSystems/StoryQuestSystem.cs.meta new file mode 100644 index 0000000..337fc9f --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Quests/Mechanics/QuestSystems/StoryQuestSystem.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 37041e9478b24f8aa35d6c42fced9475 +timeCreated: 1734960269 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/BaseCollectProgressQuest.cs b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/BaseCollectProgressQuest.cs index 3b5a2b4..5dbc577 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/BaseCollectProgressQuest.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/BaseCollectProgressQuest.cs @@ -8,20 +8,20 @@ namespace RedCatEngine.Quests.Mechanics.Quests { public abstract class BaseCollectProgressQuest : BaseSavedQuest { - public override double Progress - => Math.Min(1, CurrentValue / TargetValue); - - public override string ProcessProgressText - => $"{Math.Min(CurrentValue, TargetValue)} / {TargetValue}"; + protected BaseCollectProgressQuest(ConfigID config, double targetValue) + : base(config) + { + TargetValue = targetValue; + } protected double TargetValue { get; } protected double CurrentValue { get; private set; } - protected BaseCollectProgressQuest(ConfigID config, IReward reward, double targetValue) - : base(config, reward) - { - TargetValue = targetValue; - } + public override double GetProgress() + => Math.Min(1, CurrentValue / TargetValue); + + public override string GetProcessProgressText() + => $"{Math.Min(CurrentValue, TargetValue)} / {TargetValue}"; protected void SetCurrentValue(double value) { @@ -33,7 +33,7 @@ protected void SetCurrentValue(double value) protected override void CheckComplete() { - if(QuestState != QuestState.InProgress) + if (QuestState != QuestState.InProgress) return; if (TargetValue <= CurrentValue) diff --git a/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/BaseDeltaChangeProgressQuest.cs b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/BaseDeltaChangeProgressQuest.cs index e3dd946..40851c4 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/BaseDeltaChangeProgressQuest.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/BaseDeltaChangeProgressQuest.cs @@ -2,30 +2,29 @@ using RedCatEngine.Configs; using RedCatEngine.Quests.Configs.Quests; using RedCatEngine.Quests.Mechanics.Quests.QuestDatas; -using RedCatEngine.Rewards.Base; namespace RedCatEngine.Quests.Mechanics.Quests { public abstract class BaseDeltaChangeProgressQuest : BaseSavedQuest { - public override double Progress - => Math.Max(0, Math.Min(1, (CurrentDeltaValue - StartValue) / DeltaValue)); - public override string ProcessProgressText - => $"{Math.Min(Math.Max(0, CurrentDeltaValue - StartValue), DeltaValue)} / {DeltaValue}"; - - protected double DeltaValue { get; } - protected double CurrentDeltaValue { get; private set; } - protected double StartValue { get; private set; } - protected BaseDeltaChangeProgressQuest( ConfigID config, - IReward reward, double deltaValue - ) : base(config, reward) + ) : base(config) { DeltaValue = deltaValue; } + protected double DeltaValue { get; } + protected double CurrentDeltaValue { get; private set; } + protected double StartValue { get; private set; } + + public override double GetProgress() + => Math.Max(0, Math.Min(1, (CurrentDeltaValue - StartValue) / DeltaValue)); + + public override string GetProcessProgressText() + => $"{Math.Min(Math.Max(0, CurrentDeltaValue - StartValue), DeltaValue)} / {DeltaValue}"; + protected sealed override IQuest DoLoadData(DeltaChangeProgressQuestData questData) { CurrentDeltaValue = questData.CurrentDeltaValue; @@ -62,7 +61,7 @@ protected void AddDeltaCurrentValue(double delta) protected override void CheckComplete() { - if(QuestState is not QuestState.InProgress) + if (QuestState is not QuestState.InProgress) return; if (StartValue + DeltaValue <= CurrentDeltaValue) SendComplete(); diff --git a/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/BaseQuest.cs b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/BaseQuest.cs index 4b1dca2..c7fbd42 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/BaseQuest.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/BaseQuest.cs @@ -2,39 +2,31 @@ using RedCatEngine.Configs; using RedCatEngine.Quests.Configs.Quests; using RedCatEngine.Quests.Mechanics.Quests.QuestDatas; -using RedCatEngine.Rewards.Base; namespace RedCatEngine.Quests.Mechanics.Quests { public abstract class BaseQuest : IQuest { + protected BaseQuest(ConfigID config) + { + Config = config; + } + + protected DateTime StartQuestTime { get; private set; } public event Action ChangeQuestStateEvent; public event Action ChangeProgressEvent; public ConfigID Config { get; } - public IReward Reward { get; } - protected DateTime StartQuestTime { get; private set; } public QuestState QuestState { get; private set; } - public abstract double Progress { get; } - public abstract string ProcessProgressText { get; } - protected BaseQuest(ConfigID config, IReward reward) - { - Config = config; - Reward = reward; - } - - protected void SetStartTime(DateTime time) - => StartQuestTime = time; + public abstract double GetProgress(); + public abstract string GetProcessProgressText(); - protected void SetQuestState(QuestState newState) - { - if (newState == QuestState) - return; + public abstract string GetLocalizedName(); + public abstract string GetLocalizedDescription(); - QuestState = newState; - ChangeQuestStateEvent?.Invoke(this); - } + public abstract IQuest LoadSave(IQuestData data); + public abstract IQuestData GetData(); public void Start(DateTime time) { @@ -49,38 +41,50 @@ public void Continue() DoStart(); } - public void Close() - => DoClose(); + public void Disable() + => DoReset(); public void Skip() { if (QuestState is not QuestState.Finished) SetQuestState(QuestState.Skip); - Close(); + Disable(); } - public void Finished() + public void SuccessFinished() { if (QuestState is QuestState.Complete or QuestState.InProgress) SetQuestState(QuestState.Finished); + DoSuccessFinished(); + Disable(); + } + + protected abstract void CheckComplete(); + protected abstract void DoResetValue(); + protected abstract void DoStart(); + protected abstract void DoReset(); + protected abstract void DoSuccessFinished(); + + protected void SetStartTime(DateTime time) + => StartQuestTime = time; + + protected void SetQuestState(QuestState newState) + { + if (newState == QuestState) + return; + if (newState != QuestState.InProgress) + Disable(); + + QuestState = newState; + ChangeQuestStateEvent?.Invoke(this); } protected void SendComplete() { if (QuestState == QuestState.InProgress) SetQuestState(QuestState.Complete); - Close(); } - protected abstract void CheckComplete(); - protected abstract void DoResetValue(); - protected abstract void DoStart(); - protected abstract void DoClose(); - - public abstract IQuest LoadSave(IQuestData data); - public abstract IQuestData GetData(); - public abstract string GetDescription(); - protected void UpdateProgress() => ChangeProgressEvent?.Invoke(this); } diff --git a/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/BaseSavedQuest.cs b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/BaseSavedQuest.cs index e15882f..4d42b30 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/BaseSavedQuest.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/BaseSavedQuest.cs @@ -1,13 +1,12 @@ using RedCatEngine.Configs; using RedCatEngine.Quests.Configs.Quests; using RedCatEngine.Quests.Mechanics.Quests.QuestDatas; -using RedCatEngine.Rewards.Base; namespace RedCatEngine.Quests.Mechanics.Quests { public abstract class BaseSavedQuest : BaseQuest where TQuestData : BaseQuestData, new() { - protected BaseSavedQuest(ConfigID config, IReward reward) : base(config, reward) + protected BaseSavedQuest(ConfigID config) : base(config) { } @@ -20,7 +19,7 @@ public sealed override IQuest LoadSave(IQuestData data) SetQuestState(data.GetQuestState()); var result = DoLoadData(data as TQuestData); - + CheckComplete(); return result; } diff --git a/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/IQuest.cs b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/IQuest.cs index 4f87cca..a3ea985 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/IQuest.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/IQuest.cs @@ -1,27 +1,19 @@ using System; -using RedCatEngine.Configs; -using RedCatEngine.Quests.Configs.Quests; using RedCatEngine.Quests.Mechanics.Quests.QuestDatas; -using RedCatEngine.Rewards.Base; namespace RedCatEngine.Quests.Mechanics.Quests { - public interface IQuest + public interface IQuest : IQuestDescription { event Action ChangeQuestStateEvent; event Action ChangeProgressEvent; - ConfigID Config { get; } - public IReward Reward { get; } - QuestState QuestState { get; } - double Progress { get; } - string ProcessProgressText { get; } + void Start(DateTime time); void Continue(); - void Close(); + void Disable(); void Skip(); - void Finished(); + void SuccessFinished(); IQuest LoadSave(IQuestData data); IQuestData GetData(); - public string GetDescription(); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/IQuestDescription.cs b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/IQuestDescription.cs new file mode 100644 index 0000000..3e8fa15 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/IQuestDescription.cs @@ -0,0 +1,16 @@ +using RedCatEngine.Configs; +using RedCatEngine.Quests.Configs.Quests; + +namespace RedCatEngine.Quests.Mechanics.Quests +{ + public interface IQuestDescription + { + ConfigID Config { get; } + QuestState QuestState { get; } + + double GetProgress(); + string GetProcessProgressText(); + string GetLocalizedName(); + string GetLocalizedDescription(); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/IQuestDescription.cs.meta b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/IQuestDescription.cs.meta new file mode 100644 index 0000000..a04efc5 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Quests/Mechanics/Quests/IQuestDescription.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 34ad2ee2afe04cc18c7bca4aa2f05f85 +timeCreated: 1734957747 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Quests.asmdef b/RedCatEngineUnityProject/Packages/Quests/Quests.asmdef index 06d4c36..b096312 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Quests.asmdef +++ b/RedCatEngineUnityProject/Packages/Quests/Quests.asmdef @@ -6,7 +6,8 @@ "GUID:2a1cb7db0a8c79e47bda29872f7fe8e7", "GUID:bc1a77b6bbee94316b30d47e73c29c41", "GUID:687b69a268bf4402bb854a43d7732d8a", - "GUID:79ad2193969254fbd829729521e3eee3" + "GUID:79ad2193969254fbd829729521e3eee3", + "GUID:bbde3178fd05c8d478a9b2b47af2fb54" ], "includePlatforms": [], "excludePlatforms": [], diff --git a/RedCatEngineUnityProject/Packages/Quests/Tests/BaseCollectProgressQuestTests.cs b/RedCatEngineUnityProject/Packages/Quests/Tests/BaseCollectProgressQuestTests.cs index 6de67a1..6e01808 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Tests/BaseCollectProgressQuestTests.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Tests/BaseCollectProgressQuestTests.cs @@ -2,7 +2,6 @@ using RedCatEngine.Configs; using RedCatEngine.Quests.Configs.Quests; using RedCatEngine.Quests.Tests.SpecialSubClasses; -using RedCatEngine.Rewards.Base; using UnityEngine; namespace RedCatEngine.Quests.Tests @@ -12,16 +11,17 @@ public class BaseCollectProgressQuestTests [Test] public void GivenDeltaChangeProgressQuest_WhenChangeValuesAndSave_ThenLoadCorrect() { - var questForChange = new TestCollectProgressQuest(ConfigID.Invalid, IReward.Empty, 5); - Debug.Log($"Create quest. Start progress: {questForChange.ProcessProgressText}"); + var questForChange = new TestCollectProgressQuest(ConfigID.Invalid, 5); + Debug.Log($"Create quest. Start progress: {questForChange.GetProcessProgressText()}"); questForChange.SetCurrentValueForTest(3); - Debug.Log($"Progress after change: {questForChange.ProcessProgressText}"); + Debug.Log($"Progress after change: {questForChange.GetProcessProgressText()}"); var data = questForChange.GetData(); - var questForLoad = new TestCollectProgressQuest(ConfigID.Invalid, IReward.Empty, 5); + var questForLoad = new TestCollectProgressQuest(ConfigID.Invalid, 5); questForLoad.LoadSave(data); - Debug.Log($"New quest after load: {questForLoad.ProcessProgressText}"); - Assert.AreEqual(questForChange.ProcessProgressText, - questForLoad.ProcessProgressText, + Debug.Log($"New quest after load: {questForLoad.GetProcessProgressText()}"); + Assert.AreEqual( + questForChange.GetProcessProgressText(), + questForLoad.GetProcessProgressText(), "Incorrect load data"); } } diff --git a/RedCatEngineUnityProject/Packages/Quests/Tests/BaseDeltaChangeProgressQuestTests.cs b/RedCatEngineUnityProject/Packages/Quests/Tests/BaseDeltaChangeProgressQuestTests.cs index d3f6e2e..b935de7 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Tests/BaseDeltaChangeProgressQuestTests.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Tests/BaseDeltaChangeProgressQuestTests.cs @@ -2,7 +2,6 @@ using RedCatEngine.Configs; using RedCatEngine.Quests.Configs.Quests; using RedCatEngine.Quests.Tests.SpecialSubClasses; -using RedCatEngine.Rewards.Base; using UnityEngine; namespace RedCatEngine.Quests.Tests @@ -12,18 +11,19 @@ public class BaseDeltaChangeProgressQuestTests [Test] public void GivenDeltaChangeProgressQuest_WhenChangeValuesAndSave_ThenLoadCorrect() { - var questForChange = new TestDeltaChangeProgressQuest(ConfigID.Invalid, IReward.Empty, 5); - Debug.Log($"Create quest. Start progress: {questForChange.ProcessProgressText}"); + var questForChange = new TestDeltaChangeProgressQuest(ConfigID.Invalid, 5); + Debug.Log($"Create quest. Start progress: {questForChange.GetProcessProgressText()}"); questForChange.SetStartValueForTest(1); questForChange.SetCurrentValueForTest(3); - Debug.Log($"Progress after change: {questForChange.ProcessProgressText}"); + Debug.Log($"Progress after change: {questForChange.GetProcessProgressText()}"); var data = questForChange.GetData(); - var questForLoad = new TestDeltaChangeProgressQuest(ConfigID.Invalid, IReward.Empty, 5); + var questForLoad = new TestDeltaChangeProgressQuest(ConfigID.Invalid, 5); questForLoad.LoadSave(data); - Debug.Log($"New quest after load: {questForLoad.ProcessProgressText}"); + Debug.Log($"New quest after load: {questForLoad.GetProcessProgressText()}"); - Assert.AreEqual(questForChange.ProcessProgressText, - questForLoad.ProcessProgressText, + Assert.AreEqual( + questForChange.GetProcessProgressText(), + questForLoad.GetProcessProgressText(), "Incorrect load data"); } } diff --git a/RedCatEngineUnityProject/Packages/Quests/Tests/DailyQuestSystemTests.cs b/RedCatEngineUnityProject/Packages/Quests/Tests/DailyQuestSystemTests.cs index 8113e5b..8977324 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Tests/DailyQuestSystemTests.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Tests/DailyQuestSystemTests.cs @@ -5,7 +5,6 @@ using RedCatEngine.Quests.Mechanics.Quests; using RedCatEngine.Quests.Mechanics.QuestSystems; using RedCatEngine.Quests.Tests.SpecialSubClasses; -using RedCatEngine.Rewards.Base; using UnityEngine; namespace RedCatEngine.Quests.Tests @@ -38,7 +37,7 @@ public void GivenDailyQuestSystem_WhenCreateWithEmptyData_ThenCreatedNeedCountQu _testFactory, questCount, 24 * 60 * 60); - var activeQuests = system.GetActiveQuest(); + var activeQuests = system.GetActiveQuests(); Assert.AreEqual( activeQuests.Count, @@ -66,7 +65,7 @@ public void GivenDailyQuestSystemWithQuests_WhenSkipQuest_ThenActiveQuestIsResto 3, 24 * 60 * 60); skipQuest.Skip(); - var activeQuests = system.GetActiveQuest(); + var activeQuests = system.GetActiveQuests(); Assert.AreEqual( activeQuests.Sum(quest => quest.QuestState == QuestState.Skip ? 1 : 0), @@ -97,8 +96,8 @@ public void GivenDailyQuestSystemWithQuests_WhenFinishedQuest_ThenActiveQuestLes _testFactory, 3, 24 * 60 * 60); - skipQuest.Close(); - var activeQuests = system.GetActiveQuest(); + skipQuest.Disable(); + var activeQuests = system.GetActiveQuests(); Assert.AreEqual( activeQuests.Sum(quest => quest.QuestState == QuestState.Skip ? 1 : 0), @@ -115,26 +114,23 @@ public void GivenDailyQuestSystemWithQuests_WhenSaveData_ThenCorrectLoad() { var deltaTest = new TestDeltaChangeProgressQuest( ConfigID.MakeForTest(41), - IReward.Empty, 41); var deltaTest2 = new TestDeltaChangeProgressQuest( ConfigID.MakeForTest(42), - IReward.Empty, 42); var collectTest = new TestCollectProgressQuest( ConfigID.MakeForTest(43), - IReward.Empty, 43); Debug.Log("Before load parameters:"); deltaTest.SetStartValueForTest(21); deltaTest.SetCurrentValueForTest(44); - Debug.LogFormat("41: {0}", deltaTest.ProcessProgressText); + Debug.LogFormat("41: {0}", deltaTest.GetProcessProgressText()); deltaTest2.SetStartValueForTest(20); deltaTest2.SetCurrentValueForTest(44); - Debug.LogFormat("42: {0}", deltaTest2.ProcessProgressText); + Debug.LogFormat("42: {0}", deltaTest2.GetProcessProgressText()); collectTest.SetCurrentValueForTest(3); - Debug.LogFormat("43: {0}", collectTest.ProcessProgressText); + Debug.LogFormat("43: {0}", collectTest.GetProcessProgressText()); _testFactory.SetReturnQuest( new IQuest[] @@ -161,15 +157,12 @@ public void GivenDailyQuestSystemWithQuests_WhenSaveData_ThenCorrectLoad() var deltaTestAfterLoad = new TestDeltaChangeProgressQuest( ConfigID.MakeForTest(41), - IReward.Empty, 41); var deltaTest2AfterLoad = new TestDeltaChangeProgressQuest( ConfigID.MakeForTest(42), - IReward.Empty, 42); var collectTestAfterLoad = new TestCollectProgressQuest( ConfigID.MakeForTest(43), - IReward.Empty, 43); _testFactory.SetReturnQuest( @@ -186,17 +179,17 @@ public void GivenDailyQuestSystemWithQuests_WhenSaveData_ThenCorrectLoad() 24 * 60 * 60); systemForLoad.LoadData(questContainer); - var activeQuestBeforeLoad = systemForSave.GetActiveQuest(); - var activeQuestAfterLoad = systemForLoad.GetActiveQuest(); + var activeQuestBeforeLoad = systemForSave.GetActiveQuests(); + var activeQuestAfterLoad = systemForLoad.GetActiveQuests(); Assert.AreEqual(activeQuestBeforeLoad.Count, activeQuestAfterLoad.Count); for (var i = 0; i < activeQuestBeforeLoad.Count; i++) { - Debug.Log($"[{i}] Before: {activeQuestBeforeLoad[i].ProcessProgressText}"); - Debug.Log($"[{i}] After: {activeQuestAfterLoad[i].ProcessProgressText}"); + Debug.Log($"[{i}] Before: {activeQuestBeforeLoad[i].GetProcessProgressText()}"); + Debug.Log($"[{i}] After: {activeQuestAfterLoad[i].GetProcessProgressText()}"); Assert.AreEqual( - activeQuestBeforeLoad[i].ProcessProgressText, - activeQuestAfterLoad[i].ProcessProgressText); + activeQuestBeforeLoad[i].GetProcessProgressText(), + activeQuestAfterLoad[i].GetProcessProgressText()); } } @@ -220,7 +213,7 @@ public void GivenDailyQuestSystemWithQuests_WhenSaveQuests_ThenActiveQuestIsRest 3, 24 * 60 * 60); skipQuest.Skip(); - var activeQuests = system.GetActiveQuest(); + var activeQuests = system.GetActiveQuests(); Assert.AreEqual( activeQuests.Sum(quest => quest.QuestState == QuestState.Skip ? 1 : 0), diff --git a/RedCatEngineUnityProject/Packages/Quests/Tests/QuestsTests.asmdef b/RedCatEngineUnityProject/Packages/Quests/Tests/QuestsTests.asmdef index 0e71a5b..9b3af9d 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Tests/QuestsTests.asmdef +++ b/RedCatEngineUnityProject/Packages/Quests/Tests/QuestsTests.asmdef @@ -6,7 +6,10 @@ "UnityEditor.TestRunner", "Quests", "Configs", - "Rewards" + "Rewards", + "Conditions", + "DependencyInjection", + "Values" ], "includePlatforms": [ "Editor" diff --git a/RedCatEngineUnityProject/Packages/Quests/Tests/SpecialSubClasses/TestCollectProgressQuest.cs b/RedCatEngineUnityProject/Packages/Quests/Tests/SpecialSubClasses/TestCollectProgressQuest.cs index 6d03994..d6c0e8d 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Tests/SpecialSubClasses/TestCollectProgressQuest.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Tests/SpecialSubClasses/TestCollectProgressQuest.cs @@ -1,40 +1,48 @@ using RedCatEngine.Configs; using RedCatEngine.Quests.Configs.Quests; using RedCatEngine.Quests.Mechanics.Quests; -using RedCatEngine.Rewards.Base; namespace RedCatEngine.Quests.Tests.SpecialSubClasses { public class TestCollectProgressQuest : BaseCollectProgressQuest { + public TestCollectProgressQuest( + ConfigID config, + float targetValue + ) + : base( + config, + targetValue) + { + } public void SetCurrentValueForTest(float newValue) => SetCurrentValue(newValue); protected override void DoResetValue() { - } protected override void DoStart() { - } - protected override void DoClose() + protected override void DoReset() + { + } + + protected override void DoSuccessFinished() { - } - public override string GetDescription() + public override string GetLocalizedName() { throw new System.NotImplementedException(); } - public TestCollectProgressQuest(ConfigID config, IReward reward, - float targetValue - ) - : base(config, reward, - targetValue) { } + public override string GetLocalizedDescription() + { + throw new System.NotImplementedException(); + } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Tests/SpecialSubClasses/TestDeltaChangeProgressQuest.cs b/RedCatEngineUnityProject/Packages/Quests/Tests/SpecialSubClasses/TestDeltaChangeProgressQuest.cs index 72f91e7..03d8956 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Tests/SpecialSubClasses/TestDeltaChangeProgressQuest.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Tests/SpecialSubClasses/TestDeltaChangeProgressQuest.cs @@ -1,12 +1,21 @@ using RedCatEngine.Configs; using RedCatEngine.Quests.Configs.Quests; using RedCatEngine.Quests.Mechanics.Quests; -using RedCatEngine.Rewards.Base; namespace RedCatEngine.Quests.Tests.SpecialSubClasses { public class TestDeltaChangeProgressQuest : BaseDeltaChangeProgressQuest { + public TestDeltaChangeProgressQuest( + ConfigID config, + float deltaValue + ) + : base( + config, + deltaValue) + { + } + public void SetStartValueForTest(float startValue) => SetStartAndCurrentValue(startValue); @@ -17,21 +26,20 @@ protected override void DoResetValue() { } protected override void DoStart() { } - protected override void DoClose() { } + protected override void DoReset() { } - public override string GetDescription() + protected override void DoSuccessFinished() + { + } + + public override string GetLocalizedName() { throw new System.NotImplementedException(); } - public TestDeltaChangeProgressQuest( - ConfigID config, - IReward reward, - float deltaValue - ) - : base( - config, - reward, - deltaValue) { } + public override string GetLocalizedDescription() + { + throw new System.NotImplementedException(); + } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Tests/SpecialSubClasses/TestQuest.cs b/RedCatEngineUnityProject/Packages/Quests/Tests/SpecialSubClasses/TestQuest.cs index e0392f8..44d04fd 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Tests/SpecialSubClasses/TestQuest.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Tests/SpecialSubClasses/TestQuest.cs @@ -9,13 +9,28 @@ namespace RedCatEngine.Quests.Tests.SpecialSubClasses { public class TestQuest : IQuest { + private string _processProgressText; + private double _progress; + public IReward Reward { get; } + public double Progress + { + set => _progress = value; + } + + public string ProcessProgressText + { + set => _processProgressText = value; + } public event Action ChangeQuestStateEvent; public event Action ChangeProgressEvent; public ConfigID Config { get; set; } - public IReward Reward { get; } public QuestState QuestState { get; set; } - public double Progress { get; set; } - public string ProcessProgressText { get; set; } + + public double GetProgress() + => _progress; + + public string GetProcessProgressText() + => _processProgressText; public void Start(DateTime time) { @@ -28,7 +43,7 @@ public void Continue() throw new NotImplementedException(); } - public void Close() + public void Disable() { QuestState = QuestState.Complete; ChangeQuestStateEvent?.Invoke(this); @@ -40,9 +55,8 @@ public void Skip() ChangeQuestStateEvent?.Invoke(this); } - public void Finished() + public void SuccessFinished() { - } public IQuest LoadSave(IQuestData data) @@ -55,7 +69,12 @@ public IQuestData GetData() return new TestQuestData(); } - public string GetDescription() + public string GetLocalizedName() + { + throw new NotImplementedException(); + } + + public string GetLocalizedDescription() { throw new NotImplementedException(); } diff --git a/RedCatEngineUnityProject/Packages/Quests/Tests/SpecialSubClasses/TestQuestFactory.cs b/RedCatEngineUnityProject/Packages/Quests/Tests/SpecialSubClasses/TestQuestFactory.cs index 9c5e626..6160784 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Tests/SpecialSubClasses/TestQuestFactory.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Tests/SpecialSubClasses/TestQuestFactory.cs @@ -9,16 +9,10 @@ namespace RedCatEngine.Quests.Tests.SpecialSubClasses { public class TestQuestFactory : IQuestFactory { - private IQuest[] _returnQuest; private int _index = 0; + private IQuest[] _returnQuest; - public void SetReturnQuest(IQuest[] returnQuest) - { - _returnQuest = returnQuest; - _index = 0; - } - - public IQuest MakeFromConfig(ConfigID questConfig) + public IQuest MakeFromConfig(ConfigID questId) { throw new System.NotImplementedException(); } @@ -28,13 +22,6 @@ public IQuest MakeNewQuest(List currentActiveQuests) throw new System.NotImplementedException(); } - public IQuest MakeNewQuest() - { - var result = _returnQuest[_index]; - _index++; - return result; - } - public IQuest LoadFrom(IQuestData saveData) { foreach (var quest in _returnQuest) @@ -47,5 +34,18 @@ public bool TryLoad(ConfigID questId, out QuestConfig questConfig) { throw new System.NotImplementedException(); } + + public void SetReturnQuest(IQuest[] returnQuest) + { + _returnQuest = returnQuest; + _index = 0; + } + + public IQuest MakeNewQuest() + { + var result = _returnQuest[_index]; + _index++; + return result; + } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Quests/Utils/SerializedDateTime.cs b/RedCatEngineUnityProject/Packages/Quests/Utils/SerializedDateTime.cs index e9dfcbd..ed4edaf 100644 --- a/RedCatEngineUnityProject/Packages/Quests/Utils/SerializedDateTime.cs +++ b/RedCatEngineUnityProject/Packages/Quests/Utils/SerializedDateTime.cs @@ -5,8 +5,6 @@ namespace RedCatEngine.Quests.Utils [Serializable] public class SerializedDateTime { - public static SerializedDateTime Now - => (SerializedDateTime)DateTime.Now; public int Year; public int Month; public int Day; diff --git a/RedCatEngineUnityProject/Packages/Rewards/Rewards.asmdef b/RedCatEngineUnityProject/Packages/Rewards/Rewards.asmdef index 79f0e0c..e9509a8 100644 --- a/RedCatEngineUnityProject/Packages/Rewards/Rewards.asmdef +++ b/RedCatEngineUnityProject/Packages/Rewards/Rewards.asmdef @@ -5,7 +5,8 @@ "GUID:2a1cb7db0a8c79e47bda29872f7fe8e7", "GUID:687b69a268bf4402bb854a43d7732d8a", "GUID:79ad2193969254fbd829729521e3eee3", - "GUID:bc1a77b6bbee94316b30d47e73c29c41" + "GUID:bc1a77b6bbee94316b30d47e73c29c41", + "GUID:bbde3178fd05c8d478a9b2b47af2fb54" ], "includePlatforms": [], "excludePlatforms": [], diff --git a/RedCatEngineUnityProject/Packages/StateMachine/StateMachines/BasePayloadState.cs b/RedCatEngineUnityProject/Packages/StateMachine/StateMachines/BasePayloadState.cs index 2926ee2..81f9b33 100644 --- a/RedCatEngineUnityProject/Packages/StateMachine/StateMachines/BasePayloadState.cs +++ b/RedCatEngineUnityProject/Packages/StateMachine/StateMachines/BasePayloadState.cs @@ -7,7 +7,7 @@ public void Enter(object payload) Enter((TPayload)payload); } - public abstract void Exit(); + public virtual void Exit() { } public abstract void Enter(TPayload payload); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/StateMachine/StateMachines/BaseTypedStateMachine.cs b/RedCatEngineUnityProject/Packages/StateMachine/StateMachines/BaseTypedStateMachine.cs index 7bd5dd3..f076351 100644 --- a/RedCatEngineUnityProject/Packages/StateMachine/StateMachines/BaseTypedStateMachine.cs +++ b/RedCatEngineUnityProject/Packages/StateMachine/StateMachines/BaseTypedStateMachine.cs @@ -1,49 +1,77 @@ using System; using System.Collections.Generic; using RedCatEngine.StateMachine.Exceptions; +using UnityEngine; namespace RedCatEngine.StateMachine.StateMachines { - public abstract class BaseTypedStateMachine : ITypedGameStateMachine + public abstract class BaseTypedStateMachine : ITypedGameStateMachine + where TBaseState : IExitableState { - private readonly Dictionary _states = new(); + private readonly string _name; + protected readonly Dictionary _states = new(); private readonly Queue _queue = new(); private readonly List _stepHistory = new(); - protected IExitableState ActiveState { get; private set; } + protected BaseTypedStateMachine(string name) + { + _name = name; + } + + protected TBaseState ActiveState { get; private set; } - protected void AddState(IExitableState state) where TType : IExitableState + protected void AddState(TBaseState state) where TType : TBaseState { if (_states.ContainsKey(typeof(TType))) throw new AlreadyContainStateException(typeof(TType)); _states.Add(typeof(TType), state); } - protected void AddState(TType state) where TType : IExitableState + protected void AddState(TState state) where TState : TBaseState { - if (_states.ContainsKey(typeof(TType))) - throw new AlreadyContainStateException(typeof(TType)); - _states.Add(typeof(TType), state); + if (_states.ContainsKey(typeof(TState))) + throw new AlreadyContainStateException(typeof(TState)); + _states.Add(typeof(TState), state); } - public ITypedQueueStateMachine Enter() where TState : class, IState + protected void AddState(Type stateType, TBaseState state) { - IState state = SelectStateAsActive(); - state.Enter(); - _stepHistory.Add(new StateStepData(typeof(TState))); + if (!_states.TryAdd(stateType, state)) + throw new AlreadyContainStateException(stateType); + } + + public ITypedQueueStateMachine Enter() where TState : class, TBaseState, IState + { + var state = SelectStateAsActive(); + AddToHistory(new StateStepData(typeof(TState))); + EnterState(state); return this; } + private void EnterState(IState state) + { + if(state == null) + throw new ArgumentNullException(string.Format("State {0} is null", nameof(state))); + state.Enter(); + } + + private void EnterState(IPayloadedState state, TPayload payload) + { + if(state == null) + throw new ArgumentNullException(string.Format("State {0} is null", nameof(state))); + state.Enter(payload); + } + public ITypedQueueStateMachine Enter(TPayload payload) - where TState : class, IPayloadedState + where TState : class, TBaseState, IPayloadedState { var state = SelectStateAsActive(); - state.Enter(payload); - _stepHistory.Add( + AddToHistory( new StateStepData( typeof(TState), typeof(TPayload), payload)); + state.Enter(payload); return this; } @@ -51,34 +79,48 @@ public ITypedQueueStateMachine Enter(TPayload payload) public ITypedQueueStateMachine EnterNextFromQueue() { var data = _queue.Dequeue(); + AddToHistory(data); var nextState = SelectStateAsActive(data.StateType); if (!data.IsPayLoadState) - (nextState as IState)?.Enter(); + EnterState(nextState as IState); else - (nextState as IPayloadedState)?.Enter(data.Payload); + EnterState(nextState as IPayloadedState, data.Payload); - _stepHistory.Add(data); return this; } public ITypedQueueStateMachine AddToQueue() where TState : class, IState { - _queue.Enqueue(new StateStepData(typeof(TState))); - return this; + return AddToQueue(new StateStepData(typeof(TState))); } public ITypedQueueStateMachine AddToQueue(TPayload payload) where TState : class, IPayloadedState { - _queue.Enqueue( + return AddToQueue( new StateStepData( typeof(TState), typeof(TPayload), payload)); + } + + private void AddToHistory(StateStepData data) + { + if(!data.IsPayLoadState) + Debug.LogFormat("[{0}] Enter to state {1}", _name, data.StateType); + else + Debug.LogFormat("[{0}] Enter to payload state {1} with {2}", _name, data.StateType, data.Payload); + _stepHistory.Add(data); + } + + private ITypedQueueStateMachine AddToQueue(StateStepData data) + { + Debug.LogFormat("[{0}] Add to queue state {1}", _name, data.StateType); + _queue.Enqueue(data); return this; } - private TState SelectStateAsActive() where TState : class, IExitableState + private TState SelectStateAsActive() where TState : class, TBaseState { ActiveState?.Exit(); @@ -101,10 +143,12 @@ private IExitableState SelectStateAsActive(Type type) private TState GetState() where TState : class, IExitableState => GetState(typeof(TState)) as TState; - private IExitableState GetState(Type type) + protected virtual TBaseState GetState(Type type) { if (!_states.TryGetValue(type, out var targetState)) throw new NotFoundStateException(type); + if(targetState == null) + Debug.LogError("State is null"); return targetState; } } diff --git a/RedCatEngineUnityProject/Packages/StateMachine/StateMachines/ITypedGameStateMachine.cs b/RedCatEngineUnityProject/Packages/StateMachine/StateMachines/ITypedGameStateMachine.cs index 5c3c2a2..c23c993 100644 --- a/RedCatEngineUnityProject/Packages/StateMachine/StateMachines/ITypedGameStateMachine.cs +++ b/RedCatEngineUnityProject/Packages/StateMachine/StateMachines/ITypedGameStateMachine.cs @@ -1,8 +1,8 @@ namespace RedCatEngine.StateMachine.StateMachines { - public interface ITypedGameStateMachine : ITypedQueueStateMachine + public interface ITypedGameStateMachine : ITypedQueueStateMachine { - ITypedQueueStateMachine Enter() where TState : class, IState; - ITypedQueueStateMachine Enter(TPayload payload) where TState : class, IPayloadedState; + new ITypedQueueStateMachine Enter() where TState : class, IState, TBaseState; + new ITypedQueueStateMachine Enter(TPayload payload) where TState : class, IPayloadedState, TBaseState; } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/StateMachine/Tests/BaseStatesTests.cs b/RedCatEngineUnityProject/Packages/StateMachine/Tests/BaseStatesTests.cs index 41e237e..49ed406 100644 --- a/RedCatEngineUnityProject/Packages/StateMachine/Tests/BaseStatesTests.cs +++ b/RedCatEngineUnityProject/Packages/StateMachine/Tests/BaseStatesTests.cs @@ -21,10 +21,10 @@ public void SetUp() _testStateB = new TestStateB(); _testStateC = new TestStateC(); - _stateMachine.AddTestState(_testStateA); - _stateMachine.AddTestState(_testStateB); - _stateMachine.AddTestState(_testStateC); - _stateMachine.AddTestState(_testStatePayloadA); + _stateMachine.AddTestState(_testStateA); + _stateMachine.AddTestState(_testStateB); + _stateMachine.AddTestState(_testStateC); + _stateMachine.AddTestState(_testStatePayloadA); } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/StateMachine/Tests/SpecialSubClasses/TestedTypedStateMachine.cs b/RedCatEngineUnityProject/Packages/StateMachine/Tests/SpecialSubClasses/TestedTypedStateMachine.cs index c5c3690..fc488ce 100644 --- a/RedCatEngineUnityProject/Packages/StateMachine/Tests/SpecialSubClasses/TestedTypedStateMachine.cs +++ b/RedCatEngineUnityProject/Packages/StateMachine/Tests/SpecialSubClasses/TestedTypedStateMachine.cs @@ -2,10 +2,14 @@ namespace RedCatEngine.StateMachine.Tests.SpecialSubClasses { - public class TestedTypedStateMachine : BaseTypedStateMachine + public class TestedTypedStateMachine : BaseTypedStateMachine { - public void AddTestState(IExitableState state) where TType : IExitableState - => AddState(state); + public TestedTypedStateMachine() : base("TestedTypedStateMachine") + { + } + + public void AddTestState(TType state) where TType : IExitableState + => AddState(state); public IExitableState CurrenState => ActiveState; diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/CommonServices.asmdef b/RedCatEngineUnityProject/Packages/UniversalServices/CommonServices.asmdef new file mode 100644 index 0000000..5191b09 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/CommonServices.asmdef @@ -0,0 +1,18 @@ +{ + "name": "CommonServices", + "rootNamespace": "RedCatEngine.CommonServices", + "references": [ + "GUID:bc1a77b6bbee94316b30d47e73c29c41", + "GUID:687b69a268bf4402bb854a43d7732d8a", + "GUID:f8db481d96857fd478a6ffb797500869" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/CommonServices.asmdef.meta b/RedCatEngineUnityProject/Packages/UniversalServices/CommonServices.asmdef.meta new file mode 100644 index 0000000..bfe2d35 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/CommonServices.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: b8800b26ba16516489a32c4ee4cd1d0f +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers.meta new file mode 100644 index 0000000..68a81d9 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: fb59fd72592e446bba3a986b55067b24 +timeCreated: 1726149943 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components.meta new file mode 100644 index 0000000..097bebd --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 21274a78f6c9459fb5817067a74dd6b2 +timeCreated: 1726663339 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components/IRedComponent.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components/IRedComponent.cs new file mode 100644 index 0000000..cbecdc5 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components/IRedComponent.cs @@ -0,0 +1,7 @@ +namespace RedCatEngine.CommonServices.Containers.Components +{ + public interface IRedComponent + { + + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components/IRedComponent.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components/IRedComponent.cs.meta new file mode 100644 index 0000000..481ac44 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components/IRedComponent.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c38d54e8126b4566a3e1916f0d3f6b8c +timeCreated: 1726663333 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components/IRedComponentContainer.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components/IRedComponentContainer.cs new file mode 100644 index 0000000..2ae2b91 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components/IRedComponentContainer.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; + +namespace RedCatEngine.CommonServices.Containers.Components +{ + public interface IRedComponentContainer + { + bool TryGetRedComponent(out TRedComponent result) where TRedComponent : IRedComponent; + TRedComponent GetRedComponent() where TRedComponent : IRedComponent; + IEnumerable GetRedComponents() where TRedComponent : IRedComponent; + void Add(TRedComponent item) where TRedComponent : IRedComponent; + void Remove() where TRedComponent : IRedComponent; + bool IsContains() where TRedComponent : IRedComponent; + + TRedComponent GetOrCreateRedComponent() where TRedComponent : IRedComponent, new() + { + if (TryGetRedComponent(out TRedComponent result)) + return result; + + result = new TRedComponent(); + Add(result); + return result; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components/IRedComponentContainer.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components/IRedComponentContainer.cs.meta new file mode 100644 index 0000000..66d033e --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components/IRedComponentContainer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c60880fca28f4f5eb47f0e8f2e7fdade +timeCreated: 1732709907 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components/RedComponentContainer.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components/RedComponentContainer.cs new file mode 100644 index 0000000..b10dd83 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components/RedComponentContainer.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using RedCatEngine.CommonServices.Containers.Storages.TypedStorage; + +namespace RedCatEngine.CommonServices.Containers.Components +{ + public class RedComponentContainer : ConditionTypedStorage, IRedComponentContainer + { + public bool TryGetRedComponent(out TRedComponent result) where TRedComponent : IRedComponent + => TryGet(out result); + + public TRedComponent GetRedComponent() where TRedComponent : IRedComponent + { + if (TryGet(out var result)) + return result; + + throw new Exception("Not found component" + typeof(TRedComponent)); + } + + public IEnumerable GetRedComponents() where TRedComponent : IRedComponent + { + return TryGets(out var result) ? result : ArraySegment.Empty; + } + + public new void Add(TRedComponent item) where TRedComponent : IRedComponent + { + base.Add(item); + } + + public void Remove() where TRedComponent : IRedComponent + { + base.Remove(); + } + + public bool IsContains() where TRedComponent : IRedComponent + { + return IsContain(); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components/RedComponentContainer.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components/RedComponentContainer.cs.meta new file mode 100644 index 0000000..5115529 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Components/RedComponentContainer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 25a3a3f9fe984e1fb6b5461634cee451 +timeCreated: 1726663360 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Observables.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Observables.meta new file mode 100644 index 0000000..800ccce --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Observables.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d5b369f56b5d48c2913c07427bb34192 +timeCreated: 1733393822 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Observables/Observable.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Observables/Observable.cs new file mode 100644 index 0000000..ed05ad0 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Observables/Observable.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; + +namespace RedCatEngine.CommonServices.Containers.Observables +{ + public class Observable + { + private T _value; + public event Action ValueChangeEvent; + + public T Value + { + get => _value; + set => Set(value); + } + + public static implicit operator T(Observable observable) + => observable._value; + + public Observable(T value, Action onValueChanged = null) + { + this._value = value; + + if (onValueChanged != null) + ValueChangeEvent += onValueChanged; + } + + public void Set(T value) + { + if (EqualityComparer.Default.Equals(this._value, value)) + return; + this._value = value; + Invoke(); + } + + private void Invoke() + { + ValueChangeEvent?.Invoke(_value); + } + + public void AddListener(Action handler) + { + ValueChangeEvent += handler; + } + + public void RemoveListener(Action handler) + { + ValueChangeEvent -= handler; + } + + public void Dispose() + { + ValueChangeEvent = null; + _value = default; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Observables/Observable.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Observables/Observable.cs.meta new file mode 100644 index 0000000..f1aa9c6 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Observables/Observable.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 8cfd3623fb554e658c8e61f2f1132b1d +timeCreated: 1733393839 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages.meta new file mode 100644 index 0000000..0d4911a --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: fd4ec0b8f428483fa2048605346915f9 +timeCreated: 1726149952 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/BaseStorage.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/BaseStorage.meta new file mode 100644 index 0000000..b38d507 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/BaseStorage.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4b06bbf1fcb649f5b1d923d276dbb14d +timeCreated: 1726208578 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/BaseStorage/BaseStorage.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/BaseStorage/BaseStorage.cs new file mode 100644 index 0000000..66577fa --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/BaseStorage/BaseStorage.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace RedCatEngine.CommonServices.Containers.Storages.BaseStorage +{ + public class BaseStorage : IStorage + { + protected readonly List _items = new(); + + public event Action DeltaChangeElementEvent; + public event Action FinalChangeElementEvent; + public event Action ClearEvent; + + public IEnumerable GetElements() + => _items; + + public virtual bool IsContain(TItemContainer item) + => _items.Contains(item); + + public bool IsContainAny(IEnumerable itemsForCheck) + => _items.Any(itemsForCheck.Contains); + + public void Add(TItemContainer item) + { + _items.Add(item); + DeltaChangeElementEvent?.Invoke(item, 1); + FinalChangeElementEvent?.Invoke(item, 1); + } + + public void Clear() + { + _items.Clear(); + ClearEvent?.Invoke(); + } + + public void Remove(TItemContainer item) + => _items.Remove(item); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/BaseStorage/BaseStorage.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/BaseStorage/BaseStorage.cs.meta new file mode 100644 index 0000000..326ce55 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/BaseStorage/BaseStorage.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4f085b48aca743edacdbe552fc1ddc04 +timeCreated: 1726150074 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/BaseStorage/IStorage.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/BaseStorage/IStorage.cs new file mode 100644 index 0000000..1a62131 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/BaseStorage/IStorage.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using RedCatEngine.CommonServices.Containers.Components; + +namespace RedCatEngine.CommonServices.Containers.Storages.BaseStorage +{ + public interface IStorage : IRedComponent + { + event Action DeltaChangeElementEvent; + event Action FinalChangeElementEvent; + event Action ClearEvent; + IEnumerable GetElements(); + void Add(TItem item); + bool IsContain(TItem item); + bool IsContainAny(IEnumerable itemsForCheck); + void Clear(); + void Remove(TItem item); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/BaseStorage/IStorage.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/BaseStorage/IStorage.cs.meta new file mode 100644 index 0000000..1782a53 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/BaseStorage/IStorage.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 36aac75323f64ad9bda2ec83c3041f6a +timeCreated: 1726149968 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/CountedStorage.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/CountedStorage.meta new file mode 100644 index 0000000..6b3dad1 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/CountedStorage.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 32ddeb73317e4d1ea65e2f433bbc5943 +timeCreated: 1726208603 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/CountedStorage/BaseCountedStorage.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/CountedStorage/BaseCountedStorage.cs new file mode 100644 index 0000000..c4b94da --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/CountedStorage/BaseCountedStorage.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace RedCatEngine.CommonServices.Containers.Storages.CountedStorage +{ + public class BaseCountedStorage : ICountedStorage + { + private readonly Dictionary _container = new(); + public event Action DeltaChangeElementEvent; + public event Action FinalChangeElementEvent; + public event Action ClearEvent; + + public IEnumerable GetElements() + => _container.Keys.Where(item => IsContain(item)); + + public void Add(TItem item) + => Add(item, 1); + + public void Add(TItem item, int addCount) + { + if (_container.TryGetValue(item, out var currentCount)) + _container[item] = currentCount + addCount; + else + _container.Add(item, addCount); + DeltaChangeElementEvent?.Invoke(item, addCount); + FinalChangeElementEvent?.Invoke(item, GetCount(item)); + } + + public bool IsContain(TItem item) + => _container.TryGetValue(item, out var count) && count > 0; + + public bool IsContain(TItem item, int count) + => IsContain(item) && _container[item] >= count; + + public bool IsContainAny(IEnumerable itemsForCheck) + => itemsForCheck.Any(IsContain); + + public void Clear() + { + _container.Clear(); + ClearEvent?.Invoke(); + } + + public void Remove(TItem item) + => Remove(item, 1); + + public void Remove(TItem item, int count) + { + if (!_container.TryGetValue(item, out var currentCount)) + return; + + _container[item] = Math.Max(currentCount - count, 0); + DeltaChangeElementEvent?.Invoke(item, -Math.Min(currentCount, -count)); + FinalChangeElementEvent?.Invoke(item, GetCount(item)); + } + + public int GetCount(TItem item) + => _container.GetValueOrDefault(item, 0); + + public IEnumerable GetItems() + { + return _container.Keys; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/CountedStorage/BaseCountedStorage.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/CountedStorage/BaseCountedStorage.cs.meta new file mode 100644 index 0000000..7f01f27 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/CountedStorage/BaseCountedStorage.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b628585ab12d4d6fbe350e60cb548320 +timeCreated: 1726208744 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/CountedStorage/ICountedStorage.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/CountedStorage/ICountedStorage.cs new file mode 100644 index 0000000..70e57c2 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/CountedStorage/ICountedStorage.cs @@ -0,0 +1,14 @@ +using System.Collections.Generic; +using RedCatEngine.CommonServices.Containers.Storages.BaseStorage; + +namespace RedCatEngine.CommonServices.Containers.Storages.CountedStorage +{ + public interface ICountedStorage : IStorage + { + int GetCount(TItem item); + IEnumerable GetItems(); + bool IsContain(TItem item, int count); + void Add(TItem item, int count); + void Remove(TItem item, int count); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/CountedStorage/ICountedStorage.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/CountedStorage/ICountedStorage.cs.meta new file mode 100644 index 0000000..2ed954c --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/CountedStorage/ICountedStorage.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a143833dab874777a7548998f59f6a9f +timeCreated: 1726208628 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items.meta new file mode 100644 index 0000000..104ae9d --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4c0c8b6488834a87b31f45269c92343f +timeCreated: 1726208365 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/BaseLevelItemStorage.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/BaseLevelItemStorage.cs new file mode 100644 index 0000000..0cd2d1d --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/BaseLevelItemStorage.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; +using RedCatEngine.CommonServices.Containers.Storages.CountedStorage; + +namespace RedCatEngine.CommonServices.Containers.Storages.Items +{ + public class BaseLevelItemStorage : BaseCountedStorage, IItemStorage + where TItem : BaseItemConfig + { + private const int DefaultLevel = 1; + + private readonly Dictionary _levels = new(); + + public int GetLevel(TItem item) + => _levels.GetValueOrDefault(item, DefaultLevel); + + public void SetLevel(TItem item, int level) + { + if (_levels.TryGetValue(item, out _)) + _levels[item] = level; + else + _levels.Add(item, level); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/BaseLevelItemStorage.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/BaseLevelItemStorage.cs.meta new file mode 100644 index 0000000..2e15a3d --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/BaseLevelItemStorage.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3c6e37bcc57d4509a02d7be21092f1cf +timeCreated: 1726208420 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/DummyItemStorage.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/DummyItemStorage.cs new file mode 100644 index 0000000..a2bd6b5 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/DummyItemStorage.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; + +namespace RedCatEngine.CommonServices.Containers.Storages.Items +{ + public class DummyItemStorage : IItemStorage + { + public static DummyItemStorage Empty + => new(); + + public event Action DeltaChangeElementEvent; + public event Action FinalChangeElementEvent; + public event Action ClearEvent; + + private DummyItemStorage() { } + + public IEnumerable GetElements() + { + return ArraySegment.Empty; + } + + public void Add(BaseItemConfig item) { } + + public bool IsContain(BaseItemConfig item) + { + return false; + } + + public bool IsContainAny(IEnumerable itemsForCheck) + { + return false; + } + + public void Clear() + { + ClearEvent?.Invoke(); + } + + public void Remove(BaseItemConfig item) + { + DeltaChangeElementEvent?.Invoke(item, 0); + FinalChangeElementEvent?.Invoke(item, 0); + } + + public int GetCount(BaseItemConfig item) + { + return 0; + } + + public IEnumerable GetItems() + { + return Array.Empty(); + } + + public bool IsContain(BaseItemConfig item, int count) + { + return false; + } + + public void Add(BaseItemConfig item, int count) + { + DeltaChangeElementEvent?.Invoke(item, 0); + FinalChangeElementEvent?.Invoke(item, 0); + } + + public void Remove(BaseItemConfig item, int count) + { + DeltaChangeElementEvent?.Invoke(item, 0); + FinalChangeElementEvent?.Invoke(item, 0); + } + + public int GetLevel(BaseItemConfig item) + { + return 1; + } + + public void SetLevel(BaseItemConfig item, int level) { } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/DummyItemStorage.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/DummyItemStorage.cs.meta new file mode 100644 index 0000000..2383d2a --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/DummyItemStorage.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 23ba3faf078845859f5944e45e3b0335 +timeCreated: 1726231329 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/ExpireTimeItemConfig.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/ExpireTimeItemConfig.cs new file mode 100644 index 0000000..ed98525 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/ExpireTimeItemConfig.cs @@ -0,0 +1,7 @@ +namespace RedCatEngine.CommonServices.Containers.Storages.Items +{ + public class ExpireTimeItemConfig : BaseItemConfig + { + + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/ExpireTimeItemConfig.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/ExpireTimeItemConfig.cs.meta new file mode 100644 index 0000000..481563e --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/ExpireTimeItemConfig.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 44314373fccf43c88aebf9ef1d6ff549 +timeCreated: 1726208444 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/IItemStorage.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/IItemStorage.cs new file mode 100644 index 0000000..8104eb8 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/IItemStorage.cs @@ -0,0 +1,11 @@ +using RedCatEngine.CommonServices.Containers.Storages.CountedStorage; + +namespace RedCatEngine.CommonServices.Containers.Storages.Items +{ + public interface IItemStorage : ICountedStorage + where TItem : BaseItemConfig + { + int GetLevel(TItem item); + void SetLevel(TItem item, int level); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/IItemStorage.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/IItemStorage.cs.meta new file mode 100644 index 0000000..a4e6b02 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/IItemStorage.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c83f3738b5cc4b93a39225a6cd400f8d +timeCreated: 1726208391 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/ItemConfig.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/ItemConfig.cs new file mode 100644 index 0000000..a3370b0 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/ItemConfig.cs @@ -0,0 +1,9 @@ +using RedCatEngine.Configs; + +namespace RedCatEngine.CommonServices.Containers.Storages.Items +{ + public class BaseItemConfig : BaseConfig + { + + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/ItemConfig.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/ItemConfig.cs.meta new file mode 100644 index 0000000..7c7afec --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Items/ItemConfig.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b2f60f54b8b443ebb9d52c2b4807ae7e +timeCreated: 1726208374 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags.meta new file mode 100644 index 0000000..ffc9dcf --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ded545ac32684038a1ada2f303d7b2b7 +timeCreated: 1726150378 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags/ITagStorage.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags/ITagStorage.cs new file mode 100644 index 0000000..516812f --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags/ITagStorage.cs @@ -0,0 +1,8 @@ +using RedCatEngine.CommonServices.Containers.Storages.CountedStorage; + +namespace RedCatEngine.CommonServices.Containers.Storages.Tags +{ + public interface ITagStorage : ICountedStorage + { + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags/ITagStorage.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags/ITagStorage.cs.meta new file mode 100644 index 0000000..d5c0379 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags/ITagStorage.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: af80274377ec43aabc17cd4178b12ba2 +timeCreated: 1726150408 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags/TagConfig.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags/TagConfig.cs new file mode 100644 index 0000000..eec8d6d --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags/TagConfig.cs @@ -0,0 +1,11 @@ +using RedCatEngine.Configs; +using UnityEngine; + +namespace RedCatEngine.CommonServices.Containers.Storages.Tags +{ + [CreateAssetMenu(menuName = "Configs/Common/Tags/Tag", fileName = nameof(TagConfig))] + public class TagConfig : BaseConfig + { + + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags/TagConfig.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags/TagConfig.cs.meta new file mode 100644 index 0000000..8be760c --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags/TagConfig.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 226e2877deeb44f6b185171fe8a7c0d0 +timeCreated: 1726150421 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags/TagStorage.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags/TagStorage.cs new file mode 100644 index 0000000..44d581b --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags/TagStorage.cs @@ -0,0 +1,8 @@ +using RedCatEngine.CommonServices.Containers.Storages.CountedStorage; + +namespace RedCatEngine.CommonServices.Containers.Storages.Tags +{ + public class TagStorage : BaseCountedStorage, ITagStorage + { + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags/TagStorage.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags/TagStorage.cs.meta new file mode 100644 index 0000000..a454c8c --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/Tags/TagStorage.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3ad68c232d2f4f9385f8084d55e28518 +timeCreated: 1726150399 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage.meta new file mode 100644 index 0000000..5644431 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ebd5dc0d7c814c8abf7bc5c6ea69dd9b +timeCreated: 1726663679 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/ConditionTypedStorage.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/ConditionTypedStorage.cs new file mode 100644 index 0000000..b157de2 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/ConditionTypedStorage.cs @@ -0,0 +1,11 @@ +namespace RedCatEngine.CommonServices.Containers.Storages.TypedStorage +{ + public class ConditionTypedStorage : TypedStorage + { + protected override void AddToDictionary(TType item) + { + if(item is TBaseType) + base.AddToDictionary(item); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/ConditionTypedStorage.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/ConditionTypedStorage.cs.meta new file mode 100644 index 0000000..4dfd5e0 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/ConditionTypedStorage.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: eb55543f7ad14fc4bb3aa26f02703f85 +timeCreated: 1726664147 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/DynamicTypedStorage.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/DynamicTypedStorage.cs new file mode 100644 index 0000000..0335644 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/DynamicTypedStorage.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace RedCatEngine.CommonServices.Containers.Storages.TypedStorage +{ + public class DynamicTypedStorage : ITypedStorage + { + private readonly List _items = new(); + + public event Action AddNewElementEvent; + public event Action RemoveElementEvent; + + public event Action ClearEvent; + + public bool TryGets(out IEnumerable result) + { + result = _items.Where(item => item is TType).Cast(); + return result.Any(); + } + + public bool TryGet(out TType result) + { + var isContain = TryGets(out var collect); + result = isContain ? collect.First() : default; + return isContain; + } + + public IEnumerable Gets() + { + return TryGets(out var result) + ? result + : Array.Empty(); + } + + public void Add(TType item) + { + if (item is not TBaseTypeStorage baseType) + return; + + _items.Add(baseType); + AddNewElementEvent?.Invoke(item); + } + + public bool IsContain() + => _items.Any(item => item is TType); + + public void Clear() + { + _items.Clear(); + ClearEvent?.Invoke(); + } + + public void Remove() + { + _items.RemoveAll(item => item is TType); + } + + public void Remove(TBaseTypeStorage itemToRemove) + { + if (_items.Contains(itemToRemove)) + _items.Remove(itemToRemove); + RemoveElementEvent?.Invoke(); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/DynamicTypedStorage.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/DynamicTypedStorage.cs.meta new file mode 100644 index 0000000..a1ed1b4 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/DynamicTypedStorage.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f1d1f3dd85d84ca3b351dc3dd435371f +timeCreated: 1727796142 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/ITypedStorage.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/ITypedStorage.cs new file mode 100644 index 0000000..dbfb9f1 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/ITypedStorage.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; + +namespace RedCatEngine.CommonServices.Containers.Storages.TypedStorage +{ + public interface ITypedStorage + { + event Action AddNewElementEvent; + event Action ClearEvent; + bool TryGet(out TType result); + bool TryGets(out IEnumerable result); + IEnumerable Gets(); + + public void Add(TType item); + bool IsContain(); + void Clear(); + public void Remove(); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/ITypedStorage.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/ITypedStorage.cs.meta new file mode 100644 index 0000000..b685d32 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/ITypedStorage.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 166a6f8b5cc24cf5b70d50471f95d951 +timeCreated: 1726663713 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/TypedStorage.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/TypedStorage.cs new file mode 100644 index 0000000..07f46ce --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/TypedStorage.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace RedCatEngine.CommonServices.Containers.Storages.TypedStorage +{ + public class TypedStorage : ITypedStorage + { + private readonly Dictionary> _items = new(); + + public event Action AddNewElementEvent; + + public event Action ClearEvent; + + protected virtual void AddToDictionary(TType item) + { + if (!_items.TryGetValue(typeof(TType), out var elementsList)) + { + elementsList = new List(); + _items.Add(typeof(TType), elementsList); + } + + elementsList.Add(item); + AddNewElementEvent?.Invoke(item); + } + + public bool TryGets(out IEnumerable result) + { + var isContain = _items.TryGetValue(typeof(TType), out var collect); + result = isContain ? collect.Cast() : Array.Empty(); + return isContain; + } + + public bool TryGet(out TType result) + { + var isContain = _items.TryGetValue(typeof(TType), out var collect) && collect.Any(); + if(isContain) + result = (TType)collect.First(); + else + result = default; + return isContain; + } + + public IEnumerable Gets() + { + return _items.TryGetValue(typeof(TType), out var result) + ? result.Cast() + : Array.Empty(); + } + + public void Add(TType item) + => AddToDictionary(item); + + public bool IsContain() + => _items.TryGetValue(typeof(TType), out var items) && items.Any(); + + public void Clear() + { + _items.Clear(); + ClearEvent?.Invoke(); + } + + public void Remove() + { + if (_items.TryGetValue(typeof(TType), out var items)) + items.Clear(); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/TypedStorage.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/TypedStorage.cs.meta new file mode 100644 index 0000000..167ed27 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Containers/Storages/TypedStorage/TypedStorage.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: bbc96e499ff5416497c6023adeb58aef +timeCreated: 1726663670 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions.meta new file mode 100644 index 0000000..fbbda3e --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2ab78bb0e0af428bb32e512c70587baa +timeCreated: 1726497473 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/AnimationCurveExtensions.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/AnimationCurveExtensions.cs new file mode 100644 index 0000000..2cad94e --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/AnimationCurveExtensions.cs @@ -0,0 +1,43 @@ +using System; +using System.Linq; +using UnityEngine; + +namespace RedCatEngine.CommonServices.Extensions +{ + public static class AnimationCurveExtensions + { + public enum GetCurveType + { + Duplication = 1, + Clamp = 2 + } + + public static float GetValue( + this AnimationCurve animationCurve, + float x, + GetCurveType curveType = GetCurveType.Clamp + ) + { + var minXValue = animationCurve.keys.First().time; + var maxXValue = animationCurve.keys.Last().time; + switch (curveType) + { + case GetCurveType.Duplication: + var absMax = Mathf.Abs(minXValue); + var absMin = Mathf.Abs(maxXValue); + + while (x > maxXValue) + x -= absMax; + while (x < minXValue) + x += absMin; + + return animationCurve.Evaluate(x); + case GetCurveType.Clamp: + x = Mathf.Clamp(x, minXValue, maxXValue); + return animationCurve.Evaluate(x); + default: + throw new ArgumentOutOfRangeException(nameof(curveType), curveType, null); + } + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/AnimationCurveExtensions.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/AnimationCurveExtensions.cs.meta new file mode 100644 index 0000000..7f1cad2 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/AnimationCurveExtensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4e52b179b1b34fa99cbbed45cac042f7 +timeCreated: 1727101572 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/ArrayExtensions.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/ArrayExtensions.cs new file mode 100644 index 0000000..823ba94 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/ArrayExtensions.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; +using System.Linq; + +namespace RedCatEngine.CommonServices.Extensions +{ + public static class ArrayExtensions + { + public static object[] WrapInArrayAsSingle(this object singleObject) + => new[] { singleObject }; + + public static object[] Attach(this object[] array, T value) + => array.Union(new object[] { value }).ToArray(); + + public static object[] Attach(this object[] array, params object[] values) + => array.Union(values).ToArray(); + + public static object[] AttachAsSingle(this object[] array, T[] value) + => array.Union(new[] { value }).ToArray(); + + public static object[] AttachAsSingle(this object[] array, List value) + => array.Union(new[] { value }).ToArray(); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/ArrayExtensions.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/ArrayExtensions.cs.meta new file mode 100644 index 0000000..84b581a --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/ArrayExtensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: bd5d4f215d454167b4c26b5c07a878e1 +timeCreated: 1735392179 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/Editor.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/Editor.meta new file mode 100644 index 0000000..c16b9ac --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/Editor.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a3dc5419ea0b4ed092869b725cfeacf0 +timeCreated: 1735040940 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/Editor/EditorHelper.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/Editor/EditorHelper.cs new file mode 100644 index 0000000..666b3fd --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/Editor/EditorHelper.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +namespace RedCatEngine.CommonServices.Extensions.Editor +{ +#if UNITY_EDITOR + public class EditorHelper + { + public static List FindAssetsByType() where T : Object + { + var assets = new List(); + var guids = AssetDatabase.FindAssets("t:" + typeof(T).Name); + foreach (var guid in guids) + { + var assetPath = AssetDatabase.GUIDToAssetPath(guid); + var asset = AssetDatabase.LoadAssetAtPath(assetPath); + if (asset != null) + assets.Add(asset); + } + return assets; + } + } +#endif +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/Editor/EditorHelper.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/Editor/EditorHelper.cs.meta new file mode 100644 index 0000000..050700d --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/Editor/EditorHelper.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 60597ebb70d742f498f4a839103ed71c +timeCreated: 1735040952 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/EditorExtensions.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/EditorExtensions.cs new file mode 100644 index 0000000..beb29e7 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/EditorExtensions.cs @@ -0,0 +1,10 @@ +using UnityEngine; + +namespace RedCatEngine.CommonServices.Extensions +{ + public static class EditorExtensions + { + public static bool IsPrefab(this GameObject go) + => go.scene.rootCount == 0; + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/EditorExtensions.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/EditorExtensions.cs.meta new file mode 100644 index 0000000..5deb13d --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/EditorExtensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2519c922d98a4730a8aa20c3f00f3834 +timeCreated: 1730459347 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/GameObjectExtensions.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/GameObjectExtensions.cs new file mode 100644 index 0000000..285c3f0 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/GameObjectExtensions.cs @@ -0,0 +1,21 @@ +using UnityEngine; + +namespace RedCatEngine.CommonServices.Extensions +{ + public static class GameObjectExtensions + { + public static bool IsHasComponent(this MonoBehaviour otherComponent, out TBehaviour component) + where TBehaviour : MonoBehaviour + { + component = null; + return otherComponent != null && otherComponent.gameObject.TryGetComponent(out component); + } + + public static bool IsHasComponent(this GameObject gameObject, out TBehaviour component) + where TBehaviour : MonoBehaviour + { + component = null; + return gameObject != null && gameObject.TryGetComponent(out component); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/GameObjectExtensions.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/GameObjectExtensions.cs.meta new file mode 100644 index 0000000..d75d63e --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/GameObjectExtensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: e32539869c6a4fc6b9e1759a01ed8848 +timeCreated: 1753775737 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/GizmosExtensions.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/GizmosExtensions.cs new file mode 100644 index 0000000..595f796 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/GizmosExtensions.cs @@ -0,0 +1,199 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace RedCatEngine.CommonServices.Extensions +{ + public static class GizmosExtensions + { + public static void DrawCube( + Vector3 a, + Vector3 b, + Color color + ) + { + Gizmos.color = color; + Gizmos.DrawLine( + a, + new Vector3( + a.x, + b.y, + a.z)); + Gizmos.DrawLine( + a, + new Vector3( + a.x, + a.y, + b.z)); + Gizmos.DrawLine( + a, + new Vector3( + b.x, + a.y, + a.z)); + + Gizmos.DrawLine( + b, + new Vector3( + b.x, + a.y, + b.z)); + Gizmos.DrawLine( + b, + new Vector3( + b.x, + b.y, + a.z)); + Gizmos.DrawLine( + b, + new Vector3( + a.x, + b.y, + b.z)); + + Gizmos.DrawLine( + new Vector3( + a.x, + b.y, + a.z), + new Vector3( + b.x, + b.y, + a.z)); + Gizmos.DrawLine( + new Vector3( + a.x, + b.y, + a.z), + new Vector3( + a.x, + b.y, + b.z)); + Gizmos.DrawLine( + new Vector3( + a.x, + a.y, + b.z), + new Vector3( + a.x, + b.y, + b.z)); + Gizmos.DrawLine( + new Vector3( + b.x, + a.y, + a.z), + new Vector3( + b.x, + a.y, + b.z)); + Gizmos.DrawLine( + new Vector3( + a.x, + a.y, + b.z), + new Vector3( + b.x, + a.y, + b.z)); + Gizmos.DrawLine( + new Vector3( + b.x, + a.y, + a.z), + new Vector3( + b.x, + b.y, + a.z)); + } + + public static void DrawBox( + Vector2 a, + Vector2 b, + Color color + ) + { + Gizmos.color = color; + Gizmos.DrawLine( + new Vector2( + a.x, + a.y), + new Vector2( + a.x, + b.y)); + Gizmos.DrawLine( + new Vector2( + a.x, + a.y), + new Vector2( + b.x, + a.y)); + Gizmos.DrawLine( + new Vector2( + b.x, + b.y), + new Vector2( + a.x, + b.y)); + Gizmos.DrawLine( + new Vector2( + b.x, + b.y), + new Vector2( + b.x, + a.y)); + } + + public static void DrawBox( + Vector3 a, + Vector3 b, + Vector3 shift, + Color color + ) + { + Gizmos.color = color; + a = new Vector3(a.x + shift.x, a.y + shift.y); + b = new Vector3(b.x + shift.x, b.y + shift.y); + Gizmos.DrawLine( + new Vector2( + a.x, + a.y), + new Vector2( + a.x, + b.y)); + Gizmos.DrawLine( + new Vector2( + a.x, + a.y), + new Vector2( + b.x, + a.y)); + Gizmos.DrawLine( + new Vector2( + b.x, + b.y), + new Vector2( + a.x, + b.y)); + Gizmos.DrawLine( + new Vector2( + b.x, + b.y), + new Vector2( + b.x, + a.y)); + } + + public static void DrawLinks( + Component from, + IEnumerable to, + Color color + ) + { + Gizmos.color = color; + foreach (var target in to) + { + Gizmos.DrawLine(from.transform.position, target.transform.position); + } + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/GizmosExtensions.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/GizmosExtensions.cs.meta new file mode 100644 index 0000000..17e0629 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/GizmosExtensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 55e89c4a10e84d6ba009a294cb3e7734 +timeCreated: 1726497490 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/PhysicsExtensions.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/PhysicsExtensions.cs new file mode 100644 index 0000000..3053aeb --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/PhysicsExtensions.cs @@ -0,0 +1,12 @@ +using UnityEngine; + +namespace RedCatEngine.CommonServices.Extensions +{ + public static class PhysicsExtensions + { + public static bool CompareLayer(this LayerMask layermask, int layer) + { + return layermask == (layermask | (1 << layer)); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/PhysicsExtensions.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/PhysicsExtensions.cs.meta new file mode 100644 index 0000000..89a335b --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/PhysicsExtensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9ef6b66d5106454d8346df4b19afec44 +timeCreated: 1751400289 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/StringExtensions.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/StringExtensions.cs new file mode 100644 index 0000000..76c3fbe --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/StringExtensions.cs @@ -0,0 +1,41 @@ +namespace RedCatEngine.CommonServices.Extensions +{ + public static class StringExtensions + { + public static string FormatWith(this string value, params object[] args) + => string.Format(value, args); + + public static bool IsNullOrEmpty(this string value) + { + return string.IsNullOrEmpty(value); + } + + public static bool IsNullOrWhiteSpace(this string value) + { + return string.IsNullOrWhiteSpace(value); + } + + public static bool IsNullOrWhitespace(this string value) + { + return string.IsNullOrWhiteSpace(value); + } + + public static bool IsNotNullOrEmpty(this string value) + { + return !IsNullOrEmpty(value); + } + + public static int SizeOfMemory(this string value) + { + return 26 + 2 * value.Length; + } + public static float SizeOfMemoryKb(this string value) + { + return (float)value.SizeOfMemory() / 1024; + } + public static float SizeOfMemoryMb(this string value) + { + return value.SizeOfMemoryKb() / 1024; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/StringExtensions.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/StringExtensions.cs.meta new file mode 100644 index 0000000..a289d55 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/StringExtensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f46a40ccf08b44a8a762cafaa67101a3 +timeCreated: 1730286647 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/VectorsExtensions.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/VectorsExtensions.cs new file mode 100644 index 0000000..a4c1da3 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/VectorsExtensions.cs @@ -0,0 +1,35 @@ +using UnityEngine; + +namespace RedCatEngine.CommonServices.Extensions +{ + public static class VectorsExtensions + { + public static Vector2 NewWithX(this Vector2 baseValue, float xValue) + => new( + xValue, + baseValue.y); + + public static Vector2 NewWithY(this Vector2 baseValue, float yValue) + => new( + baseValue.x, + yValue); + + public static Vector3 NewWithX(this Vector3 baseValue, float xValue) + => new( + xValue, + baseValue.y, + baseValue.z); + + public static Vector3 NewWithY(this Vector3 baseValue, float yValue) + => new( + baseValue.x, + yValue, + baseValue.z); + + public static Vector3 NewWithZ(this Vector3 baseValue, float zValue) + => new( + baseValue.x, + baseValue.y, + zValue); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/VectorsExtensions.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/VectorsExtensions.cs.meta new file mode 100644 index 0000000..fc590fb --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Extensions/VectorsExtensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 73d591c624d5453fa4f656d141be12d8 +timeCreated: 1734522681 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Factories.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Factories.meta new file mode 100644 index 0000000..d035f10 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Factories.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b5cb61d590c840248539d6bd1e91ba50 +timeCreated: 1731077185 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Factories/DiInstanceCreator.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Factories/DiInstanceCreator.cs new file mode 100644 index 0000000..62bbb85 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Factories/DiInstanceCreator.cs @@ -0,0 +1,39 @@ +using RedCatEngine.DependencyInjection.Containers.Interfaces.Unity; +using RedCatEngine.Pools.Containers.Creators.InstanceCreator; +using RedCatEngine.Pools.Pools; +using UnityEngine; + +namespace RedCatEngine.CommonServices.Factories +{ + public class DiInstanceCreator : IInstanceCreator + { + private readonly IUnityGameContainer _container; + private readonly GameObject _prefab; + private readonly Transform _parent; + + public DiInstanceCreator( + IUnityGameContainer container, + GameObject prefab, + Transform parent + ) + { + _container = container; + _prefab = prefab; + _parent = parent; + } + + public IPooledObject Create(params object[] context) + { + var instance = _container.Create( + _prefab, + _parent, + context: context); + if (instance.TryGetComponent(out var pooledObject)) + return pooledObject; + + var collector = instance.AddComponent(); + collector.CollectPooledComponents(); + return collector; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Factories/DiInstanceCreator.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Factories/DiInstanceCreator.cs.meta new file mode 100644 index 0000000..9cea8be --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Factories/DiInstanceCreator.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c50c5b22ae1446098b15ff7826e281be +timeCreated: 1731077214 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Factories/DiPoolInstanceCreatorFactory.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Factories/DiPoolInstanceCreatorFactory.cs new file mode 100644 index 0000000..6274ca8 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Factories/DiPoolInstanceCreatorFactory.cs @@ -0,0 +1,21 @@ +using RedCatEngine.DependencyInjection.Containers.Attributes; +using RedCatEngine.DependencyInjection.Containers.Interfaces.Unity; +using RedCatEngine.Pools.Containers.Creators.Factories; +using RedCatEngine.Pools.Containers.Creators.InstanceCreator; +using UnityEngine; + +namespace RedCatEngine.CommonServices.Factories +{ + public class DiPoolInstanceCreatorFactory : IPoolInstanceCreatorFactory + { + private readonly IUnityGameContainer _container; + + [Inject] + public DiPoolInstanceCreatorFactory(IUnityGameContainer container) + { + _container = container; + } + public IInstanceCreator Make(GameObject prefab, Transform parent) + => new DiInstanceCreator(_container, prefab, parent); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Factories/DiPoolInstanceCreatorFactory.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Factories/DiPoolInstanceCreatorFactory.cs.meta new file mode 100644 index 0000000..0b65b8c --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Factories/DiPoolInstanceCreatorFactory.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 5195842804d14498b6276bfdab2d75a2 +timeCreated: 1731077193 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services.meta new file mode 100644 index 0000000..5dac9c9 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 0ebc37fbab794d1cbd6655501f777fe5 +timeCreated: 1726149876 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Callbacks.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Callbacks.meta new file mode 100644 index 0000000..e9781ac --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Callbacks.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c784c0aadea54592a9b9d6e15fdcfb72 +timeCreated: 1733501295 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Callbacks/DisposableCallback.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Callbacks/DisposableCallback.cs new file mode 100644 index 0000000..05efb88 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Callbacks/DisposableCallback.cs @@ -0,0 +1,83 @@ +using System; + +namespace RedCatEngine.CommonServices.Services.Callbacks +{ + /// + /// Обёртка над , которая позволяет вызвать действие один раз и/или при освобождении ресурсов. + /// + public class DisposableCallback : IDisposable + { + /// + /// Действие, которое будет выполнено. + /// + private Action _callback; + + /// + /// Флаг, указывающий, должно ли действие быть вызвано при освобождении (). + /// + private readonly bool _invokeOnDispose; + + /// + /// Флаг, указывающий, было ли уже вызвано действие. + /// + private bool _isDisposed; + + /// + /// Возвращает значение, указывающее, включён ли callback и может ли он быть вызван. + /// + public bool IsEnable { get; private set; } + + /// + /// Инициализирует новый экземпляр класса . + /// + /// Действие, которое будет выполнено. + /// , если действие должно быть вызвано при вызове . + public DisposableCallback(Action callback, bool invokeOnDispose) + { + _callback = callback; + _invokeOnDispose = invokeOnDispose; + IsEnable = true; + } + + /// + /// Вызывает сохранённое действие, если оно ещё не было вызвано. + /// + public void Invoke() + { + var callback = _callback; + _callback = null; + callback?.Invoke(); + IsEnable = false; + } + + /// + /// Освобождает ресурсы, связанные с этим объектом. + /// Если установлен в , вызывает действие перед освобождением. + /// + public void Dispose() + { + if (_isDisposed) + return; + + if (_invokeOnDispose) + { + Invoke(); + } + else + { + IsEnable = false; + _callback = null; + } + + _isDisposed = true; + DoDispose(); + } + + /// + /// Метод для расширения логики освобождения ресурсов в производных классах. + /// + protected virtual void DoDispose() + { + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Callbacks/DisposableCallback.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Callbacks/DisposableCallback.cs.meta new file mode 100644 index 0000000..945be87 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Callbacks/DisposableCallback.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b7b3ca4bc05e46e896770738f2a62f16 +timeCreated: 1733501307 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Callbacks/DisposableTimerCallback.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Callbacks/DisposableTimerCallback.cs new file mode 100644 index 0000000..7750882 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Callbacks/DisposableTimerCallback.cs @@ -0,0 +1,70 @@ +using System; +using RedCatEngine.CommonServices.Services.Times.TimeServices; +using RedCatEngine.DependencyInjection.Containers.Attributes; + +namespace RedCatEngine.CommonServices.Services.Callbacks +{ + /// + /// Обёртка над , которая вызывает действие после истечения заданного времени. + /// Использует для отсчёта времени. + /// + public class DisposableTimerCallback : DisposableCallback + { + /// + /// Служба времени, используемая для отсчёта таймера. + /// + private readonly ITimeService _timeService; + + /// + /// Общее время таймера в секундах. + /// + private readonly float _timer; + public float TimeLeft + => _timer - _time; + + /// + /// Текущее прошедшее время с начала таймера. + /// + private float _time; + + /// + /// Инициализирует новый экземпляр класса . + /// + /// Длительность таймера в секундах. + /// Действие, которое будет вызвано по истечении таймера. + /// , если действие должно быть вызвано при вызове . + [Inject] + public DisposableTimerCallback( + float timer, + Action callback, + bool invokeOnDispose + ) + : base(callback, invokeOnDispose) + { + _timer = timer; + } + + /// + /// Вызывается каждый кадр для обновления таймера. + /// Если время истекло, вызывается и объект уничтожается. + /// + /// Время, прошедшее с последнего кадра. + public void OnUpdate(float deltaTime) + { + _time += deltaTime; + if (_time < _timer) + return; + Invoke(); + Dispose(); + } + + /// + /// Освобождает ресурсы и завершает таймер. + /// Устанавливает прошедшее время равным общему времени таймера. + /// + protected override void DoDispose() + { + _time = _timer; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Callbacks/DisposableTimerCallback.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Callbacks/DisposableTimerCallback.cs.meta new file mode 100644 index 0000000..e193378 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Callbacks/DisposableTimerCallback.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 93c02fc9025e4768807ccda71f8a1422 +timeCreated: 1733501445 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/DisposableCallbacks.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/DisposableCallbacks.meta new file mode 100644 index 0000000..0345d17 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/DisposableCallbacks.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 21d39bd2fe3f4ace8d210dc75082c9db +timeCreated: 1728914860 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/DisposableCallbacks/DisposableCallbackService.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/DisposableCallbacks/DisposableCallbackService.cs new file mode 100644 index 0000000..fce08a5 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/DisposableCallbacks/DisposableCallbackService.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using RedCatEngine.CommonServices.Services.Callbacks; +using RedCatEngine.CommonServices.Services.Times.TimeServices; +using RedCatEngine.DependencyInjection.Containers.Attributes; + +namespace RedCatEngine.CommonServices.Services.DisposableCallbacks +{ + public class DisposableCallbackService : IDisposableCallbackService, IDisposable + { + private readonly List _disposable = new(); + private readonly List _timers = new(); + private readonly ITimeService _timeService; + + [Inject] + public DisposableCallbackService(ITimeService timeService) + { + _timeService = timeService; + _timeService.UpdateEvent += OnUpdate; + } + + public void Dispose() + { + _timeService.UpdateEvent -= OnUpdate; + foreach (var disposableTimerCallback in _timers) + disposableTimerCallback.Dispose(); + foreach (var disposableCallback in _disposable) + disposableCallback.Dispose(); + } + + public DisposableTimerCallback MakeTimerCallback(float time, Action callback) + { + var timerCallback = new DisposableTimerCallback(time, callback, false); + _timers.Add(timerCallback); + return timerCallback; + } + + public DisposableTimerCallback MakeAlwaysInvokeTimerCallback(float time, Action callback) + { + var timerCallback = new DisposableTimerCallback(time, callback, true); + _timers.Add(timerCallback); + return timerCallback; + } + + public DisposableCallback MakeCallback(Action callback) + { + var disposableCallback = new DisposableCallback(callback, false); + _disposable.Add(disposableCallback); + return disposableCallback; + } + + public DisposableCallback MakeAlwaysInvokeCallback(Action callback) + { + var disposableCallback = new DisposableCallback(callback, true); + _disposable.Add(disposableCallback); + return disposableCallback; + } + + private void OnUpdate(float deltaTime) + { + var currentFrameTimers = _timers.ToArray(); + foreach (var timerDisposableCallback in currentFrameTimers) + { + if (timerDisposableCallback == null) + continue; + timerDisposableCallback.OnUpdate(deltaTime); + if (!timerDisposableCallback.IsEnable) + timerDisposableCallback.Invoke(); + } + + _timers.RemoveAll(timer => timer == null || !timer.IsEnable); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/DisposableCallbacks/DisposableCallbackService.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/DisposableCallbacks/DisposableCallbackService.cs.meta new file mode 100644 index 0000000..6269ecf --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/DisposableCallbacks/DisposableCallbackService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f287e80b766c4450bfbb9f0fd972fc40 +timeCreated: 1728914915 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/DisposableCallbacks/IDisposableCallbackService.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/DisposableCallbacks/IDisposableCallbackService.cs new file mode 100644 index 0000000..2fe5b71 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/DisposableCallbacks/IDisposableCallbackService.cs @@ -0,0 +1,13 @@ +using System; +using RedCatEngine.CommonServices.Services.Callbacks; + +namespace RedCatEngine.CommonServices.Services.DisposableCallbacks +{ + public interface IDisposableCallbackService + { + DisposableTimerCallback MakeTimerCallback(float time, Action callback); + DisposableTimerCallback MakeAlwaysInvokeTimerCallback(float time, Action callback); + DisposableCallback MakeCallback(Action callback); + DisposableCallback MakeAlwaysInvokeCallback(Action callback); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/DisposableCallbacks/IDisposableCallbackService.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/DisposableCallbacks/IDisposableCallbackService.cs.meta new file mode 100644 index 0000000..012c679 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/DisposableCallbacks/IDisposableCallbackService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 347aaf6a0c1c4d9ebf50fae9980e8e9c +timeCreated: 1728914870 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs.meta new file mode 100644 index 0000000..e068735 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 20e76a175e0d462eb3ba9750d24b11c7 +timeCreated: 1729161773 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/BaseLogService.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/BaseLogService.cs new file mode 100644 index 0000000..e4945de --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/BaseLogService.cs @@ -0,0 +1,68 @@ +namespace RedCatEngine.CommonServices.Services.Logs +{ + public abstract class BaseLogService : ILogService + { + protected readonly string Tag; + + protected BaseLogService(string tag) + { + Tag = tag; + } + + public void Log(string log) + => DoLog( + string.IsNullOrEmpty(Tag) + ? log + : $"[{Tag}] {log}" + ); + + public void LogWarning(string log) + => DoLogWarning( + string.IsNullOrEmpty(Tag) + ? log + : $"[{Tag}] {log}" + ); + + public void LogError(string log) + => DoLogError( + string.IsNullOrEmpty(Tag) + ? log + : $"[{Tag}] {log}" + ); + + public void LogFormat(string log, params object[] parameters) + { + var logFormat = string.Format(log, parameters); + Log(logFormat); + } + + public void LogWarningFormat(string log, params object[] parameters) + { + var logFormat = string.Format(log, parameters); + LogWarning(logFormat); + } + + public void LogErrorFormat(string log, params object[] parameters) + { + var logFormat = string.Format(log, parameters); + LogError(logFormat); + } + + public ILogService CreateTag() + => CreateTag(typeof(TType).Name); + + public ILogService CreateTag(string tag) + { + var tagForInstance = string.IsNullOrEmpty(Tag) + ? tag + : $"{Tag}:{tag}"; + return DoCreateInstance(tagForInstance); + } + + protected abstract ILogService DoCreateInstance(string tag); + + protected abstract void DoLog(string log); + protected abstract void DoLogWarning(string log); + protected abstract void DoLogError(string log); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/BaseLogService.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/BaseLogService.cs.meta new file mode 100644 index 0000000..12c1c19 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/BaseLogService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 14430286fbdf41f4ad6eb680ac794d56 +timeCreated: 1729162420 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/ILogService.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/ILogService.cs new file mode 100644 index 0000000..02c009f --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/ILogService.cs @@ -0,0 +1,18 @@ +using UnityEngine; + +namespace RedCatEngine.CommonServices.Services.Logs +{ + public interface ILogService + { + ILogService CreateTag(string tag); + ILogService CreateTag(); + void Log(string log); + void LogWarning(string log); + void LogError(string log); + void LogFormat(string log, params object[] parameters); + void LogWarningFormat(string log, params object[] parameters); + void LogErrorFormat(string log, params object[] parameters); + public ILogService CreateTag(GameObject gameObject) + => CreateTag(gameObject.name); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/ILogService.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/ILogService.cs.meta new file mode 100644 index 0000000..e5d5e9a --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/ILogService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 1513d60fde784482af8451be0ac9900c +timeCreated: 1729161777 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor.meta new file mode 100644 index 0000000..47033f3 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c465d2287c9548888946d6bf7042c965 +timeCreated: 1754682256 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/TagNode.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/TagNode.cs new file mode 100644 index 0000000..7947eeb --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/TagNode.cs @@ -0,0 +1,147 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; + +namespace RedCatEngine.CommonServices.Services.Logs.UnityEditor +{ + /// + /// Вспомогательный класс‑узел для построения иерархии тегов. + /// + internal sealed class TagNode + { + /// Имя узла (последняя часть пути). + public string Name { get; } + + /// Полный путь, как в исходном списке. + public string FullPath { get; } + + public int Depth { get; } + + /// Список дочерних узлов. + public readonly List Children = new(); + + public TagNode(string name, string fullPath) + { + Name = name; + FullPath = fullPath; + Depth = FullPath.Split(':').Length - 1; + } + } + + /// + /// Класс‑помощник для работы с иерархией тегов в редакторе. + /// + internal static class HierarchicalTagDrawer + { +#if UNITY_EDITOR + /// + /// Построить дерево из списка строк‑путей. + /// + private static TagNode BuildTree(IEnumerable tags) + { + var root = new TagNode(string.Empty, string.Empty); + + foreach (var tag in tags) + { + // Разбиваем путь на части + var parts = tag.Split(':'); + var current = root; + string pathSoFar = string.Empty; + + foreach (var part in parts) + { + pathSoFar += (pathSoFar == string.Empty + ? "" + : ":") + + part; + + // Найти существующий дочерний узел + var child = current.Children.FirstOrDefault(c => c.FullPath == pathSoFar); + if (child == null) + { + child = new TagNode(part, pathSoFar); + current.Children.Add(child); + } + + current = child; + } + } + + return root; + } + + /// + /// Сортировать дочерние узлы по имени (можно заменить на любой другой компаратор). + /// + private static void SortChildren(TagNode node) + { + node.Children.Sort((a, b) => string.CompareOrdinal(a.Name, b.Name)); + foreach (var child in node.Children) + SortChildren(child); + } + + /// + /// Получить упорядоченный список тегов с уровнем вложенности. + /// + private static IEnumerable<(string FullPath, int Depth)> GetOrderedTags(TagNode root) + { + var result = new List<(string, int)>(); + + void Traverse(TagNode node) + { + if (!string.IsNullOrEmpty(node.FullPath)) + result.Add((node.FullPath, node.Depth)); + + foreach (var child in node.Children) + Traverse(child); + } + + Traverse(root); + return result; + } + + /// + /// Отрисовать список тегов в редакторе с отступами. + /// + public static void Draw(IEnumerable tags) + { + // 1. Построить дерево + var root = BuildTree(tags); + + // 2. Сортировать узлы + SortChildren(root); + + // 3. Получить упорядоченный список (Depth – количество ':' в пути) + var orderedTags = GetOrderedTags(root).ToList(); + + // 4. Рисуем каждый тег + foreach (var (fullPath, depth) in orderedTags) + { + EditorGUI.indentLevel = depth; // Устанавливаем отступ + + bool isEnabled = UnityEditorLogServiceStaticBridge.IsLogTypeEnabled(fullPath); + bool newState = EditorGUILayout.ToggleLeft(fullPath, isEnabled); + + if (newState != isEnabled) + SetEnable(fullPath, newState); + } + + // Сбросить indentLevel в случае, если дальше рисуется что‑то ещё + EditorGUI.indentLevel = 0; + } + + private static void SetEnable(string tag, bool newState) + { + var needChange = UnityEditorLogServiceStaticBridge.AllTags.Where( + item => !string.IsNullOrEmpty(item) + && item.Contains(tag, StringComparison.OrdinalIgnoreCase) + ); + foreach (var tagItem in needChange) + { + UnityEditorLogServiceStaticBridge.SetEnable(tagItem, newState); + } + } +#endif + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/TagNode.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/TagNode.cs.meta new file mode 100644 index 0000000..e222804 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/TagNode.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d564448cf4c14c30908a32a422d26aeb +timeCreated: 1755023298 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/UnityEditorLogService.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/UnityEditorLogService.cs new file mode 100644 index 0000000..7ffaf21 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/UnityEditorLogService.cs @@ -0,0 +1,43 @@ +namespace RedCatEngine.CommonServices.Services.Logs.UnityEditor +{ + public class UnityEditorLogService : UnityLogService + { + public UnityEditorLogService() + { + } + + protected UnityEditorLogService(string tag) + : base(tag) + { + } + +#if UNITY_EDITOR + private bool IsCanShow() + => UnityEditorLogServiceStaticBridge.IsLogTypeEnabled(Tag); + + protected override void DoLog(string log) + { + if (IsCanShow()) + base.DoLog(log); + } + + protected override void DoLogWarning(string log) + { + if (IsCanShow()) + base.DoLogWarning(log); + } + + protected override void DoLogError(string log) + { + if (IsCanShow()) + base.DoLogError(log); + } + + protected override ILogService DoCreateInstance(string tag) + { + UnityEditorLogServiceStaticBridge.AddLog(tag); + return new UnityEditorLogService(tag); + } +#endif + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/UnityEditorLogService.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/UnityEditorLogService.cs.meta new file mode 100644 index 0000000..c7de3aa --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/UnityEditorLogService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9a6c55a6b2684addb098f1d170d3a5a4 +timeCreated: 1754682245 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/UnityEditorLogServiceStaticBridge.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/UnityEditorLogServiceStaticBridge.cs new file mode 100644 index 0000000..d61921c --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/UnityEditorLogServiceStaticBridge.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using UnityEditor; + +namespace RedCatEngine.CommonServices.Services.Logs.UnityEditor +{ +#if UNITY_EDITOR + public static class UnityEditorLogServiceStaticBridge + { + public static readonly HashSet AllTags = new(); + private static readonly HashSet ShowTags = new(); + private const string PrefsKeyAll = "EditorLogSettingsAllTags"; + private const string PrefsKeyShow = "EditorLogSettingsShowTags"; + + public static bool IsLogTypeEnabled(string logType) + => ShowTags.Contains(logType); + + public static void AddLog(string logType) + { + if (!AllTags.Add(logType)) + return; + ShowTags.Add(logType); + } + + public static void SetEnable(string logType, bool enable) + { + AllTags.Add(logType); + + if (enable) + ShowTags.Add(logType); + else + ShowTags.Remove(logType); + + SaveStates(); + } + + public static void SetAllEnabled(bool enabled) + { + ShowTags.Clear(); + + if (enabled) + { + foreach (var tag in AllTags) + { + ShowTags.Add(tag); + } + } + + SaveStates(); + } + + private static void SaveStates() + { + var data = string.Join(";", ShowTags); + EditorPrefs.SetString(PrefsKeyShow, data); + data = string.Join(";", AllTags); + EditorPrefs.SetString(PrefsKeyAll, data); + } + + public static void LoadStates() + { + if (!EditorPrefs.HasKey(PrefsKeyAll)) + return; + + var allData = EditorPrefs.GetString(PrefsKeyAll, ""); + if (string.IsNullOrEmpty(allData)) + return; + + AllTags.Clear(); + var allTags = allData.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + foreach (var tag in allTags) + AllTags.Add(tag); + + var showData = EditorPrefs.GetString(PrefsKeyAll, ""); + if (string.IsNullOrEmpty(showData)) + return; + + ShowTags.Clear(); + var showTags = showData.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + foreach (var tag in showTags) + ShowTags.Add(tag); + } + } +#endif +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/UnityEditorLogServiceStaticBridge.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/UnityEditorLogServiceStaticBridge.cs.meta new file mode 100644 index 0000000..15de244 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/UnityEditorLogServiceStaticBridge.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 8a9d6a58f4ac4c76aa0788b56c569b66 +timeCreated: 1754682372 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/UnityEditorLogServiceWindow.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/UnityEditorLogServiceWindow.cs new file mode 100644 index 0000000..eb494a7 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/UnityEditorLogServiceWindow.cs @@ -0,0 +1,100 @@ +using System; +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace RedCatEngine.CommonServices.Services.Logs.UnityEditor +{ +#if UNITY_EDITOR + public class UnityEditorLogServiceWindow : EditorWindow + { + private Vector2 _scrollPosition; + private string _searchFilter = ""; + + [MenuItem("Tools/🐛 EditorLog")] + public static void ShowWindow() + { + var window = GetWindow("🐛 Editor Log Settings"); + window.minSize = new Vector2(300, 400); + UnityEditorLogServiceStaticBridge.LoadStates(); + } + + private void OnGUI() + { + DrawSearchField(); + DrawControlButtons(); + DrawTagList(); + } + + private void DrawSearchField() + { + EditorGUILayout.Space(); + EditorGUILayout.LabelField("Log Filter Settings", EditorStyles.boldLabel); + + using (new EditorGUILayout.HorizontalScope()) + { + GUILayout.Label("Search:", GUILayout.Width(50)); + _searchFilter = EditorGUILayout.TextField(_searchFilter); + } + + EditorGUILayout.Space(); + } + + private void DrawControlButtons() + { + using (new EditorGUILayout.HorizontalScope()) + { + if (GUILayout.Button("Select All")) + { + var filteredTags = UnityEditorLogServiceStaticBridge.AllTags + .Where(tag => tag.IndexOf(_searchFilter, StringComparison.OrdinalIgnoreCase) >= 0) + .OrderBy(tag => tag); + + foreach (var tag in filteredTags) + { + SetEnable(tag, true); + } + } + + if (GUILayout.Button("Deselect All")) + { + var filteredTags = UnityEditorLogServiceStaticBridge.AllTags + .Where(tag => tag.IndexOf(_searchFilter, StringComparison.OrdinalIgnoreCase) >= 0) + .OrderBy(tag => tag); + + foreach (var tag in filteredTags) + { + SetEnable(tag, false); + } + } + } + + EditorGUILayout.Space(); + } + + private void DrawTagList() + { + _scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition); + + var filteredTags = UnityEditorLogServiceStaticBridge.AllTags + .Where(tag => tag.IndexOf(_searchFilter, StringComparison.OrdinalIgnoreCase) >= 0) + .OrderBy(tag => tag); + + HierarchicalTagDrawer.Draw(filteredTags); + + EditorGUILayout.EndScrollView(); + } + + private void SetEnable(string tag, bool newState) + { + var needChange = UnityEditorLogServiceStaticBridge.AllTags.Where(item => !string.IsNullOrEmpty(item) + && item.Contains(tag, StringComparison.OrdinalIgnoreCase) + ); + foreach (var tagItem in needChange) + { + UnityEditorLogServiceStaticBridge.SetEnable(tagItem, newState); + } + } + } +#endif +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/UnityEditorLogServiceWindow.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/UnityEditorLogServiceWindow.cs.meta new file mode 100644 index 0000000..f7513d5 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityEditor/UnityEditorLogServiceWindow.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 34724b156f57450892fd724cf397bedd +timeCreated: 1754682273 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityLogService.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityLogService.cs new file mode 100644 index 0000000..5f6c654 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityLogService.cs @@ -0,0 +1,29 @@ +using UnityEngine; + +namespace RedCatEngine.CommonServices.Services.Logs +{ + public class UnityLogService : BaseLogService + { + public UnityLogService() : base(null) + { + } + + protected UnityLogService(string tag) : base(tag) + { + } + + protected override ILogService DoCreateInstance(string tag) + { + return new UnityLogService(tag); + } + + protected override void DoLog(string log) + => Debug.Log(log); + + protected override void DoLogWarning(string log) + => Debug.LogWarning(log); + + protected override void DoLogError(string log) + => Debug.LogError(log); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityLogService.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityLogService.cs.meta new file mode 100644 index 0000000..ecbbab1 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Logs/UnityLogService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 495e242c82b242d5bbecd53ba8d59fba +timeCreated: 1729161848 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices.meta new file mode 100644 index 0000000..232d605 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 04bcf96e3a7b4bc68ba186d5b6b35bf4 +timeCreated: 1727277709 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices/IRandomService.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices/IRandomService.cs new file mode 100644 index 0000000..3bea14d --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices/IRandomService.cs @@ -0,0 +1,11 @@ +namespace RedCatEngine.CommonServices.Services.RandomServices +{ + public interface IRandomService + { + void SetSeed(int seed); + int GetRange(int minInclude, int maxExecute); + float GetRange(float minInclude, float maxExecute); + float ErrorRate(float baseValue, float error); + float ErrorRate(float baseValue, float error, float min, float max); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices/IRandomService.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices/IRandomService.cs.meta new file mode 100644 index 0000000..602f5cc --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices/IRandomService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 53a5c21a116d45f7ac9b9f841e3c9331 +timeCreated: 1727277717 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices/RandomServiceExtensions.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices/RandomServiceExtensions.cs new file mode 100644 index 0000000..6080cb7 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices/RandomServiceExtensions.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; +using System.Linq; + +namespace RedCatEngine.CommonServices.Services.RandomServices +{ + public static class RandomServiceExtensions + { + public static T GetRandomElement(this IRandomService randomService, IEnumerable items) + { + var enumerable = items as T[] ?? items.ToArray(); + var index = randomService.GetRange(0, enumerable.Length); + return enumerable[index]; + } + + /// + /// Возвращает новую последовательность с элементами из inputSequence в случайном порядке (по алгориму Фишера-Йетса). + /// + /// Тип элементов списка + /// Генератор случайных чисел + /// Исходная последовательность + /// Перемешанная последовательность + public static IEnumerable GetShuffle(this IRandomService randomService, IEnumerable inputSequence) + => inputSequence.OrderBy(_ => randomService.GetRange(0, int.MaxValue)); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices/RandomServiceExtensions.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices/RandomServiceExtensions.cs.meta new file mode 100644 index 0000000..966c23f --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices/RandomServiceExtensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2cc350e7aef4412b8586d8ec76c7cadc +timeCreated: 1732285828 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices/UnityRandomService.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices/UnityRandomService.cs new file mode 100644 index 0000000..6258f58 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices/UnityRandomService.cs @@ -0,0 +1,33 @@ +using System; +using UnityEngine; +using Random = UnityEngine.Random; + +namespace RedCatEngine.CommonServices.Services.RandomServices +{ + public class UnityRandomService : IRandomService + { + public void SetSeed(int seed) + { + Random.InitState(seed); + } + + public int GetRange(int minInclude, int maxExecute) + => Random.Range(minInclude, maxExecute); + + public float GetRange(float minInclude, float maxExecute) + => Random.Range(minInclude, maxExecute); + + public float ErrorRate(float baseValue, float error) + => baseValue + Random.Range(-error, error); + + public float ErrorRate( + float baseValue, + float error, + float min, + float max + ) + { + return Mathf.Clamp(ErrorRate(baseValue, error), min, max); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices/UnityRandomService.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices/UnityRandomService.cs.meta new file mode 100644 index 0000000..7399b73 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/RandomServices/UnityRandomService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b910774e92fb493796df82bf7bbfa029 +timeCreated: 1727277745 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices.meta new file mode 100644 index 0000000..47e76fa --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0c848ce0c9962784792a359d5f72e3e9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/DummySoundService.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/DummySoundService.cs new file mode 100644 index 0000000..a543500 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/DummySoundService.cs @@ -0,0 +1,17 @@ +using UnityEngine; + +namespace RedCatEngine.CommonServices.Services.SoundServices +{ + public class DummySoundService : ISoundService + { + public void PlayMusic(AudioClip clip) + { + + } + + public void PlaySfx(AudioClip clip) + { + + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/DummySoundService.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/DummySoundService.cs.meta new file mode 100644 index 0000000..42920e9 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/DummySoundService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: e5c27a18e4194f3ea9462214d3171f1a +timeCreated: 1713986726 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/ISoundContainer.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/ISoundContainer.cs new file mode 100644 index 0000000..7471b2e --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/ISoundContainer.cs @@ -0,0 +1,9 @@ +using UnityEngine; + +namespace RedCatEngine.CommonServices.Services.SoundServices +{ + public interface ISoundContainer + { + void SetClip(AudioClip audioClip); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/ISoundContainer.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/ISoundContainer.cs.meta new file mode 100644 index 0000000..08071c8 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/ISoundContainer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7b659b53bc3047588b007ef8acf86052 +timeCreated: 1708454205 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/ISoundService.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/ISoundService.cs new file mode 100644 index 0000000..871c086 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/ISoundService.cs @@ -0,0 +1,10 @@ +using UnityEngine; + +namespace RedCatEngine.CommonServices.Services.SoundServices +{ + public interface ISoundService + { + void PlayMusic(AudioClip clip); + void PlaySfx(AudioClip clip); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/ISoundService.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/ISoundService.cs.meta new file mode 100644 index 0000000..041b1b0 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/ISoundService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f7bbcb052ebc426facdd7e0295e9fd27 +timeCreated: 1708452113 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/SoundService.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/SoundService.cs new file mode 100644 index 0000000..a31385c --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/SoundService.cs @@ -0,0 +1,22 @@ +using UnityEngine; + +namespace RedCatEngine.CommonServices.Services.SoundServices +{ + public class SoundService : ISoundService + { + private readonly AudioSource _musicSource; + private readonly AudioSource _sfxSource; + + public SoundService(AudioSource musicSource,AudioSource sfxSource) + { + _musicSource = musicSource; + _sfxSource = sfxSource; + } + + public void PlayMusic(AudioClip clip) + => _musicSource.clip = clip; + + public void PlaySfx(AudioClip clip) + => _sfxSource.PlayOneShot(clip); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/SoundService.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/SoundService.cs.meta new file mode 100644 index 0000000..c910594 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/SoundService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: cdd770f2544c46c287090c9d05f43f31 +timeCreated: 1708452159 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/SoundSfxContainer.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/SoundSfxContainer.cs new file mode 100644 index 0000000..e063c92 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/SoundSfxContainer.cs @@ -0,0 +1,30 @@ +using JetBrains.Annotations; +using RedCatEngine.DependencyInjection.Containers.Attributes; +using RedCatEngine.DependencyInjection.Specials.Components; +using UnityEngine; + +namespace RedCatEngine.CommonServices.Services.SoundServices +{ + public class SoundSfxContainer : MonoConstruct, ISoundContainer + { + [SerializeField] + private AudioClip _sfx; + + private ISoundService _soundService; + + [MonoInject] + public void Construct(ISoundService soundService) + { + _soundService = soundService; + } + + [UsedImplicitly] + public void ActionPlay() + => _soundService.PlaySfx(_sfx); + + public void SetClip(AudioClip audioClip) + { + _sfx = audioClip; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/SoundSfxContainer.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/SoundSfxContainer.cs.meta new file mode 100644 index 0000000..e3a16c2 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/SoundSfxContainer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2f3325f6a0af4f8783ae05a21134e75d +timeCreated: 1708452996 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/SoundSourceContainer.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/SoundSourceContainer.cs new file mode 100644 index 0000000..66c66d0 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/SoundSourceContainer.cs @@ -0,0 +1,16 @@ +using UnityEngine; + +namespace RedCatEngine.CommonServices.Services.SoundServices +{ + public class SoundSourceContainer : MonoBehaviour, ISoundService + { + [SerializeField] private AudioSource _musicSource; + [SerializeField] private AudioSource _sfxSource; + + public void PlayMusic(AudioClip clip) + => _musicSource.clip = clip; + + public void PlaySfx(AudioClip clip) + => _sfxSource.PlayOneShot(clip); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/SoundSourceContainer.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/SoundSourceContainer.cs.meta new file mode 100644 index 0000000..e5ac025 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/SoundServices/SoundSourceContainer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f310708ec0ba4114b372c09db8560ab5 +timeCreated: 1708453660 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times.meta new file mode 100644 index 0000000..5e5b3cb --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 57880d988e814533b4b09db65f70fc6c +timeCreated: 1733392168 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices.meta new file mode 100644 index 0000000..995f5e8 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 038175c869274c86b9f6603880b162a1 +timeCreated: 1733392181 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/GameDayTimeService.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/GameDayTimeService.cs new file mode 100644 index 0000000..b2bcc3c --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/GameDayTimeService.cs @@ -0,0 +1,106 @@ +using System; +using RedCatEngine.CommonServices.Containers.Observables; +using RedCatEngine.CommonServices.Services.Times.GameDayTimeServices.Settings; +using RedCatEngine.CommonServices.Services.Times.TimeServices; +using RedCatEngine.DependencyInjection.Containers.Attributes; +using UnityEngine; + +namespace RedCatEngine.CommonServices.Services.Times.GameDayTimeServices +{ + public class GameDayTimeService : IGameDayTimeService, IDisposable + { + private readonly ITimeService _timeService; + private readonly ITimeSetting _settings; + private readonly TimeSpan _sunriseTime; + private readonly TimeSpan _sunsetTime; + private DateTime _currentTime; + + public DateTime CurrentTime + => _currentTime; + + public event Action SunriseEvent; + public event Action SunsetEvent; + public event Action HourChangeEvent; + + private readonly Observable _isDayTime; + private readonly Observable _currentHour; + + [Inject] + public GameDayTimeService(ITimeService timeService, ITimeSetting settings) + { + _timeService = timeService; + _settings = settings; + _currentTime = DateTime.Now.Date + TimeSpan.FromHours(settings.StartHour); + _sunriseTime = TimeSpan.FromHours(settings.SunriseHour); + _sunsetTime = TimeSpan.FromHours(settings.SunsetHour); + + _isDayTime = new Observable(IsDayTime()); + _currentHour = new Observable(_currentTime.Hour); + + _timeService.UpdateEvent += UpdateTime; + _isDayTime.ValueChangeEvent += OnDayTimeChanged; + _currentHour.ValueChangeEvent += OnHourChange; + } + + private void OnHourChange(int hour) + => HourChangeEvent?.Invoke(); + + private void OnDayTimeChanged(bool day) + => (day ? SunriseEvent : SunsetEvent)?.Invoke(); + + private void UpdateTime(float deltaTime) + { + var addSeconds = deltaTime * _settings.TimeMultiplier; + +#if CHEAT_ENABLED + addSeconds *= TimeMultiplier; +#endif + _currentTime = _currentTime.AddSeconds(addSeconds); + _isDayTime.Value = IsDayTime(); + _currentHour.Value = _currentTime.Hour; + } + + public float CalculateSunAngle() + { + var isDay = IsDayTime(); + float startDegree = isDay ? 0 : 180; + var start = isDay ? _sunriseTime : _sunsetTime; + var end = isDay ? _sunsetTime : _sunriseTime; + + var totalTime = CalculateDifference(start, end); + var elapsedTime = CalculateDifference(start, _currentTime.TimeOfDay); + + var percentage = elapsedTime.TotalMinutes / totalTime.TotalMinutes; + return Mathf.Lerp( + startDegree, + startDegree + 180, + (float)percentage); + } +#if CHEAT_ENABLED + public float TimeMultiplier { get; set; } = 1f; +#endif + + // This method checks whether the current game time falls within the daytime period. + // It returns true if the current time of day is later than sunriseTime and earlier than sunsetTime, + // representing daytime. Otherwise, it returns false, indicating it is nighttime. + private bool IsDayTime() + => _currentTime.TimeOfDay > _sunriseTime && _currentTime.TimeOfDay < _sunsetTime; + + // This method calculates the difference between two TimeSpan objects ("from" and "to"). + // If the calculated difference is negative, this indicates that the "from" time is ahead of the "to" time. + // In such cases, 24 hours (representing a full day) is added to the negative difference to calculate the actual + // time difference taking into account the next day. + private TimeSpan CalculateDifference(TimeSpan from, TimeSpan to) + { + var difference = to - from; + return difference.TotalHours < 0 ? difference + TimeSpan.FromHours(24) : difference; + } + + public void Dispose() + { + _timeService.UpdateEvent -= UpdateTime; + _isDayTime.ValueChangeEvent -= OnDayTimeChanged; + _currentHour.ValueChangeEvent -= OnHourChange; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/GameDayTimeService.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/GameDayTimeService.cs.meta new file mode 100644 index 0000000..b440f04 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/GameDayTimeService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7b75a938b6b64c1eabe53f84ee3fefd7 +timeCreated: 1733393944 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/IGameDayTimeService.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/IGameDayTimeService.cs new file mode 100644 index 0000000..bace75a --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/IGameDayTimeService.cs @@ -0,0 +1,17 @@ +using System; + +namespace RedCatEngine.CommonServices.Services.Times.GameDayTimeServices +{ + public interface IGameDayTimeService + { + DateTime CurrentTime { get; } + event Action SunriseEvent; + event Action SunsetEvent; + event Action HourChangeEvent; + + float CalculateSunAngle(); +#if CHEAT_ENABLED + float TimeMultiplier { get; set; } +#endif + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/IGameDayTimeService.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/IGameDayTimeService.cs.meta new file mode 100644 index 0000000..6bdfb91 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/IGameDayTimeService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 578257b739ac44639b968b328c929c81 +timeCreated: 1733392157 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Monobeshs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Monobeshs.meta new file mode 100644 index 0000000..c0118f3 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Monobeshs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 37ef3bf70e2a42a8a767879c5e186f8e +timeCreated: 1733396504 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Monobeshs/SunRotator.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Monobeshs/SunRotator.cs new file mode 100644 index 0000000..0eebe9a --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Monobeshs/SunRotator.cs @@ -0,0 +1,108 @@ +using System; +using UnityEngine; + +namespace RedCatEngine.CommonServices.Services.Times.GameDayTimeServices.Monobeshs +{ + public class SunRotator : MonoBehaviour + { + [SerializeField] private Vector3 _axisRotation = Vector3.right; + [SerializeField] private Light _sun; + [SerializeField] private Light _moon; + [SerializeField] private AnimationCurve _lightIntensityCurve; + [SerializeField] private float _maxSunIntensity = 1; + [SerializeField] private float _maxMoonIntensity = 0.5f; + [SerializeField] private Color _dayAmbientLight; + [SerializeField] private Color _nightAmbientLight; + //[SerializeField] private Volume _volume; + [SerializeField] private Material _skyboxMaterial; + + //private ColorAdjustments _colorAdjustments; + + public event Action OnSunrise + { + add => _service.SunriseEvent += value; + remove => _service.SunriseEvent -= value; + } + + public event Action OnSunset + { + add => _service.SunsetEvent += value; + remove => _service.SunsetEvent -= value; + } + + public event Action OnHourChange + { + add => _service.HourChangeEvent += value; + remove => _service.HourChangeEvent -= value; + } + + private IGameDayTimeService _service; + + public void Construct(IGameDayTimeService dayTimeService) + { + _service = dayTimeService; + //_volume.profile.TryGet(out _colorAdjustments); + OnSunrise += () => Debug.Log("Sunrise"); + OnSunset += () => Debug.Log("Sunset"); + OnHourChange += () => Debug.LogFormat("Hour change: {0}", _service.CurrentTime); + } + + private void Update() + { + RotateSun(); + UpdateLightSettings(); + UpdateSkyBlend(); + +#if CHEAT_ENABLED + if (Input.GetKeyDown(KeyCode.RightBracket)) + { + _service.TimeMultiplier *= 2; + } + if (Input.GetKeyDown(KeyCode.LeftBracket)) + { + _service.TimeMultiplier /= 2; + } +#endif + } + + private void UpdateSkyBlend() + { + var dotProduct = Vector3.Dot(_sun.transform.forward, Vector3.up); + var blend = Mathf.Lerp( + 0, + 1, + _lightIntensityCurve.Evaluate(dotProduct)); + _skyboxMaterial.SetFloat("_Blend", blend); + } + + private void UpdateLightSettings() + { + var dotProduct = Vector3.Dot(_sun.transform.forward, Vector3.down); + var lightIntensity = _lightIntensityCurve.Evaluate(dotProduct); + + _sun.intensity = Mathf.Lerp( + 0, + _maxSunIntensity, + lightIntensity); + _moon.intensity = Mathf.Lerp( + _maxMoonIntensity, + 0, + lightIntensity); + + // if (_colorAdjustments == null) + // return; + // _colorAdjustments.colorFilter.value = Color.Lerp( + // _nightAmbientLight, + // _dayAmbientLight, + // lightIntensity); + } + + private void RotateSun() + { + var rotationSun = _service.CalculateSunAngle(); + _sun.transform.rotation = Quaternion.AngleAxis(rotationSun, _axisRotation); + var rotationMoon = _service.CalculateSunAngle(); + _moon.transform.rotation = Quaternion.AngleAxis(rotationMoon + 180, _axisRotation); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Monobeshs/SunRotator.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Monobeshs/SunRotator.cs.meta new file mode 100644 index 0000000..6b42aff --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Monobeshs/SunRotator.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 8edc9579fff54021ae034c1c06276914 +timeCreated: 1733396515 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Settings.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Settings.meta new file mode 100644 index 0000000..7cdfcfd --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Settings.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 07b9f30bd50148e5b829382136c8d8ae +timeCreated: 1733395706 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Settings/ITimeSetting.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Settings/ITimeSetting.cs new file mode 100644 index 0000000..a6d64c6 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Settings/ITimeSetting.cs @@ -0,0 +1,10 @@ +namespace RedCatEngine.CommonServices.Services.Times.GameDayTimeServices.Settings +{ + public interface ITimeSetting + { + public float TimeMultiplier { get; } + public float StartHour { get; } + public float SunriseHour { get; } + public float SunsetHour { get; } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Settings/ITimeSetting.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Settings/ITimeSetting.cs.meta new file mode 100644 index 0000000..621f836 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Settings/ITimeSetting.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 097e4736084d4d80bd5146615ee0657c +timeCreated: 1733395712 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Settings/TimeSettingsConfig.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Settings/TimeSettingsConfig.cs new file mode 100644 index 0000000..a98ee8b --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Settings/TimeSettingsConfig.cs @@ -0,0 +1,25 @@ +using RedCatEngine.Configs; +using UnityEngine; + +namespace RedCatEngine.CommonServices.Services.Times.GameDayTimeServices.Settings +{ + [CreateAssetMenu(menuName = "Configs/Common/Time Settings Config")] + public class TimeSettingsConfig : BaseConfig, ITimeSetting + { + [SerializeField] private float _timeMultiplier = 2000; + + [SerializeField] private float _startHour = 12; + + [SerializeField] private float _sunriseHour = 6; + + [SerializeField] private float _sunsetHour = 18; + public float TimeMultiplier + => _timeMultiplier; + public float StartHour + => _startHour; + public float SunriseHour + => _sunriseHour; + public float SunsetHour + => _sunsetHour; + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Settings/TimeSettingsConfig.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Settings/TimeSettingsConfig.cs.meta new file mode 100644 index 0000000..8c28c51 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/GameDayTimeServices/Settings/TimeSettingsConfig.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 37acd973c2eb4030a3c6c66322eae2f2 +timeCreated: 1733393944 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices.meta new file mode 100644 index 0000000..73c5dea --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 01217e0ec1e340c7bb655137744be681 +timeCreated: 1726144991 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices/IPausedTimeService.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices/IPausedTimeService.cs new file mode 100644 index 0000000..7fe3f9a --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices/IPausedTimeService.cs @@ -0,0 +1,8 @@ +namespace RedCatEngine.CommonServices.Services.Times.TimeServices +{ + public interface IPausedTimeService + { + void Pause(object source); + void UnPause(object source); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices/IPausedTimeService.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices/IPausedTimeService.cs.meta new file mode 100644 index 0000000..cfa5c02 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices/IPausedTimeService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 487142851d9c4eb2aec95ae993943a49 +timeCreated: 1718266353 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices/ITimeService.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices/ITimeService.cs new file mode 100644 index 0000000..81c3969 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices/ITimeService.cs @@ -0,0 +1,13 @@ +using System; + +namespace RedCatEngine.CommonServices.Services.Times.TimeServices +{ + public interface ITimeService + { + float FixedDeltaTime { get; } + float DeltaTime { get; } + float TimeScale { get; } + float TotalTime { get; } + event Action UpdateEvent; + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices/ITimeService.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices/ITimeService.cs.meta new file mode 100644 index 0000000..fbc5749 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices/ITimeService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 5b37185e6d0c4ea6a62cd588751acf54 +timeCreated: 1726144961 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices/UnityTimeService.cs b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices/UnityTimeService.cs new file mode 100644 index 0000000..6971334 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices/UnityTimeService.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace RedCatEngine.CommonServices.Services.Times.TimeServices +{ + public class UnityTimeService : MonoBehaviour, ITimeService, IPausedTimeService + { + private readonly List _pauseHolder = new(); + + public float FixedDeltaTime + => Time.fixedDeltaTime; + + public float DeltaTime + => Time.deltaTime; + + public float TimeScale + => Time.timeScale; + + public float TotalTime + => Time.time; + + private void Update() + => UpdateEvent?.Invoke(DeltaTime); + + public void Pause(object source) + { + if (_pauseHolder.Contains(source)) + return; + _pauseHolder.Add(source); + UpdatePauseState(); + } + + public void UnPause(object source) + { + if (!_pauseHolder.Contains(source)) + return; + _pauseHolder.Remove(source); + UpdatePauseState(); + } + + public event Action UpdateEvent; + + private void UpdatePauseState() + { + Time.timeScale = _pauseHolder.Count > 0 + ? 0.001f + : 1f; //todo: merge with IInputService + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices/UnityTimeService.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices/UnityTimeService.cs.meta new file mode 100644 index 0000000..ac9d0a9 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/Services/Times/TimeServices/UnityTimeService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f88a9ae07bb04a3d8f8a5cc9899eda8f +timeCreated: 1726145009 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes.meta b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes.meta new file mode 100644 index 0000000..fee7d37 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: cdf173a8d04f409eb692a334ee05a726 +timeCreated: 1751400784 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangeTrackedValues.meta b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangeTrackedValues.meta new file mode 100644 index 0000000..74130c6 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangeTrackedValues.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 117daa24d61243e08f75fbc1305c5433 +timeCreated: 1753710776 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangeTrackedValues/ChangeTrackedValue.cs b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangeTrackedValues/ChangeTrackedValue.cs new file mode 100644 index 0000000..f29ccc9 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangeTrackedValues/ChangeTrackedValue.cs @@ -0,0 +1,71 @@ +namespace RedCatEngine.CommonServices.SpecialTypes.ChangeTrackedValues +{ + /// + /// Обёртка для значения, которое информирует о том, + /// было ли оно изменено в результате попытки установить новое значение. + /// + /// Тип хранимого значения. + public class ChangeTrackedValue + { + /// + /// Хранит текущее значение. + /// + private TValue _value; + + /// + /// Получает текущее значение. Не позволяет его изменить напрямую. + /// + public TValue Value => _value; + + /// + /// Инициализирует новый экземпляр класса со значением по умолчанию. + /// + public ChangeTrackedValue() + { + _value = default; + } + + /// + /// Инициализирует новый экземпляр класса с указанным начальным значением. + /// + /// Начальное значение. + public ChangeTrackedValue(TValue value) + { + _value = value; + } + + /// + /// Пытается задать новое значение. Возвращает результат того, было ли значение изменено или нет. + /// + /// Новое значение. + /// + /// , если новое значение было успешно изменено, + /// , если значение уже соответствует текущему и оно не было изменено. + /// + public bool TrySetNewValue(TValue value) + { + if (Equals(_value, value)) + return false; + + _value = value; + return true; + } + + /// + /// Определяет неявное преобразование из значения типа + /// в экземпляр класса . + /// + /// Значение для обёртки. + /// Новый экземпляр класса . + public static implicit operator ChangeTrackedValue(TValue value) + => new(value); + + /// + /// Определяет неявное преобразование из экземпляра класса + /// в значение . + /// + /// Значение для обёртки. + /// Значение типа . + public static implicit operator TValue(ChangeTrackedValue value) => value.Value; + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangeTrackedValues/ChangeTrackedValue.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangeTrackedValues/ChangeTrackedValue.cs.meta new file mode 100644 index 0000000..36ec9d1 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangeTrackedValues/ChangeTrackedValue.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 41a4ddecc44346b5a01e565e7ce066e6 +timeCreated: 1753710341 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues.meta b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues.meta new file mode 100644 index 0000000..122c591 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 92e0db2cb4714bc99db4b5b11dc09310 +timeCreated: 1753372816 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/BasedTypes.meta b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/BasedTypes.meta new file mode 100644 index 0000000..8ef82c0 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/BasedTypes.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 1557eeb179dd43b1b8609d40451ab7e2 +timeCreated: 1753372904 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/BasedTypes/FloatDeltaChangeValue.cs b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/BasedTypes/FloatDeltaChangeValue.cs new file mode 100644 index 0000000..5a7fa80 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/BasedTypes/FloatDeltaChangeValue.cs @@ -0,0 +1,30 @@ +using System; + +namespace RedCatEngine.CommonServices.SpecialTypes.ChangedValues.BasedTypes +{ + /// +/// Представляет изменение значения с плавающей точкой с возможностью вычисления дельты (разницы). +/// Является специализацией класса для типа . +/// +public class FloatDeltaChangeValue : DeltaChangeValue +{ + /// + /// Инициализирует новый экземпляр класса . + /// + /// Старое значение. + /// Новое значение. + public FloatDeltaChangeValue(float oldValue, float newValue) + : base(oldValue, newValue, (oldVal, newVal) => newVal - oldVal) + { + } + + /// + /// Определяет неявное преобразование из кортежа со старым и новым значением в объект . + /// + /// Кортеж, содержащий oldValue и newValue. + /// Новый объект . + public static implicit operator FloatDeltaChangeValue((float oldValue, float newValue) tuple) + => new(tuple.oldValue, tuple.newValue); +} + +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/BasedTypes/FloatDeltaChangeValue.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/BasedTypes/FloatDeltaChangeValue.cs.meta new file mode 100644 index 0000000..65c1171 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/BasedTypes/FloatDeltaChangeValue.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3285b3ea82904b6cb5cd3f1debb7318d +timeCreated: 1753372913 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/BasedTypes/IntDeltaChangeValue.cs b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/BasedTypes/IntDeltaChangeValue.cs new file mode 100644 index 0000000..f7628b3 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/BasedTypes/IntDeltaChangeValue.cs @@ -0,0 +1,28 @@ +namespace RedCatEngine.CommonServices.SpecialTypes.ChangedValues.BasedTypes +{ + /// +/// Представляет изменение целочисленного значения с возможностью вычисления дельты (разницы). +/// Является специализацией класса для типа . +/// +public class IntDeltaChangeValue : DeltaChangeValue +{ + /// + /// Инициализирует новый экземпляр класса . + /// + /// Старое значение. + /// Новое значение. + public IntDeltaChangeValue(int oldValue, int newValue) + : base(oldValue, newValue, (oldVal, newVal) => newVal - oldVal) + { + } + + /// + /// Определяет неявное преобразование из кортежа со старым и новым значением в объект . + /// + /// Кортеж, содержащий oldValue и newValue. + /// Новый объект . + public static implicit operator IntDeltaChangeValue((int oldValue, int newValue) tuple) + => new(tuple.oldValue, tuple.newValue); +} + +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/BasedTypes/IntDeltaChangeValue.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/BasedTypes/IntDeltaChangeValue.cs.meta new file mode 100644 index 0000000..ccf0be5 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/BasedTypes/IntDeltaChangeValue.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7ec79ecc239747a68f7d8a3ac267b4d6 +timeCreated: 1753373015 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/ChangeValue.cs b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/ChangeValue.cs new file mode 100644 index 0000000..44949eb --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/ChangeValue.cs @@ -0,0 +1,36 @@ +namespace RedCatEngine.CommonServices.SpecialTypes.ChangedValues +{ + /// + /// Представляет информацию о изменении значения, содержащую старое и новое значение. + /// + /// Тип хранимого значения. + public class ChangeValue + { + /// + /// Получает старое значение до изменения. + /// + public T OldValue { get; } + + /// + /// Получает новое значение после изменения. + /// + public T NewValue { get; } + + /// + /// Инициализирует новый экземпляр класса . + /// + /// Старое значение. + /// Новое значение. + public ChangeValue(T oldValue, T newValue) + { + OldValue = oldValue; + NewValue = newValue; + } + + /// + /// Возвращает строковое представление объекта в формате "(Old: {OldValue}, New: {NewValue})". + /// + /// Строковое представление текущего объекта. + public override string ToString() => $"(Old:{OldValue} -> New:{NewValue})"; + } +} diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/ChangeValue.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/ChangeValue.cs.meta new file mode 100644 index 0000000..e098f82 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/ChangeValue.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: acd4edf9db9d4c3186bfe2dba5ee8987 +timeCreated: 1753372530 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/DeltaChangeValue.cs b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/DeltaChangeValue.cs new file mode 100644 index 0000000..4677c79 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/DeltaChangeValue.cs @@ -0,0 +1,41 @@ +using System; + +namespace RedCatEngine.CommonServices.SpecialTypes.ChangedValues +{ + /// +/// Расширяет , добавляя возможность вычисления разницы (дельты) между старым и новым значением. +/// +/// Тип значения, для которого рассчитывается дельта. +public class DeltaChangeValue : ChangeValue +{ + /// + /// Функция, используемая для вычисления дельты между старым и новым значением. + /// + private readonly Func _deltaCalculator; + + /// + /// Получает значение дельты (разницу) между и . + /// + public T Delta => _deltaCalculator(OldValue, NewValue); + + /// + /// Инициализирует новый экземпляр класса . + /// + /// Старое значение. + /// Новое значение. + /// Функция для вычисления дельты между старым и новым значением. + /// Выбрасывается, если равен . + public DeltaChangeValue(T oldValue, T newValue, Func deltaCalculator) + : base(oldValue, newValue) + { + _deltaCalculator = deltaCalculator ?? throw new ArgumentNullException(nameof(deltaCalculator)); + } + + /// + /// Возвращает строковое представление объекта в формате "Δ: {Delta} (Old: {OldValue}, New: {NewValue})". + /// + /// Строковое представление текущего объекта. + public override string ToString() => $"Δ:{Delta} (Old:{OldValue} -> New:{NewValue})"; +} + +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/DeltaChangeValue.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/DeltaChangeValue.cs.meta new file mode 100644 index 0000000..28f5fc3 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/ChangedValues/DeltaChangeValue.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: fa7c5ad4a5d543f2b421d5e220c5f0ee +timeCreated: 1753372829 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes.meta b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes.meta new file mode 100644 index 0000000..af7b3b0 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 6f77fdb9319e453eb138bf3b783581f2 +timeCreated: 1753772877 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/CallbacksComponentCollector.cs b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/CallbacksComponentCollector.cs new file mode 100644 index 0000000..00f61e2 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/CallbacksComponentCollector.cs @@ -0,0 +1,77 @@ +using System; +using RedCatEngine.CommonServices.SpecialTypes.UnityHelpTypes.ComponentFinders; + +namespace RedCatEngine.CommonServices.SpecialTypes.UnityHelpTypes +{ + /// +/// Расширяет , добавляя возможность вызывать пользовательские коллбэки +/// после добавления или удаления компонента из списка. +/// +/// Тип компонентов, которые собираются. Может быть интерфейсом, классом или другим типом. +public class CallbacksComponentCollector : ComponentCollector where TBehaviour : class +{ + /// + /// Действие, которое будет вызвано после успешного добавления компонента в список. + /// + private readonly Action _callbackAfterAddComponent; + + /// + /// Действие, которое будет вызвано после успешного удаления компонента из списка. + /// + private readonly Action _callbackAfterRemoveComponent; + + /// + /// Инициализирует новый экземпляр класса . + /// + /// + /// Коллбэк, вызываемый после добавления компонента. + /// + /// + /// Коллбэк, вызываемый после удаления компонента. + /// + public CallbacksComponentCollector( + Action callbackAfterAddComponent, + Action callbackAfterRemoveComponent) + { + _callbackAfterAddComponent = callbackAfterAddComponent; + _callbackAfterRemoveComponent = callbackAfterRemoveComponent; + } + + /// + /// Инициализирует новый экземпляр класса . + /// + /// Переопределённый поисковик, в который можно добавить разные фильтры + /// + /// Коллбэк, вызываемый после добавления компонента. + /// + /// + /// Коллбэк, вызываемый после удаления компонента. + /// + public CallbacksComponentCollector( + ComponentTypeFinder specialFinder, + Action callbackAfterAddComponent, + Action callbackAfterRemoveComponent + ) + : base(specialFinder) + { + _callbackAfterAddComponent = callbackAfterAddComponent; + _callbackAfterRemoveComponent = callbackAfterRemoveComponent; + } + /// + /// Вызывается после добавления компонента в список. + /// Выполняет действие . + /// + /// Добавленный компонент. + protected override void DoAfterAdd(TBehaviour component) + => _callbackAfterAddComponent?.Invoke(component); + + /// + /// Вызывается после удаления компонента из списка. + /// Выполняет действие . + /// + /// Удалённый компонент. + protected override void DoAfterRemove(TBehaviour component) + => _callbackAfterRemoveComponent?.Invoke(component); +} + +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/CallbacksComponentCollector.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/CallbacksComponentCollector.cs.meta new file mode 100644 index 0000000..86638e2 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/CallbacksComponentCollector.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d33a012c9dcc43dd9f5047ee5c4a8dac +timeCreated: 1753778792 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentCollector.cs b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentCollector.cs new file mode 100644 index 0000000..9cb9be3 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentCollector.cs @@ -0,0 +1,125 @@ +using System.Collections; +using System.Collections.Generic; +using RedCatEngine.CommonServices.SpecialTypes.UnityHelpTypes.ComponentFinders; +using UnityEngine; + +namespace RedCatEngine.CommonServices.SpecialTypes.UnityHelpTypes +{ + /// + /// Утилита для сбора и управления компонентами указанного типа на игровых объектах. + /// + /// Тип компонента, который собирается. + public class ComponentCollector : IEnumerable where TBehaviour : class + { + /// + /// Вспомогательный фасад для проверки наличия компонентов нужного типа. + /// + private readonly ComponentTypeFinder _specialFinder; + + /// + /// Список собранных компонентов типа . + /// + private readonly List _components = new(); + + public ComponentCollector() + { + _specialFinder = new ComponentTypeFinder(); + } + + public ComponentCollector(ComponentTypeFinder specialFinder) + { + _specialFinder = specialFinder; + } + + /// + /// Пытается добавить компонент указанного типа из игрового объекта в список. + /// + /// Игровой объект, на котором проверяется наличие компонента. + /// Найденный и успешно добавленный компонент. Пустой в случае отсутствия компонента на объекте + /// + /// , если компонент был найден и успешно добавлен; + /// , если компонент не найден или уже существует в списке. + /// + public bool TryAdd(GameObject gameObject, out TBehaviour component) + { + if (!_specialFinder.IsHasComponent(gameObject, out component)) + return false; + + _components.Add(component); + DoAfterAdd(component); + return true; + } + + /// + /// Дополнительные действия после добавления компонента. Можно переопределить в наследниках при необходимости. + /// + /// Компонент над которым необходимо совершить дополнительные действия после добавления. + protected virtual void DoAfterAdd(TBehaviour component) + { + } + + /// + /// Пытается удалить компонент указанного типа из списка, если он там есть. + /// + /// Игровой объект, чей компонент нужно удалить. + /// Найденный и успешно удалённый компонент. Пустой в случае отсутствия компонента на объекте + /// + /// , если компонент был найден и успешно удален; + /// , если компонент не найден или отсутствует в коллекции. + /// + public bool TryRemove(GameObject gameObject, out TBehaviour component) + { + return _specialFinder.IsHasComponent(gameObject, out component) && Remove(component); + } + + /// + /// Пытается удалить указанный компонент из коллекции, если он в ней содержится. + /// + /// Компонент, который нужно удалить из коллекции. + /// + /// , если компонент был в коллекции и успешно удалён; + /// , если компонент не был найден в коллекции. + /// + public bool TryRemove(TBehaviour component) + => Remove(component); + + private bool Remove(TBehaviour component) + { + if (!_components.Contains(component)) + return false; + + _components.Remove(component); + DoAfterRemove(component); + return true; + } + + /// + /// Дополнительные действия после удаления компонента. Можно переопределить в наследниках при необходимости. + /// + /// Компонент над которым необходимо совершить дополнительные действия после удаления. + protected virtual void DoAfterRemove(TBehaviour component) + { + } + + /// + /// Возвращает итератор по компонентам. + /// + /// + /// Итератор по компонентам. + /// + public IEnumerator GetEnumerator() + => _components.GetEnumerator(); + + /// + /// Очищает список компонентов. + /// + public void Clear() + { + var componentsArray = _components.ToArray(); + foreach (var component in componentsArray) + { + Remove(component); + } + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentCollector.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentCollector.cs.meta new file mode 100644 index 0000000..e7523dd --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentCollector.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3309c4716385442e9005601d7167f98d +timeCreated: 1753775985 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentFinders.meta b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentFinders.meta new file mode 100644 index 0000000..637cad4 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentFinders.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 98fbe7c1545f4e5b8593008e8f35f2ec +timeCreated: 1753811043 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentFinders/ComponentTypeFinder.cs b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentFinders/ComponentTypeFinder.cs new file mode 100644 index 0000000..4f245dc --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentFinders/ComponentTypeFinder.cs @@ -0,0 +1,49 @@ +using UnityEngine; + +namespace RedCatEngine.CommonServices.SpecialTypes.UnityHelpTypes.ComponentFinders +{ + /// + /// Утилита для проверки наличия компонента определённого типа на объекте. + /// + /// Тип компонента, который необходимо найти. Должен быть наследником . + public class ComponentTypeFinder where TBehaviour : class + { + /// + /// Проверяет, содержит ли указанный объект компонент типа . + /// + /// Компонент, чей объект будет проверяться на наличие нужного компонента. + /// Найденный компонент типа , если он существует. + /// + /// , если компонент найден; в противном случае — . + /// + public bool IsHasComponent(MonoBehaviour otherComponent, out TBehaviour component) + { + component = null; + return otherComponent != null + && otherComponent.gameObject.TryGetComponent(out component) + && IsValid(otherComponent.gameObject, component); + } + + /// + /// Проверяет, содержит ли указанный объект компонент типа . + /// + /// Объект, на котором ищется компонент. + /// Найденный компонент типа , если он существует. + /// + /// , если компонент найден; в противном случае — . + /// + public bool IsHasComponent(GameObject gameObject, out TBehaviour component) + { + component = null; + return gameObject != null && gameObject.TryGetComponent(out component) && IsValid(gameObject, component); + } + + /// + /// Валидирует, должен ли данный объект игнорироваться при поиске компонента. + /// + /// Объект, на котором осуществлялся поиск компонента + /// + /// Прошла ли валидация успешно + protected virtual bool IsValid(GameObject gameObject, TBehaviour component) => true; + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentFinders/ComponentTypeFinder.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentFinders/ComponentTypeFinder.cs.meta new file mode 100644 index 0000000..e80e0d2 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentFinders/ComponentTypeFinder.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3151d5fb65e148978c0ad96b82075cfb +timeCreated: 1753772900 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentFinders/RendererComponentTypeFinder.cs b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentFinders/RendererComponentTypeFinder.cs new file mode 100644 index 0000000..4763016 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentFinders/RendererComponentTypeFinder.cs @@ -0,0 +1,16 @@ +using UnityEngine; + +namespace RedCatEngine.CommonServices.SpecialTypes.UnityHelpTypes.ComponentFinders +{ + public class RendererComponentTypeFinder : ComponentTypeFinder where TBehaviour : class + { + protected override bool IsValid(GameObject gameObject, TBehaviour component) + { + var renderer = gameObject.GetComponentInParent(); + if (renderer != null) + return renderer.isVisible; + renderer = gameObject.GetComponentInChildren(); + return renderer != null && renderer.isVisible; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentFinders/RendererComponentTypeFinder.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentFinders/RendererComponentTypeFinder.cs.meta new file mode 100644 index 0000000..ccc5418 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/ComponentFinders/RendererComponentTypeFinder.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 6be4b107e8d843249ee416c960ba061c +timeCreated: 1753811091 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/UnityTag.cs b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/UnityTag.cs new file mode 100644 index 0000000..47d2ac7 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/UnityTag.cs @@ -0,0 +1,50 @@ +using System; +using UnityEngine; + +namespace RedCatEngine.CommonServices.SpecialTypes.UnityHelpTypes +{ + /// + /// Обёртка над строкой, представляющая тег объекта в Unity. + /// Позволяет использовать теги более безопасно и удобно, например, для сравнения с GameObject. + /// + [Serializable] + public struct UnityTag + { + /// + /// Содержит имя тега в виде строки. + /// + public string Tag; + + /// + /// Неявное преобразование из в . + /// + /// Структура . + /// Строковое представление тега. + public static implicit operator string(UnityTag tag) + { + return tag.Tag; + } + + /// + /// Неявное преобразование из строки в . + /// + /// Строковое значение тега. + /// Созданный объект . + public static implicit operator UnityTag(string tag) + { + UnityTag result = default; + result.Tag = tag; + return result; + } + + /// + /// Сравнивает тег этого объекта с тегом указанного GameObject. + /// + /// Объект , у которого проверяется тег. + /// , если теги совпадают; в противном случае — . + public bool CompareTag(GameObject obj) + { + return obj.CompareTag(this); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/UnityTag.cs.meta b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/UnityTag.cs.meta new file mode 100644 index 0000000..bc3df10 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/SpecialTypes/UnityHelpTypes/UnityTag.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b62be1add8e9405a8d482ccfb7853fa7 +timeCreated: 1751400791 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/package.json b/RedCatEngineUnityProject/Packages/UniversalServices/package.json new file mode 100644 index 0000000..8b5aca7 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/package.json @@ -0,0 +1,11 @@ +{ + "name": "com.boronnikov.games.red-cat-engine.services", + "version": "1.0.0", + "displayName": "Red Cat Engine: Common services", + "description": "Pack of universal services for create games", + "unity": "2021.3", + "author": { + "name": "Boronnikov Games", + "url": "https://github.com/Red-Cat-Fat" + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/UniversalServices/package.json.meta b/RedCatEngineUnityProject/Packages/UniversalServices/package.json.meta new file mode 100644 index 0000000..4b02035 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/UniversalServices/package.json.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: bf67b5a90a9bd9345a9aceada9416e31 +timeCreated: 1713125223 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/BaseConfigLinkValue.cs b/RedCatEngineUnityProject/Packages/Values/Base/BaseConfigLinkValue.cs deleted file mode 100644 index 9973a6d..0000000 --- a/RedCatEngineUnityProject/Packages/Values/Base/BaseConfigLinkValue.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using RedCatEngine.DependencyInjection.Containers.Interfaces; -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; - -namespace RedCatEngine.Values.Base -{ - [Serializable] - public class BaseConfigLinkValue : IValue - { - public BaseValueConfig ValueConfig; - public TValue GetValue(IApplicationContainer applicationContainer) - => ValueConfig.GetValue(applicationContainer); - } -} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations.meta b/RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations.meta new file mode 100644 index 0000000..567d964 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 01a6a980124b4d8785ad5ae50def5f7a +timeCreated: 1729173206 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations/BaseConfigLinkValue.cs b/RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations/BaseConfigLinkValue.cs new file mode 100644 index 0000000..4f2f554 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations/BaseConfigLinkValue.cs @@ -0,0 +1,16 @@ +using System; +using RedCatEngine.Values.Base.Interfaces; +using IGetterApplicationContainer = + RedCatEngine.DependencyInjection.Containers.Interfaces.Application.IGetterApplicationContainer; + +namespace RedCatEngine.Values.Base.BaseRealisations +{ + [Serializable] + public class BaseConfigLinkValue : IValue + { + public BaseValueConfig ValueConfig; + + public TValue GetValue(IGetterApplicationContainer getterContainer) + => ValueConfig.GetValue(getterContainer); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/BaseConfigLinkValue.cs.meta b/RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations/BaseConfigLinkValue.cs.meta similarity index 100% rename from RedCatEngineUnityProject/Packages/Values/Base/BaseConfigLinkValue.cs.meta rename to RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations/BaseConfigLinkValue.cs.meta diff --git a/RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations/BaseServiceGetterValue.cs b/RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations/BaseServiceGetterValue.cs new file mode 100644 index 0000000..d3d85b1 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations/BaseServiceGetterValue.cs @@ -0,0 +1,13 @@ +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; +using RedCatEngine.Values.Base.Interfaces; + +namespace RedCatEngine.Values.Base.BaseRealisations +{ + public abstract class BaseServiceGetterValue : IValue + { + public TReturnedType GetValue(IGetterApplicationContainer getterContainer) + => GetValueFromServices(getterContainer.GetSingle()); + + protected abstract TReturnedType GetValueFromServices(TServiceType singleService); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations/BaseServiceGetterValue.cs.meta b/RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations/BaseServiceGetterValue.cs.meta new file mode 100644 index 0000000..287d8de --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations/BaseServiceGetterValue.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c80f3ae1708c419dbddf9974050d68ee +timeCreated: 1729173257 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations/BaseValueConfig.cs b/RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations/BaseValueConfig.cs new file mode 100644 index 0000000..8b931f7 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations/BaseValueConfig.cs @@ -0,0 +1,18 @@ +using RedCatEngine.Configs; +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; +using RedCatEngine.Values.Base.Interfaces; +using SerializeReferenceEditor; + +namespace RedCatEngine.Values.Base.BaseRealisations +{ + [SRHidden] + public abstract class BaseValueConfig : BaseConfig, IValue + { + protected abstract IValue ReturnValue { get; } + + public TValue GetValue(IGetterApplicationContainer getterContainer) + { + return ReturnValue.GetValue(getterContainer); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/BaseValueConfig.cs.meta b/RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations/BaseValueConfig.cs.meta similarity index 100% rename from RedCatEngineUnityProject/Packages/Values/Base/BaseValueConfig.cs.meta rename to RedCatEngineUnityProject/Packages/Values/Base/BaseRealisations/BaseValueConfig.cs.meta diff --git a/RedCatEngineUnityProject/Packages/Values/Base/BaseValueConfig.cs b/RedCatEngineUnityProject/Packages/Values/Base/BaseValueConfig.cs deleted file mode 100644 index 1f0fa75..0000000 --- a/RedCatEngineUnityProject/Packages/Values/Base/BaseValueConfig.cs +++ /dev/null @@ -1,16 +0,0 @@ -using RedCatEngine.Configs; -using RedCatEngine.DependencyInjection.Containers.Interfaces; -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; - -namespace RedCatEngine.Values.Base -{ - public abstract class BaseValueConfig : BaseConfig, IValue - { - protected abstract IValue ReturnValue { get; } - - public TValue GetValue(IApplicationContainer applicationContainer) - { - return ReturnValue.GetValue(applicationContainer); - } - } -} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/IBoolValue.cs b/RedCatEngineUnityProject/Packages/Values/Base/IBoolValue.cs deleted file mode 100644 index e176e39..0000000 --- a/RedCatEngineUnityProject/Packages/Values/Base/IBoolValue.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace RedCatEngine.Values.Base -{ - public interface IBoolValue : IValue - { - } -} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/IFloatValue.cs b/RedCatEngineUnityProject/Packages/Values/Base/IFloatValue.cs deleted file mode 100644 index 0250703..0000000 --- a/RedCatEngineUnityProject/Packages/Values/Base/IFloatValue.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace RedCatEngine.Values.Base -{ - public interface IFloatValue : IValue - { - } -} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/IValue.cs b/RedCatEngineUnityProject/Packages/Values/Base/IValue.cs deleted file mode 100644 index d26761f..0000000 --- a/RedCatEngineUnityProject/Packages/Values/Base/IValue.cs +++ /dev/null @@ -1,10 +0,0 @@ -using RedCatEngine.DependencyInjection.Containers.Interfaces; -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; - -namespace RedCatEngine.Values.Base -{ - public interface IValue - { - TResultType GetValue(IApplicationContainer applicationContainer); - } -} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/Interfaces.meta b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces.meta new file mode 100644 index 0000000..85fa4e3 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: a7052ab70a264b77a754587f15073b64 +timeCreated: 1729173189 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IBoolValue.cs b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IBoolValue.cs new file mode 100644 index 0000000..401ad3e --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IBoolValue.cs @@ -0,0 +1,10 @@ +using RedCatEngine.Values.Services; + +namespace RedCatEngine.Values.Base.Interfaces +{ + public interface IBoolValue : IValue + { + bool GetValue(ValueCalculationService getterContainer) + => getterContainer.GetValue(this); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/IBoolValue.cs.meta b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IBoolValue.cs.meta similarity index 100% rename from RedCatEngineUnityProject/Packages/Values/Base/IBoolValue.cs.meta rename to RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IBoolValue.cs.meta diff --git a/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IContextFloatValue.cs b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IContextFloatValue.cs new file mode 100644 index 0000000..e000844 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IContextFloatValue.cs @@ -0,0 +1,9 @@ +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; + +namespace RedCatEngine.Values.Base.Interfaces +{ + public interface IContextFloatValue : IFloatValue + { + float GetValue(IGetterApplicationContainer getterContainer, TContext context); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IContextFloatValue.cs.meta b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IContextFloatValue.cs.meta new file mode 100644 index 0000000..8bd3de2 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IContextFloatValue.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9e2fbc7944ef42c9b2dd5a362b84a958 +timeCreated: 1727097580 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IFloatValue.cs b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IFloatValue.cs new file mode 100644 index 0000000..3de4557 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IFloatValue.cs @@ -0,0 +1,10 @@ +using RedCatEngine.Values.Services; + +namespace RedCatEngine.Values.Base.Interfaces +{ + public interface IFloatValue : IValue + { + float GetValue(ValueCalculationService getterContainer) + => getterContainer.GetValue(this); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/IFloatValue.cs.meta b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IFloatValue.cs.meta similarity index 100% rename from RedCatEngineUnityProject/Packages/Values/Base/IFloatValue.cs.meta rename to RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IFloatValue.cs.meta diff --git a/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IIntValue.cs b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IIntValue.cs new file mode 100644 index 0000000..0c255d6 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IIntValue.cs @@ -0,0 +1,10 @@ +using RedCatEngine.Values.Services; + +namespace RedCatEngine.Values.Base.Interfaces +{ + public interface IIntValue : IValue + { + int GetValue(ValueCalculationService getterContainer) + => getterContainer.GetValue(this); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IIntValue.cs.meta b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IIntValue.cs.meta new file mode 100644 index 0000000..d2aa6d8 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IIntValue.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: eef5d846ddfd4db6a3815744bc6b5bde +timeCreated: 1728572742 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IValue.cs b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IValue.cs new file mode 100644 index 0000000..0f59638 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IValue.cs @@ -0,0 +1,9 @@ +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; + +namespace RedCatEngine.Values.Base.Interfaces +{ + public interface IValue + { + TResultType GetValue(IGetterApplicationContainer getterContainer); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Base/IValue.cs.meta b/RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IValue.cs.meta similarity index 100% rename from RedCatEngineUnityProject/Packages/Values/Base/IValue.cs.meta rename to RedCatEngineUnityProject/Packages/Values/Base/Interfaces/IValue.cs.meta diff --git a/RedCatEngineUnityProject/Packages/Values/CHANGELOG.md b/RedCatEngineUnityProject/Packages/Values/CHANGELOG.md index 674ff0a..e5060ae 100644 --- a/RedCatEngineUnityProject/Packages/Values/CHANGELOG.md +++ b/RedCatEngineUnityProject/Packages/Values/CHANGELOG.md @@ -5,13 +5,19 @@ All notable changes to Value package will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [1.0.0] - 2024-07-19 +## [1.0.1] - 2024-10-17 ### Added -- CHANGELOG.md +- Variable service. + +### Changes + +- ValueCalculationService.cs move to Service folder with namespace from **RedCatEngine.Values** to * + *RedCatEngine.Values.Services** -### Changed +## [1.0.0] - 2024-07-19 + +### Added -- Rename DailyQuestsData to QuestsDataContainer -- Change QuestConfig.DescriptionKey from field to abstract property \ No newline at end of file +- Base services \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Services.meta b/RedCatEngineUnityProject/Packages/Values/Services.meta new file mode 100644 index 0000000..bdafcce --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Services.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 5c2619c650e349ac8f2661a12cc52b26 +timeCreated: 1729172288 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Services/MultiplierValueCalculationService.cs b/RedCatEngineUnityProject/Packages/Values/Services/MultiplierValueCalculationService.cs new file mode 100644 index 0000000..814ecf6 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Services/MultiplierValueCalculationService.cs @@ -0,0 +1,25 @@ +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; +using RedCatEngine.Values.Base.Interfaces; +using UnityEngine; + +namespace RedCatEngine.Values.Services +{ + public class MultiplierValueCalculationService : ValueCalculationService + { + private readonly IFloatValue _multiplier; + + public MultiplierValueCalculationService(IGetterApplicationContainer getter, IFloatValue multiplier) + : base(getter) + { + _multiplier = multiplier; + } + + public override float GetValue(IFloatValue floatValue) + { + var baseValue = base.GetValue(floatValue); + var multiplier = base.GetValue(_multiplier); + Debug.LogFormat("Calculate miltiplier value: {0} * {1} = {2}", baseValue, multiplier, baseValue * multiplier ); + return baseValue * multiplier; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Services/MultiplierValueCalculationService.cs.meta b/RedCatEngineUnityProject/Packages/Values/Services/MultiplierValueCalculationService.cs.meta new file mode 100644 index 0000000..5b855a6 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Services/MultiplierValueCalculationService.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 41bbba472cb30594bbf023ca8e103dd3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/RedCatEngineUnityProject/Packages/Values/Services/ValueCalculationService.cs b/RedCatEngineUnityProject/Packages/Values/Services/ValueCalculationService.cs new file mode 100644 index 0000000..b3bae09 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Services/ValueCalculationService.cs @@ -0,0 +1,37 @@ +using JetBrains.Annotations; +using RedCatEngine.DependencyInjection.Containers.Attributes; +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; +using RedCatEngine.Values.Base.Interfaces; + +namespace RedCatEngine.Values.Services +{ + [UsedImplicitly] + public class ValueCalculationService + { + private readonly IGetterApplicationContainer _getter; + + [Inject] + public ValueCalculationService(IGetterApplicationContainer getter) + { + _getter = getter; + } + + public float GetValueOrDefault(IFloatValue floatValue, float defaultValue) + => floatValue?.GetValue(_getter) ?? defaultValue; + + public virtual float GetValue(IFloatValue floatValue) + => floatValue.GetValue(_getter); + + public float GetValue(IContextFloatValue floatValue, TContext context) + => floatValue.GetValue(_getter, context); + + public bool GetValue(IBoolValue boolValue) + => boolValue.GetValue(_getter); + + public int GetValue(IIntValue intValue) + => intValue.GetValue(_getter); + + public ValueCalculationService Multiply(IFloatValue multiplier) + => new MultiplierValueCalculationService(_getter, multiplier); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Services/ValueCalculationService.cs.meta b/RedCatEngineUnityProject/Packages/Values/Services/ValueCalculationService.cs.meta new file mode 100644 index 0000000..6e4e96a --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Services/ValueCalculationService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: bdda3152829f4ed0b32022fcdc0c066e +timeCreated: 1727096612 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Services/VariableContainer.cs b/RedCatEngineUnityProject/Packages/Values/Services/VariableContainer.cs new file mode 100644 index 0000000..f76f56f --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Services/VariableContainer.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using RedCatEngine.CommonServices.Containers.Components; +using RedCatEngine.CommonServices.SpecialTypes.ChangedValues.BasedTypes; +using RedCatEngine.DependencyInjection.Containers.Attributes; +using RedCatEngine.Values.Variants.Contents.Configs.Variables; + +namespace RedCatEngine.Values.Services +{ + public class VariableContainer : IRedComponent + { + public event Action ChangeVariableEvent; + private readonly VariableContainer _parent; + private readonly Dictionary _values = new(); + + [Inject] + public VariableContainer() + { + } + + private VariableContainer(VariableContainer parent) + { + _parent = parent; + } + + public VariableContainer MakeChild() + => new(this); + + private bool TryGetValue(VariableConfig variableConfig, out float result) + { + return _values.TryGetValue(variableConfig, out result); + } + + public float GetValue(VariableConfig variableConfig) + { + if (TryGetValue(variableConfig, out var result) + || (_parent != null + && _parent.TryGetValue(variableConfig, out result))) + return result; + + _values.Add(variableConfig, variableConfig.DefaultValue); + return variableConfig.DefaultValue; + } + + public void SetValue(VariableConfig variableConfig, float value) + { + if (!_values.TryGetValue(variableConfig, out _)) + { + ChangeVariableEvent?.Invoke(variableConfig, new FloatDeltaChangeValue(0, value)); + _values.Add(variableConfig, value); + return; + } + + var oldValue = _values[variableConfig]; + _values[variableConfig] = value; + ChangeVariableEvent?.Invoke(variableConfig, new FloatDeltaChangeValue(oldValue, value)); + } + + public void Clear() + { + _values.Clear(); + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Services/VariableContainer.cs.meta b/RedCatEngineUnityProject/Packages/Values/Services/VariableContainer.cs.meta new file mode 100644 index 0000000..a157aa8 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Services/VariableContainer.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f7c4560f947a478e80a3d2c2994027ea +timeCreated: 1729172322 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Values.asmdef b/RedCatEngineUnityProject/Packages/Values/Values.asmdef index ac9045c..38fd9c9 100644 --- a/RedCatEngineUnityProject/Packages/Values/Values.asmdef +++ b/RedCatEngineUnityProject/Packages/Values/Values.asmdef @@ -4,7 +4,8 @@ "references": [ "GUID:bc1a77b6bbee94316b30d47e73c29c41", "GUID:79ad2193969254fbd829729521e3eee3", - "GUID:687b69a268bf4402bb854a43d7732d8a" + "GUID:687b69a268bf4402bb854a43d7732d8a", + "GUID:b8800b26ba16516489a32c4ee4cd1d0f" ], "includePlatforms": [], "excludePlatforms": [], diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Configs/BoolBaseValueConfig.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Configs/BoolBaseValueConfig.cs index e9c428f..ae59080 100644 --- a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Configs/BoolBaseValueConfig.cs +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Configs/BoolBaseValueConfig.cs @@ -1,9 +1,11 @@ -using RedCatEngine.Values.Base; +using RedCatEngine.Values.Base.BaseRealisations; +using RedCatEngine.Values.Base.Interfaces; using SerializeReferenceEditor; using UnityEngine; namespace RedCatEngine.Values.Variants.Contents.Configs.Configs { + [SRHidden] [CreateAssetMenu(menuName = "Configs/Values/Bool", fileName = nameof(BoolBaseValueConfig))] public class BoolBaseValueConfig : BaseValueConfig { diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Configs/FloatBaseValueConfig.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Configs/FloatBaseValueConfig.cs index 4c1e273..5b98e94 100644 --- a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Configs/FloatBaseValueConfig.cs +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Configs/FloatBaseValueConfig.cs @@ -1,9 +1,11 @@ -using RedCatEngine.Values.Base; +using RedCatEngine.Values.Base.BaseRealisations; +using RedCatEngine.Values.Base.Interfaces; using SerializeReferenceEditor; using UnityEngine; namespace RedCatEngine.Values.Variants.Contents.Configs.Configs { + [SRHidden] [CreateAssetMenu(menuName = "Configs/Values/Float", fileName = nameof(FloatBaseValueConfig))] public class FloatBaseValueConfig : BaseValueConfig, IFloatValue { diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Links/BoolConfigLinkValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Links/BoolConfigLinkValue.cs index 99aaf06..c944d37 100644 --- a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Links/BoolConfigLinkValue.cs +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Links/BoolConfigLinkValue.cs @@ -1,10 +1,13 @@ using System; -using RedCatEngine.Values.Base; +using RedCatEngine.Values.Base.BaseRealisations; +using RedCatEngine.Values.Base.Interfaces; using SerializeReferenceEditor; namespace RedCatEngine.Values.Variants.Contents.Configs.Links { [Serializable] [SRName("ConfigLink/ConfigLink Bool")] - public class BoolConfigLinkValue : BaseConfigLinkValue, IBoolValue { } + public class BoolConfigLinkValue : BaseConfigLinkValue, IBoolValue + { + } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Links/FloatConfigLinkValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Links/FloatConfigLinkValue.cs index 975970a..339fedc 100644 --- a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Links/FloatConfigLinkValue.cs +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Links/FloatConfigLinkValue.cs @@ -1,10 +1,13 @@ using System; -using RedCatEngine.Values.Base; +using RedCatEngine.Values.Base.BaseRealisations; +using RedCatEngine.Values.Base.Interfaces; using SerializeReferenceEditor; namespace RedCatEngine.Values.Variants.Contents.Configs.Links { [Serializable] [SRName("ConfigLink/ConfigLink Float")] - public class FloatConfigLinkValue : BaseConfigLinkValue, IFloatValue { } + public class FloatConfigLinkValue : BaseConfigLinkValue, IFloatValue + { + } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables.meta b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables.meta new file mode 100644 index 0000000..ce8d797 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 00653c32d6d449beb38ae9cf374c5c39 +timeCreated: 1729173101 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables/OverrideVariableConfigCalculateValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables/OverrideVariableConfigCalculateValue.cs new file mode 100644 index 0000000..a844033 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables/OverrideVariableConfigCalculateValue.cs @@ -0,0 +1,18 @@ +using System; +using RedCatEngine.Values.Base.Interfaces; +using SerializeReferenceEditor; +using UnityEngine; + +namespace RedCatEngine.Values.Variants.Contents.Configs.Variables +{ + [Serializable] + public class OverrideVariableConfigCalculateValue + { + [HideInInspector] + public string DebugName; + public VariableConfig Variable; + [SR] + [SerializeReference] + public IFloatValue Value; + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables/OverrideVariableConfigCalculateValue.cs.meta b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables/OverrideVariableConfigCalculateValue.cs.meta new file mode 100644 index 0000000..483aed1 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables/OverrideVariableConfigCalculateValue.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 76cef0f4ef66488ca0e2444a75f1656c +timeCreated: 1755002887 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables/VariableConfig.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables/VariableConfig.cs new file mode 100644 index 0000000..86a7759 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables/VariableConfig.cs @@ -0,0 +1,11 @@ +using RedCatEngine.Configs; +using UnityEngine; + +namespace RedCatEngine.Values.Variants.Contents.Configs.Variables +{ + [CreateAssetMenu(menuName = "Configs/Values/Variable", fileName = nameof(VariableConfig))] + public class VariableConfig : BaseConfig + { + public float DefaultValue; + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables/VariableConfig.cs.meta b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables/VariableConfig.cs.meta new file mode 100644 index 0000000..e60bbb9 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables/VariableConfig.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 5730d369c3c843c1900dfa4c62aacc1c +timeCreated: 1729172396 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables/VariableValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables/VariableValue.cs new file mode 100644 index 0000000..25a3927 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables/VariableValue.cs @@ -0,0 +1,20 @@ +using System; +using RedCatEngine.Values.Base.BaseRealisations; +using RedCatEngine.Values.Base.Interfaces; +using RedCatEngine.Values.Services; +using SerializeReferenceEditor; +using UnityEngine; + +namespace RedCatEngine.Values.Variants.Contents.Configs.Variables +{ + [Serializable] + [SRName("Common/Global Variable")] + public class VariableValue : BaseServiceGetterValue, IFloatValue + { + [SerializeField] + private VariableConfig _variable; + + protected override float GetValueFromServices(VariableContainer single) + => single.GetValue(_variable); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables/VariableValue.cs.meta b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables/VariableValue.cs.meta new file mode 100644 index 0000000..cbaff1e --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Configs/Variables/VariableValue.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c2d1c014a5f14dab9594559f059e9bec +timeCreated: 1729173115 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Constants/ConstantBoolValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Constants/ConstantBoolValue.cs index f08fa8f..b617f40 100644 --- a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Constants/ConstantBoolValue.cs +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Constants/ConstantBoolValue.cs @@ -1,25 +1,24 @@ using System; -using RedCatEngine.DependencyInjection.Containers.Interfaces; -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; -using RedCatEngine.Values.Base; +using RedCatEngine.Values.Base.Interfaces; using SerializeReferenceEditor; using UnityEngine; +using IGetterApplicationContainer = + RedCatEngine.DependencyInjection.Containers.Interfaces.Application.IGetterApplicationContainer; namespace RedCatEngine.Values.Variants.Contents.Constants { [Serializable] - [SRName("Constants/Constant Bool")] + [SRName("Common/Constant Bool")] public class ConstantBoolValue : IBoolValue { + [SerializeField] + private bool _value; public static ConstantBoolValue True => new() { _value = true }; public static ConstantBoolValue False => new() { _value = false }; - [SerializeField] - private bool _value; - - public bool GetValue(IApplicationContainer applicationContainer) + public bool GetValue(IGetterApplicationContainer getterContainer) => _value; } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Constants/ConstantFloatValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Constants/ConstantFloatValue.cs index cdbb55a..31663a9 100644 --- a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Constants/ConstantFloatValue.cs +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Constants/ConstantFloatValue.cs @@ -1,21 +1,17 @@ using System; -using RedCatEngine.DependencyInjection.Containers.Interfaces; -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; -using RedCatEngine.Values.Base; +using RedCatEngine.Values.Base.Interfaces; using SerializeReferenceEditor; using UnityEngine; +using IGetterApplicationContainer = + RedCatEngine.DependencyInjection.Containers.Interfaces.Application.IGetterApplicationContainer; namespace RedCatEngine.Values.Variants.Contents.Constants { [Serializable] - [SRName("Constants/Constant Float")] + [SRName("Common/Constant Float")] public class ConstantFloatValue : IFloatValue { - [SerializeField] - private float _value; - - public float GetValue(IApplicationContainer applicationContainer) - => _value; + [SerializeField] private float _value; public ConstantFloatValue() { @@ -26,5 +22,19 @@ public ConstantFloatValue(float value) { _value = value; } + + public static ConstantFloatValue Zero + => new() { _value = 0 }; + + public static ConstantFloatValue One + => new() { _value = 1f }; + + public float GetValue(IGetterApplicationContainer getterContainer) + => _value; + + public override string ToString() + { + return _value + "(const)"; + } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Constants/ConstantIntValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Constants/ConstantIntValue.cs new file mode 100644 index 0000000..31a3923 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Constants/ConstantIntValue.cs @@ -0,0 +1,35 @@ +using System; +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; +using RedCatEngine.Values.Base.Interfaces; +using SerializeReferenceEditor; +using UnityEngine; + +namespace RedCatEngine.Values.Variants.Contents.Constants +{ + [Serializable] + [SRName("Common/Constant Int")] + public class ConstantIntValue : IIntValue + { + [SerializeField] + private int _value; + + public ConstantIntValue() + { + _value = 0; + } + + public ConstantIntValue(int value) + { + _value = value; + } + + public static ConstantIntValue Zero + => new() { _value = 0 }; + + public static ConstantIntValue One + => new() { _value = 1 }; + + public int GetValue(IGetterApplicationContainer getterContainer) + => _value; + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Constants/ConstantIntValue.cs.meta b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Constants/ConstantIntValue.cs.meta new file mode 100644 index 0000000..cd082d9 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Constants/ConstantIntValue.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2bd945df057e403f9ec5ee7b7a1ddf1c +timeCreated: 1728572773 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves.meta b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves.meta new file mode 100644 index 0000000..c26299d --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c93af7ec5be64862b90985f723304cae +timeCreated: 1727092749 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/ClampCurveValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/ClampCurveValue.cs new file mode 100644 index 0000000..5fba288 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/ClampCurveValue.cs @@ -0,0 +1,24 @@ +using System; +using RedCatEngine.Values.Base.Interfaces; +using UnityEngine; + +namespace RedCatEngine.Values.Variants.Contents.Curves +{ + [Serializable] + public class ClampCurveValue : CurveValue + { + public ClampCurveValue() : base() + { + } + + public ClampCurveValue(AnimationCurve curve, IFloatValue xValue) : base(curve, xValue) + { + } + + protected override float FilterXAxis(float getXValue) + => Mathf.Clamp( + getXValue, + MinXValue, + MaxXValue); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/ClampCurveValue.cs.meta b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/ClampCurveValue.cs.meta new file mode 100644 index 0000000..53b603c --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/ClampCurveValue.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7c86a0ed179e460a9118c006334813e0 +timeCreated: 1727093098 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/CurveValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/CurveValue.cs new file mode 100644 index 0000000..c71bb63 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/CurveValue.cs @@ -0,0 +1,48 @@ +using System; +using System.Linq; +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; +using RedCatEngine.Values.Base.Interfaces; +using RedCatEngine.Values.Variants.Contents.Constants; +using SerializeReferenceEditor; +using UnityEngine; + +namespace RedCatEngine.Values.Variants.Contents.Curves +{ + [Serializable] + public abstract class CurveValue : IFloatValue + { + [SerializeField] + private AnimationCurve _curve; + + [SerializeField] + protected float MinXValue; + [SerializeReference] + protected float MaxXValue; + [SR] + [SerializeReference] + private IFloatValue _xValue = ConstantFloatValue.Zero; + + protected CurveValue() + { + } + + protected CurveValue(AnimationCurve curve, IFloatValue xValue) + { + _xValue = xValue; + _curve = curve; + MinXValue = _curve.keys.First().time; + MaxXValue = _curve.keys.Last().time; + } + + public float GetValue(IGetterApplicationContainer getterContainer) + { + var x = FilterXAxis(GetXValue(getterContainer)); + return _curve.Evaluate(x); + } + + private float GetXValue(IGetterApplicationContainer getterContainer) + => _xValue.GetValue(getterContainer); + + protected abstract float FilterXAxis(float getXValue); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/CurveValue.cs.meta b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/CurveValue.cs.meta new file mode 100644 index 0000000..b31731f --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/CurveValue.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3537bed8ddf1476baf2800520d45eebe +timeCreated: 1727092946 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/CurveValueData.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/CurveValueData.cs new file mode 100644 index 0000000..0e603db --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/CurveValueData.cs @@ -0,0 +1,37 @@ +using System; +using RedCatEngine.Values.Base.Interfaces; +using RedCatEngine.Values.Variants.Contents.Constants; +using SerializeReferenceEditor; +using UnityEngine; + +namespace RedCatEngine.Values.Variants.Contents.Curves +{ + internal enum CurveType + { + Duplication, + Clamp + } + + [Serializable] + public class CurveValueData + { + [SerializeField] + private AnimationCurve _curve; + + [SerializeField] + private CurveType _curveType; + [SR] + [SerializeReference] + private IFloatValue _xValue = ConstantFloatValue.Zero; + + public CurveValue Make() + { + return _curveType switch + { + CurveType.Duplication => new DuplicationCurveValue(_curve, _xValue), + CurveType.Clamp => new ClampCurveValue(_curve, _xValue), + _ => throw new ArgumentOutOfRangeException() + }; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/CurveValueData.cs.meta b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/CurveValueData.cs.meta new file mode 100644 index 0000000..4ce3cc4 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/CurveValueData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: fdba7c0da84442918f805be9aa7ecd77 +timeCreated: 1727092761 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/DuplicationCurveValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/DuplicationCurveValue.cs new file mode 100644 index 0000000..8b4dbdd --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/DuplicationCurveValue.cs @@ -0,0 +1,31 @@ +using System; +using RedCatEngine.Values.Base.Interfaces; +using UnityEngine; + +namespace RedCatEngine.Values.Variants.Contents.Curves +{ + [Serializable] + public class DuplicationCurveValue : CurveValue + { + public DuplicationCurveValue() : base() + { + } + + public DuplicationCurveValue(AnimationCurve curve, IFloatValue xValue) : base(curve, xValue) + { + } + + protected override float FilterXAxis(float getXValue) + { + var absMax = Mathf.Abs(MaxXValue); + var absMin = Mathf.Abs(MinXValue); + + while (getXValue > MaxXValue) + getXValue -= absMax; + while (getXValue < MinXValue) + getXValue += absMin; + + return getXValue; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/DuplicationCurveValue.cs.meta b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/DuplicationCurveValue.cs.meta new file mode 100644 index 0000000..8d61139 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Curves/DuplicationCurveValue.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c333470a02734d3199d397ca42d33711 +timeCreated: 1727093109 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Rounders.meta b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Rounders.meta new file mode 100644 index 0000000..df95a33 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Rounders.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 63e635975561477bb73aef28721d0ec4 +timeCreated: 1728572855 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Rounders/IntToFloatValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Rounders/IntToFloatValue.cs new file mode 100644 index 0000000..c8e7401 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Rounders/IntToFloatValue.cs @@ -0,0 +1,21 @@ +using System; +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; +using RedCatEngine.Values.Base.Interfaces; +using RedCatEngine.Values.Variants.Contents.Constants; +using SerializeReferenceEditor; +using UnityEngine; + +namespace RedCatEngine.Values.Variants.Contents.Rounders +{ + [Serializable] + [SRName("Converters/Int to Float")] + public class IntToFloatValue : IFloatValue + { + [SR] + [SerializeReference] + private IIntValue _value = new ConstantIntValue(0); + + public float GetValue(IGetterApplicationContainer getterContainer) + => _value.GetValue(getterContainer); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Rounders/IntToFloatValue.cs.meta b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Rounders/IntToFloatValue.cs.meta new file mode 100644 index 0000000..b15dd96 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Rounders/IntToFloatValue.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4edd4b5b3fa045f4a6c582e756af5a95 +timeCreated: 1729166744 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Rounders/RoundFloatToIntValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Rounders/RoundFloatToIntValue.cs new file mode 100644 index 0000000..551a89b --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Rounders/RoundFloatToIntValue.cs @@ -0,0 +1,36 @@ +using System; +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; +using RedCatEngine.Values.Base.Interfaces; +using RedCatEngine.Values.Variants.Contents.Constants; +using SerializeReferenceEditor; +using UnityEngine; + +namespace RedCatEngine.Values.Variants.Contents.Rounders +{ + public enum RoundType + { + Nearest, + Ceiling + } + [Serializable] + [SRName("Converters/Float to Int")] + public class RoundFloatToIntValue : IIntValue + { + [SerializeField] + private RoundType _roundType; + [SR] + [SerializeReference] + private IFloatValue _value = new ConstantFloatValue(0); + + public int GetValue(IGetterApplicationContainer getterContainer) + { + var floatValue = _value.GetValue(getterContainer); + return _roundType switch + { + RoundType.Nearest => (int)Math.Round(floatValue), + RoundType.Ceiling => (int)Math.Ceiling(floatValue), + _ => throw new ArgumentOutOfRangeException() + }; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Rounders/RoundFloatToIntValue.cs.meta b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Rounders/RoundFloatToIntValue.cs.meta new file mode 100644 index 0000000..dc2a742 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Contents/Rounders/RoundFloatToIntValue.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3f57339e18f5483d974d53b624fa0238 +timeCreated: 1728572866 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Comparisons/EqualsValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Comparisons/EqualsValue.cs index ba5df4f..d5e7159 100644 --- a/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Comparisons/EqualsValue.cs +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Comparisons/EqualsValue.cs @@ -1,11 +1,10 @@ using System; -using RedCatEngine.DependencyInjection.Containers.Interfaces; -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; -using RedCatEngine.Values.Base; -using RedCatEngine.Values.Variants.Contents; +using RedCatEngine.Values.Base.Interfaces; using RedCatEngine.Values.Variants.Contents.Constants; using SerializeReferenceEditor; using UnityEngine; +using IGetterApplicationContainer = + RedCatEngine.DependencyInjection.Containers.Interfaces.Application.IGetterApplicationContainer; namespace RedCatEngine.Values.Variants.Logics.Comparisons { @@ -25,7 +24,8 @@ public class EqualsValue : IBoolValue [SerializeReference] private IFloatValue _tolerance = new ConstantFloatValue(0); - public bool GetValue(IApplicationContainer applicationContainer) - => Math.Abs(_baseComparison.GetValue(applicationContainer) - _otherValue.GetValue(applicationContainer)) < _tolerance.GetValue(applicationContainer); + public bool GetValue(IGetterApplicationContainer getterContainer) + => Math.Abs(_baseComparison.GetValue(getterContainer) - _otherValue.GetValue(getterContainer)) + < _tolerance.GetValue(getterContainer); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Comparisons/InIntervalValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Comparisons/InIntervalValue.cs index 611b4e2..2d85a3a 100644 --- a/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Comparisons/InIntervalValue.cs +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Comparisons/InIntervalValue.cs @@ -1,8 +1,6 @@ using System; -using RedCatEngine.DependencyInjection.Containers.Interfaces; using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; -using RedCatEngine.Values.Base; -using RedCatEngine.Values.Variants.Contents; +using RedCatEngine.Values.Base.Interfaces; using RedCatEngine.Values.Variants.Contents.Constants; using SerializeReferenceEditor; using UnityEngine; @@ -13,20 +11,19 @@ namespace RedCatEngine.Values.Variants.Logics.Comparisons [SRName("Comparisons/InInterval")] public class InIntervalValue : IBoolValue { + [SerializeField] + private bool _isEquals; + [SR] [SerializeReference] - private IFloatValue _minValue = new ConstantFloatValue(0); + private IFloatValue _checkValue = new ConstantFloatValue(0); [SR] [SerializeReference] private IFloatValue _maxValue = new ConstantFloatValue(0); - [SR] [SerializeReference] - private IFloatValue _checkValue = new ConstantFloatValue(0); - - [SerializeField] - private bool _isEquals; + private IFloatValue _minValue = new ConstantFloatValue(0); [SR] [SerializeReference] @@ -34,29 +31,33 @@ public class InIntervalValue : IBoolValue public InIntervalValue() { - } - public InIntervalValue(IFloatValue minValue, IFloatValue maxValue, IFloatValue checkValue, bool isEquals = true) + public InIntervalValue( + IFloatValue minValue, + IFloatValue maxValue, + IFloatValue checkValue, + bool isEquals = true + ) { _isEquals = isEquals; _minValue = minValue; _maxValue = maxValue; _checkValue = checkValue; } - - public bool GetValue(IApplicationContainer applicationContainer) + + public bool GetValue(IGetterApplicationContainer getterContainer) { - var minValue = _minValue.GetValue(applicationContainer); - var maxValue = _maxValue.GetValue(applicationContainer); - var checkValue = _checkValue.GetValue(applicationContainer); + var minValue = _minValue.GetValue(getterContainer); + var maxValue = _maxValue.GetValue(getterContainer); + var checkValue = _checkValue.GetValue(getterContainer); - var tolerance = _tolerance.GetValue(applicationContainer); + var tolerance = _tolerance.GetValue(getterContainer); return minValue < checkValue && checkValue < maxValue || - (_isEquals && - (Math.Abs(minValue - checkValue) < tolerance - || Math.Abs(maxValue - checkValue) < tolerance)); + (_isEquals && + (Math.Abs(minValue - checkValue) < tolerance + || Math.Abs(maxValue - checkValue) < tolerance)); } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Comparisons/LessValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Comparisons/LessValue.cs index 3c0fce0..eaf5246 100644 --- a/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Comparisons/LessValue.cs +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Comparisons/LessValue.cs @@ -1,11 +1,10 @@ using System; -using RedCatEngine.DependencyInjection.Containers.Interfaces; -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; -using RedCatEngine.Values.Base; -using RedCatEngine.Values.Variants.Contents; +using RedCatEngine.Values.Base.Interfaces; using RedCatEngine.Values.Variants.Contents.Constants; using SerializeReferenceEditor; using UnityEngine; +using IGetterApplicationContainer = + RedCatEngine.DependencyInjection.Containers.Interfaces.Application.IGetterApplicationContainer; namespace RedCatEngine.Values.Variants.Logics.Comparisons { @@ -21,7 +20,7 @@ public class LessValue : IBoolValue [SerializeReference] private IFloatValue _otherValue = new ConstantFloatValue(0); - public bool GetValue(IApplicationContainer applicationContainer) - => _baseComparison.GetValue(applicationContainer) < _otherValue.GetValue(applicationContainer); + public bool GetValue(IGetterApplicationContainer getterContainer) + => _baseComparison.GetValue(getterContainer) < _otherValue.GetValue(getterContainer); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Comparisons/MoreValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Comparisons/MoreValue.cs index f4fef37..3e3e845 100644 --- a/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Comparisons/MoreValue.cs +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Comparisons/MoreValue.cs @@ -1,11 +1,10 @@ using System; -using RedCatEngine.DependencyInjection.Containers.Interfaces; -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; -using RedCatEngine.Values.Base; -using RedCatEngine.Values.Variants.Contents; +using RedCatEngine.Values.Base.Interfaces; using RedCatEngine.Values.Variants.Contents.Constants; using SerializeReferenceEditor; using UnityEngine; +using IGetterApplicationContainer = + RedCatEngine.DependencyInjection.Containers.Interfaces.Application.IGetterApplicationContainer; namespace RedCatEngine.Values.Variants.Logics.Comparisons { @@ -21,7 +20,7 @@ public class MoreValue : IBoolValue [SerializeReference] private IFloatValue _otherValue = new ConstantFloatValue(0); - public bool GetValue(IApplicationContainer applicationContainer) - => _baseComparison.GetValue(applicationContainer) > _otherValue.GetValue(applicationContainer); + public bool GetValue(IGetterApplicationContainer getterContainer) + => _baseComparison.GetValue(getterContainer) > _otherValue.GetValue(getterContainer); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Logics/ConditionalFloatValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Logics/ConditionalFloatValue.cs index 91d1de4..c365061 100644 --- a/RedCatEngineUnityProject/Packages/Values/Variants/Logics/ConditionalFloatValue.cs +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Logics/ConditionalFloatValue.cs @@ -1,10 +1,10 @@ using System; using JetBrains.Annotations; -using RedCatEngine.DependencyInjection.Containers.Interfaces; -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; -using RedCatEngine.Values.Base; +using RedCatEngine.Values.Base.Interfaces; using SerializeReferenceEditor; using UnityEngine; +using IGetterApplicationContainer = + RedCatEngine.DependencyInjection.Containers.Interfaces.Application.IGetterApplicationContainer; namespace RedCatEngine.Values.Variants.Logics { @@ -16,22 +16,20 @@ public class ConditionalFloatValue : IFloatValue [SerializeReference] [UsedImplicitly] private IBoolValue _checkValue; - [SR] [SerializeReference] [UsedImplicitly] private IFloatValue _value; - [SR] [SerializeReference] [UsedImplicitly] private IFloatValue _alternativeValue; - public float GetValue(IApplicationContainer applicationContainer) + public float GetValue(IGetterApplicationContainer getterContainer) { - return _checkValue.GetValue(applicationContainer) - ? _value.GetValue(applicationContainer) - : _alternativeValue.GetValue(applicationContainer); + return _checkValue.GetValue(getterContainer) + ? _value.GetValue(getterContainer) + : _alternativeValue.GetValue(getterContainer); } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Operands/AndValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Operands/AndValue.cs index 25fdc44..a826f86 100644 --- a/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Operands/AndValue.cs +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Operands/AndValue.cs @@ -1,11 +1,10 @@ using System; -using RedCatEngine.DependencyInjection.Containers.Interfaces; -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; -using RedCatEngine.Values.Base; -using RedCatEngine.Values.Variants.Contents; +using RedCatEngine.Values.Base.Interfaces; using RedCatEngine.Values.Variants.Contents.Constants; using SerializeReferenceEditor; using UnityEngine; +using IGetterApplicationContainer = + RedCatEngine.DependencyInjection.Containers.Interfaces.Application.IGetterApplicationContainer; namespace RedCatEngine.Values.Variants.Logics.Operands { @@ -21,7 +20,7 @@ public class AndValue : IBoolValue [SerializeReference] private IBoolValue _right = ConstantBoolValue.False; - public bool GetValue(IApplicationContainer applicationContainer) - => _left.GetValue(applicationContainer) && _right.GetValue(applicationContainer); + public bool GetValue(IGetterApplicationContainer getterContainer) + => _left.GetValue(getterContainer) && _right.GetValue(getterContainer); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Operands/NotValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Operands/NotValue.cs index 5594999..d4b4570 100644 --- a/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Operands/NotValue.cs +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Operands/NotValue.cs @@ -1,11 +1,10 @@ using System; -using RedCatEngine.DependencyInjection.Containers.Interfaces; -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; -using RedCatEngine.Values.Base; -using RedCatEngine.Values.Variants.Contents; +using RedCatEngine.Values.Base.Interfaces; using RedCatEngine.Values.Variants.Contents.Constants; using SerializeReferenceEditor; using UnityEngine; +using IGetterApplicationContainer = + RedCatEngine.DependencyInjection.Containers.Interfaces.Application.IGetterApplicationContainer; namespace RedCatEngine.Values.Variants.Logics.Operands { @@ -17,7 +16,7 @@ public class NotValue : IBoolValue [SerializeReference] private IBoolValue _value = ConstantBoolValue.False; - public bool GetValue(IApplicationContainer applicationContainer) - => !_value.GetValue(applicationContainer); + public bool GetValue(IGetterApplicationContainer getterContainer) + => !_value.GetValue(getterContainer); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Operands/OrValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Operands/OrValue.cs index dcc50ad..c349c4d 100644 --- a/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Operands/OrValue.cs +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Logics/Operands/OrValue.cs @@ -1,11 +1,10 @@ using System; -using RedCatEngine.DependencyInjection.Containers.Interfaces; -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; -using RedCatEngine.Values.Base; -using RedCatEngine.Values.Variants.Contents; +using RedCatEngine.Values.Base.Interfaces; using RedCatEngine.Values.Variants.Contents.Constants; using SerializeReferenceEditor; using UnityEngine; +using IGetterApplicationContainer = + RedCatEngine.DependencyInjection.Containers.Interfaces.Application.IGetterApplicationContainer; namespace RedCatEngine.Values.Variants.Logics.Operands { @@ -21,7 +20,7 @@ public class OrValue : IBoolValue [SerializeReference] private IBoolValue _right = ConstantBoolValue.False; - public bool GetValue(IApplicationContainer applicationContainer) - => _left.GetValue(applicationContainer) || _right.GetValue(applicationContainer); + public bool GetValue(IGetterApplicationContainer getterContainer) + => _left.GetValue(getterContainer) || _right.GetValue(getterContainer); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Operations/AddValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Operations/AddValue.cs index f0ccfba..d1e7fc1 100644 --- a/RedCatEngineUnityProject/Packages/Values/Variants/Operations/AddValue.cs +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Operations/AddValue.cs @@ -1,9 +1,9 @@ using System; -using RedCatEngine.DependencyInjection.Containers.Interfaces; -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; -using RedCatEngine.Values.Base; +using RedCatEngine.Values.Base.Interfaces; using SerializeReferenceEditor; using UnityEngine; +using IGetterApplicationContainer = + RedCatEngine.DependencyInjection.Containers.Interfaces.Application.IGetterApplicationContainer; namespace RedCatEngine.Values.Variants.Operations { @@ -13,9 +13,9 @@ public class AddValue : IFloatValue { [SR] [SerializeReference] - private IFloatValue[] _values = {}; + private IFloatValue[] _values = { }; - public float GetValue(IApplicationContainer applicationContainer) + public float GetValue(IGetterApplicationContainer getterContainer) { if (_values.Length == 0) return 0; @@ -23,7 +23,7 @@ public float GetValue(IApplicationContainer applicationContainer) var resultValue = 0f; foreach (var floatValue in _values) { - resultValue += floatValue.GetValue(applicationContainer); + resultValue += floatValue.GetValue(getterContainer); } return resultValue; diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Operations/DivisionValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Operations/DivisionValue.cs new file mode 100644 index 0000000..c051dd9 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Operations/DivisionValue.cs @@ -0,0 +1,33 @@ +using System; +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; +using RedCatEngine.Values.Base.Interfaces; +using SerializeReferenceEditor; +using UnityEngine; + +namespace RedCatEngine.Values.Variants.Operations +{ + [Serializable] + [SRName("Operations/Division")] + public class DivisionValue : IFloatValue + { + [Header("Result = Base / Diver")] + [SR] + [SerializeReference] + private IFloatValue _base; + [SR] + [SerializeReference] + private IFloatValue _diver; + + public float GetValue(IGetterApplicationContainer getterContainer) + { + var baseValue = _base.GetValue(getterContainer); + var diverValue = _diver.GetValue(getterContainer); + + if (diverValue != 0) + return baseValue / diverValue; + + Debug.LogError("Division by zero"); + return 0; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Operations/DivisionValue.cs.meta b/RedCatEngineUnityProject/Packages/Values/Variants/Operations/DivisionValue.cs.meta new file mode 100644 index 0000000..7fff6ea --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Operations/DivisionValue.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3258391ba90d4a4ca44d413cf51fc098 +timeCreated: 1744290230 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Operations/MultiplyValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Operations/MultiplyValue.cs index e0c25f0..4cfa964 100644 --- a/RedCatEngineUnityProject/Packages/Values/Variants/Operations/MultiplyValue.cs +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Operations/MultiplyValue.cs @@ -1,9 +1,9 @@ using System; -using RedCatEngine.DependencyInjection.Containers.Interfaces; -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; -using RedCatEngine.Values.Base; +using RedCatEngine.Values.Base.Interfaces; using SerializeReferenceEditor; using UnityEngine; +using IGetterApplicationContainer = + RedCatEngine.DependencyInjection.Containers.Interfaces.Application.IGetterApplicationContainer; namespace RedCatEngine.Values.Variants.Operations { @@ -13,9 +13,9 @@ public class MultiplyValue : IFloatValue { [SR] [SerializeReference] - private IFloatValue[] _values = {}; + private IFloatValue[] _values = { }; - public float GetValue(IApplicationContainer applicationContainer) + public float GetValue(IGetterApplicationContainer getterContainer) { if (_values.Length == 0) return 0; @@ -23,7 +23,7 @@ public float GetValue(IApplicationContainer applicationContainer) var resultValue = 1f; foreach (var floatValue in _values) { - resultValue *= floatValue.GetValue(applicationContainer); + resultValue *= floatValue.GetValue(getterContainer); } return resultValue; diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Operations/SubtractionValue.cs b/RedCatEngineUnityProject/Packages/Values/Variants/Operations/SubtractionValue.cs new file mode 100644 index 0000000..7c41b18 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Operations/SubtractionValue.cs @@ -0,0 +1,28 @@ +using System; +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; +using RedCatEngine.Values.Base.Interfaces; +using SerializeReferenceEditor; +using UnityEngine; + +namespace RedCatEngine.Values.Variants.Operations +{ + [Serializable] + [SRName("Operations/Subtract")] + public class SubtractionValue : IFloatValue + { + [Header("Result = Base - Subtracted")] + [SR] + [SerializeReference] + private IFloatValue _base; + [SR] + [SerializeReference] + private IFloatValue _subtracted; + + public float GetValue(IGetterApplicationContainer getterContainer) + { + var baseValue = _base.GetValue(getterContainer); + var diverValue = _subtracted.GetValue(getterContainer); + return baseValue - diverValue; + } + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Values/Variants/Operations/SubtractionValue.cs.meta b/RedCatEngineUnityProject/Packages/Values/Variants/Operations/SubtractionValue.cs.meta new file mode 100644 index 0000000..5d480a8 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Values/Variants/Operations/SubtractionValue.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 30bfac70d5e44cc29d8bd07bf6e8b745 +timeCreated: 1744290400 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Attributes.meta b/RedCatEngineUnityProject/Packages/Windows/Attributes.meta new file mode 100644 index 0000000..a43071a --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Windows/Attributes.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: cb463c6057a0c42fea2dfb32611e2dbf +timeCreated: 1734617774 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Attributes/InjectModelContextAttribute.cs b/RedCatEngineUnityProject/Packages/Windows/Attributes/InjectModelContextAttribute.cs new file mode 100644 index 0000000..07433a5 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Windows/Attributes/InjectModelContextAttribute.cs @@ -0,0 +1,10 @@ +using System; + +namespace Infrastructure.Windows.Attributes +{ + [AttributeUsage(AttributeTargets.Method)] + public class InjectModelContextAttribute : Attribute + { + + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Attributes/InjectModelContextAttribute.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Attributes/InjectModelContextAttribute.cs.meta new file mode 100644 index 0000000..3757c0e --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Windows/Attributes/InjectModelContextAttribute.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: cac5eea7595c94d50a8119fcc10cbf79 +timeCreated: 1734617791 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Components.meta b/RedCatEngineUnityProject/Packages/Windows/Components.meta index a0f6760..a34f979 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Components.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Components.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: b432c5e5ae5e49129a63ab65ba02761b +guid: e380783ac923340528070f32db9623f9 timeCreated: 1713125479 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Components/BasePresenter.cs b/RedCatEngineUnityProject/Packages/Windows/Components/BasePresenter.cs index ff6cd06..a375c08 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Components/BasePresenter.cs +++ b/RedCatEngineUnityProject/Packages/Windows/Components/BasePresenter.cs @@ -1,36 +1,38 @@ -using RedCatEngine.Windows.Interfaces; +using System; +using Infrastructure.Windows.Interfaces; -namespace RedCatEngine.Windows.Components +namespace Infrastructure.Windows.Components { public abstract class BasePresenter : IPresenter where TView : IView - where TModel : IModel + where TModel : class, IModel { - private readonly TView View; - protected readonly TModel Model; + public event Action CloseEvent; - protected BasePresenter(TView view, TModel model) + protected readonly TView View; + + protected BasePresenter(TView view) { View = view; - Model = model; } - public void Open() + public void Open(IModel model) { - View.CloseEvent += Close; - DoOpen(View, Model); + View.ClickCloseEvent += Close; + DoOpen(model as TModel); View.Open(); } public void Close() { - View.CloseEvent -= Close; - DoClose(View, Model); + View.ClickCloseEvent -= Close; + DoClose(); View.Close(); + CloseEvent?.Invoke(); } - protected abstract void DoClose(TView view, TModel model); + protected abstract void DoClose(); - protected abstract void DoOpen(TView view, TModel model); + protected abstract void DoOpen(TModel model); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Components/BasePresenter.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Components/BasePresenter.cs.meta index 79f493a..e944c29 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Components/BasePresenter.cs.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Components/BasePresenter.cs.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: b93c38731a6a4524af6b58bf602bf496 +guid: e94574ce46dca4b88958fe1654e72524 timeCreated: 1713125369 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Components/BaseView.cs b/RedCatEngineUnityProject/Packages/Windows/Components/BaseView.cs index 62ec295..2da415d 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Components/BaseView.cs +++ b/RedCatEngineUnityProject/Packages/Windows/Components/BaseView.cs @@ -1,37 +1,65 @@ using System; +using System.Collections; +using Infrastructure.Windows.Interfaces; using JetBrains.Annotations; using RedCatEngine.DependencyInjection.Specials.Components; -using RedCatEngine.Windows.Interfaces; -namespace RedCatEngine.Windows.Components +namespace Infrastructure.Windows.Components { public abstract class BaseView : MonoConstruct, IView { - public event Action CloseEvent; + private bool _isOpen; + public event Action ClickCloseEvent; + + public bool IsOpen + => _isOpen; public void Open() { + _isOpen = true; gameObject.SetActive(true); DoOpen(); + + StartCoroutine(OnNextFrameRender()); } public void Close() { gameObject.SetActive(false); DoClose(); + _isOpen = false; + } + + private IEnumerator OnNextFrameRender() + { + yield return null; + DoAfterOpen(); } + /// + /// Действия на следующий кадр после спавна префаба View. То есть после инициализации всех размеров и тд + /// + protected virtual void DoAfterOpen() + { + } + + /// + /// Действия при спавне префаба View. + /// Если есть механики, завязанные на размерах и/или позициях элементов, + /// то стоит использовать , + /// так как на данном этапе движок Unity + /// ещё не успел инициализировать все элементы и привязать им размеры + /// protected virtual void DoOpen() { - } protected virtual void DoClose() { - } + [UsedImplicitly] public void ActionClose() - => CloseEvent?.Invoke(); + => ClickCloseEvent?.Invoke(); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Components/BaseView.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Components/BaseView.cs.meta index a1ce1a1..27c68b7 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Components/BaseView.cs.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Components/BaseView.cs.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: 03eedc944fe0496a9f5669d703399b0c +guid: 713adcc385a6d4bf4988daa780b1cee8 timeCreated: 1713125376 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Components/LayerContainer.cs b/RedCatEngineUnityProject/Packages/Windows/Components/LayerContainer.cs index 05c2cf2..67fc82d 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Components/LayerContainer.cs +++ b/RedCatEngineUnityProject/Packages/Windows/Components/LayerContainer.cs @@ -1,8 +1,8 @@ using System; -using RedCatEngine.Windows.Interfaces; +using Infrastructure.Windows.Interfaces; using UnityEngine; -namespace RedCatEngine.Windows.Components +namespace Infrastructure.Windows.Components { public class LayerContainer : MonoBehaviour, ILayerContainer { diff --git a/RedCatEngineUnityProject/Packages/Windows/Components/LayerContainer.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Components/LayerContainer.cs.meta index 66cb9c5..c614aa0 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Components/LayerContainer.cs.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Components/LayerContainer.cs.meta @@ -1,3 +1,2 @@ fileFormatVersion: 2 -guid: cabb3209dc714e9ea7a7aa7bb039dd4a -timeCreated: 1725462639 \ No newline at end of file +guid: c3718c7fb09074043a3188b962abcd08 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Components/Windows.meta b/RedCatEngineUnityProject/Packages/Windows/Components/Windows.meta index 987ed96..a111bed 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Components/Windows.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Components/Windows.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: 07cda18dded140c59726e215e7fdf33e +guid: 7051a0a05265244df8018fc9366eaef0 timeCreated: 1713449835 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseModelWindowConfig.cs b/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseModelWindowConfig.cs index d4abaa8..b66a46e 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseModelWindowConfig.cs +++ b/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseModelWindowConfig.cs @@ -1,19 +1,18 @@ +using System; +using Infrastructure.Windows.Factory; +using Infrastructure.Windows.Interfaces; using RedCatEngine.DependencyInjection.Containers.Interfaces.Application.GenerationBind; -using RedCatEngine.Windows.Factory; -using RedCatEngine.Windows.Interfaces; -namespace RedCatEngine.Windows.Components.Windows +namespace Infrastructure.Windows.Components.Windows { - public abstract class BaseModelWindowConfig : BaseWindowConfig + public abstract class BaseModelWindowConfig : WindowConfig where TModel : class, IModel where TView : BaseView where TPresenter : IPresenter - where TFactory : WindowCreatorFactory + where TFactory : WindowCreatorFactory { - protected abstract TModel MakeModel(); - - public override IModel GetModel() - => MakeModel(); + public override Type ModelType + => typeof(TModel); public override IWindowData MakeWindowData(ICreator windowContainer, params object[] context) => windowContainer.Create(context).CreateWindow(this, context); diff --git a/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseModelWindowConfig.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseModelWindowConfig.cs.meta index 0ddfb8b..fd239aa 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseModelWindowConfig.cs.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseModelWindowConfig.cs.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: c588dee25600cbd4391eb95d2df3e46a +guid: 69b6f29c6ea47421e8f428f8a3061575 timeCreated: 1713449866 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseModelWindowDataContainerConfig.cs b/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseModelWindowDataContainerConfig.cs deleted file mode 100644 index fea2f44..0000000 --- a/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseModelWindowDataContainerConfig.cs +++ /dev/null @@ -1,14 +0,0 @@ -using RedCatEngine.Windows.Interfaces; - -namespace RedCatEngine.Windows.Components.Windows -{ - public abstract class BaseModelWindowDataContainerConfig : BaseWindowDataContainerConfig where TModel : IModel - { - public bool TryOpen(IModel model, TFactory factory) - { - return model is TModel typedModel && DoOpen(typedModel); - } - - protected abstract bool DoOpen(TModel typedModel); - } -} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseModelWindowDataContainerConfig.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseModelWindowDataContainerConfig.cs.meta deleted file mode 100644 index 4fb3b39..0000000 --- a/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseModelWindowDataContainerConfig.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 70d412cd22da45cebe72901fd79a6f76 -timeCreated: 1713449866 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseWindowConfig.cs b/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseWindowConfig.cs deleted file mode 100644 index 03959d1..0000000 --- a/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseWindowConfig.cs +++ /dev/null @@ -1,22 +0,0 @@ -using RedCatEngine.Configs; -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application.GenerationBind; -using RedCatEngine.Windows.Interfaces; -using UnityEngine; - -namespace RedCatEngine.Windows.Components.Windows -{ - public abstract class BaseWindowConfig : BaseConfig - { - public WindowLayer Layer - => _layer; - public GameObject WindowPrefab - => _windowPrefab; - - [SerializeField] - protected GameObject _windowPrefab; - [SerializeField] - private WindowLayer _layer; - public abstract IModel GetModel(); - public abstract IWindowData MakeWindowData(ICreator windowContainer, params object[] context); - } -} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseWindowDataContainerConfig.cs b/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseWindowDataContainerConfig.cs deleted file mode 100644 index e2dc107..0000000 --- a/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseWindowDataContainerConfig.cs +++ /dev/null @@ -1,19 +0,0 @@ -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; -using RedCatEngine.Windows.Interfaces; -using UnityEngine; - -namespace RedCatEngine.Windows.Components.Windows -{ - public abstract class BaseWindowDataContainerConfig : ScriptableObject, IWindowSettings - { - [SerializeField] - protected GameObject Prefab; - public abstract bool TryOpen(IModel model, IApplicationContainer applicationContainer); - public uint ID { get; } - public WindowLayer Layer { get; } - public bool TryOpen(IApplicationContainer applicationContainer) - { - throw new System.NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseWindowDataContainerConfig.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseWindowDataContainerConfig.cs.meta deleted file mode 100644 index 3f27084..0000000 --- a/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseWindowDataContainerConfig.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 5c673e510e1e4ddfb8c032306ed72e4d -timeCreated: 1713449612 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Components/Windows/WindowConfig.cs b/RedCatEngineUnityProject/Packages/Windows/Components/Windows/WindowConfig.cs new file mode 100644 index 0000000..bcec13e --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Windows/Components/Windows/WindowConfig.cs @@ -0,0 +1,28 @@ +using System; +using Infrastructure.Windows.Interfaces; +using RedCatEngine.Configs; +using RedCatEngine.DependencyInjection.Containers.Interfaces.Application.GenerationBind; +using UnityEngine; + +namespace Infrastructure.Windows.Components.Windows +{ + public abstract class WindowConfig : BaseConfig + { + [SerializeField] private WindowConfig _parent; + [SerializeField] protected GameObject _windowPrefab; + [SerializeField] private WindowLayer _layer; + + public WindowLayer Layer + => _layer; + + public GameObject WindowPrefab + => _windowPrefab; + + public WindowConfig Parent + => _parent; + + public abstract Type ModelType { get; } + + public abstract IWindowData MakeWindowData(ICreator windowContainer, params object[] context); + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseWindowConfig.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Components/Windows/WindowConfig.cs.meta similarity index 53% rename from RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseWindowConfig.cs.meta rename to RedCatEngineUnityProject/Packages/Windows/Components/Windows/WindowConfig.cs.meta index 1238a28..30f751a 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Components/Windows/BaseWindowConfig.cs.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Components/Windows/WindowConfig.cs.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: f39a197c31d5d134f9eeafb420a81d07 +guid: ed90efd2cfa5c49628bb53e6ddba65c3 timeCreated: 1713449612 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Factory.meta b/RedCatEngineUnityProject/Packages/Windows/Factory.meta index bad7b61..b7c62bd 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Factory.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Factory.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: 82c172fdcb534bf8997cc9218041aa90 +guid: 498164c82ce62443e9492c7fc7736553 timeCreated: 1713125389 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Factory/WindowCreatorFactory.cs b/RedCatEngineUnityProject/Packages/Windows/Factory/WindowCreatorFactory.cs index 06ebf56..3149876 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Factory/WindowCreatorFactory.cs +++ b/RedCatEngineUnityProject/Packages/Windows/Factory/WindowCreatorFactory.cs @@ -1,40 +1,50 @@ +using Infrastructure.Windows.Components; +using Infrastructure.Windows.Components.Windows; +using Infrastructure.Windows.Interfaces; using JetBrains.Annotations; +using RedCatEngine.CommonServices.Extensions; +using RedCatEngine.CommonServices.Services.Logs; using RedCatEngine.DependencyInjection.Containers.Attributes; -using RedCatEngine.Windows.Components; -using RedCatEngine.Windows.Components.Windows; -using RedCatEngine.Windows.Interfaces; -namespace RedCatEngine.Windows.Factory +namespace Infrastructure.Windows.Factory { - public class WindowCreatorFactory - where TModel : class, IModel + public class WindowCreatorFactory where TView : BaseView where TPresenter : IPresenter { private readonly ILayerContainer _layerContainer; private readonly IWindowContainer _windowContainer; + private readonly ILogService _log; [Inject] - [UsedImplicitly] - public WindowCreatorFactory(ILayerContainer layerContainer, IWindowContainer windowContainer) + public WindowCreatorFactory(ILayerContainer layerContainer, IWindowContainer windowContainer, ILogService log) { _layerContainer = layerContainer; _windowContainer = windowContainer; + _log = log; } - public IWindowData CreateWindow(BaseWindowConfig config, params object[] context) + public IWindowData CreateWindow(WindowConfig config, params object[] context) { var parentTransform = _layerContainer.GetParentLayer(config.Layer); - var model = config.GetModel() as TModel; + var fullContext = + context.Attach(_log); var view = _windowContainer.CreateAndGetComponent( config.WindowPrefab, parentTransform, - context: model); - var presenter = _windowContainer.Create(model, view, context); + context: fullContext + ); + var presenter = _windowContainer.Create( + view, + fullContext + ); return new WindowData( - model, + config, + config.Parent, + config.Layer, view, - presenter); + presenter + ); } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Factory/WindowCreatorFactory.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Factory/WindowCreatorFactory.cs.meta index d862828..d6fbf2f 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Factory/WindowCreatorFactory.cs.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Factory/WindowCreatorFactory.cs.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: 9d8ed039fed34b9788a1b2c8f6fda61c +guid: 2ddfbd51449ca493d88299ef3276434c timeCreated: 1725456698 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Factory/WindowData.cs b/RedCatEngineUnityProject/Packages/Windows/Factory/WindowData.cs index fc8ec77..41e5b76 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Factory/WindowData.cs +++ b/RedCatEngineUnityProject/Packages/Windows/Factory/WindowData.cs @@ -1,33 +1,72 @@ -using RedCatEngine.Windows.Interfaces; +using System; +using Infrastructure.Windows.Components.Windows; +using Infrastructure.Windows.Interfaces; -namespace RedCatEngine.Windows.Factory +namespace Infrastructure.Windows.Factory { public class WindowData : IWindowData { - private readonly IModel _model; - private readonly IView _view; private readonly IPresenter _presenter; + private readonly WindowConfig _parentConfig; + private readonly IView _view; + private Action _onCloseCallBack; + + public WindowLayer Layer { get; } + + public WindowConfig Config { get; } + + public bool IsOpen + => _view.IsOpen; public WindowData( - IModel model, + WindowConfig currentConfig, + WindowConfig parentConfig, + WindowLayer layer, IView view, IPresenter presenter ) { - _model = model; + Layer = layer; + Config = currentConfig; + _parentConfig = parentConfig; _view = view; _presenter = presenter; + _presenter.CloseEvent += ClosePresenterTrigger; + } + + public bool TryGetParent(out WindowConfig parent) + { + parent = _parentConfig; + return parent != null; } - public void Open() + public void Open(IModel model) { - _presenter.Open(); + if (IsOpen) + return; + _presenter.Open(model); } public void Close() { + if (!IsOpen) + return; _presenter.Close(); } + + public void SetCloseCallback(Action onCloseCallBack) + => _onCloseCallBack = onCloseCallBack; + + public void InjectContext(object[] context) + { + } + + private void ClosePresenterTrigger() + { + _presenter.CloseEvent -= ClosePresenterTrigger; + _onCloseCallBack?.Invoke(); + _onCloseCallBack = null; + } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Factory/WindowData.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Factory/WindowData.cs.meta index bfc2960..377192c 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Factory/WindowData.cs.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Factory/WindowData.cs.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: 6ecb864fadb24c65ac5adb0f04d80c7a +guid: dedc051e673ea44699a3babe1498e6dd timeCreated: 1725457077 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Factory/WindowFactory.cs b/RedCatEngineUnityProject/Packages/Windows/Factory/WindowFactory.cs deleted file mode 100644 index 8c20427..0000000 --- a/RedCatEngineUnityProject/Packages/Windows/Factory/WindowFactory.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Collections.Generic; -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; -using RedCatEngine.Windows.Components.Windows; -using RedCatEngine.Windows.Interfaces; - -namespace RedCatEngine.Windows.Factory -{ - public class WindowFactory - { - private readonly ILayerContainer _layerContainer; - private readonly IApplicationContainer _applicationContainer; - private readonly Dictionary _windows = new(); - - public WindowFactory(ILayerContainer layerContainer, IApplicationContainer applicationContainer) - { - _layerContainer = layerContainer; - _applicationContainer = applicationContainer; - } - - public void Open(IWindowSettings windowSettings) where TModel : IModel - { - if (_windows.TryGetValue(windowSettings.ID, out var window)) - { - if(window.TryOpen(null, _applicationContainer)) - return; - } - var parent = _layerContainer.GetParentLayer(windowSettings.Layer); - } - } -} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Factory/WindowFactory.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Factory/WindowFactory.cs.meta deleted file mode 100644 index ddc8631..0000000 --- a/RedCatEngineUnityProject/Packages/Windows/Factory/WindowFactory.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 08ffaa1a8c1647fb9f47b893d9b267f0 -timeCreated: 1713125397 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces.meta b/RedCatEngineUnityProject/Packages/Windows/Interfaces.meta index ac52543..07db3f0 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: 9e35b1c6986c4255b48dc902dfb373cd +guid: bf7a6250757214a03a25e89572abf520 timeCreated: 1713125622 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/ILayerContainer.cs b/RedCatEngineUnityProject/Packages/Windows/Interfaces/ILayerContainer.cs index 8d9f8f6..3e94cf3 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces/ILayerContainer.cs +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces/ILayerContainer.cs @@ -1,6 +1,6 @@ using UnityEngine; -namespace RedCatEngine.Windows.Interfaces +namespace Infrastructure.Windows.Interfaces { public interface ILayerContainer { diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/ILayerContainer.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Interfaces/ILayerContainer.cs.meta index 619ec79..ed5a04f 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces/ILayerContainer.cs.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces/ILayerContainer.cs.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: fcba59294aa4440d987339b25473630f +guid: 0a638f41714da4bad85c7c95072c50dd timeCreated: 1713125612 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IModel.cs b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IModel.cs index 7ffbd3a..353285e 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IModel.cs +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IModel.cs @@ -1,4 +1,4 @@ -namespace RedCatEngine.Windows.Interfaces +namespace Infrastructure.Windows.Interfaces { public interface IModel { diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IModel.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IModel.cs.meta index 64e1e10..39a27cf 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IModel.cs.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IModel.cs.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: 0474e47e8c86487896167537b5890eea +guid: bf983b98786524f50b022f99f0013ae0 timeCreated: 1713126305 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IPresenter.cs b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IPresenter.cs index c918a8e..6b8d8c1 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IPresenter.cs +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IPresenter.cs @@ -1,8 +1,11 @@ -namespace RedCatEngine.Windows.Interfaces +using System; + +namespace Infrastructure.Windows.Interfaces { public interface IPresenter { - void Open(); + event Action CloseEvent; + void Open(IModel model); void Close(); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IPresenter.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IPresenter.cs.meta index 6640c34..52b95ae 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IPresenter.cs.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IPresenter.cs.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: c0380e070170493cbb7ad3a76e141b5f +guid: 437b9321ee71c4bfbbbb5c490663cb26 timeCreated: 1713452129 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IView.cs b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IView.cs index cf1e1f2..9737316 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IView.cs +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IView.cs @@ -1,10 +1,11 @@ using System; -namespace RedCatEngine.Windows.Interfaces +namespace Infrastructure.Windows.Interfaces { public interface IView { - event Action CloseEvent; + bool IsOpen { get; } + event Action ClickCloseEvent; void Close(); void Open(); } diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IView.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IView.cs.meta index 56ac07a..3346c81 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IView.cs.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IView.cs.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: bda2bd45eea84c79bcc40eb6309ef2af +guid: a603d9acce22c460ba6821cbe2e7be82 timeCreated: 1725453503 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowContainer.cs b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowContainer.cs index 6b1cff6..f7959bd 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowContainer.cs +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowContainer.cs @@ -2,9 +2,10 @@ using RedCatEngine.DependencyInjection.Containers.Interfaces.Application.GenerationBind; using RedCatEngine.DependencyInjection.Containers.Interfaces.Unity; -namespace RedCatEngine.Windows.Interfaces +namespace Infrastructure.Windows.Interfaces { public interface IWindowContainer : IGetterApplicationContainer, ICreator, IMonoCreator { + public IModel FillContextToModel(IModel model, params object[] context); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowContainer.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowContainer.cs.meta index 0ab3204..44bb9e7 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowContainer.cs.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowContainer.cs.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: df06bde9f4eb4b46ba4e4f375fea0b1d +guid: c13dbef852e6944bdbd3bc437bcc4e6f timeCreated: 1725453554 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowData.cs b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowData.cs index 1c6f6ec..6a6792f 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowData.cs +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowData.cs @@ -1,7 +1,16 @@ -namespace RedCatEngine.Windows.Interfaces +using System; +using Infrastructure.Windows.Components.Windows; + +namespace Infrastructure.Windows.Interfaces { public interface IWindowData { - void Open(); + WindowLayer Layer { get; } + bool IsOpen { get; } + WindowConfig Config { get; } + void Open(IModel model); + void Close(); + void SetCloseCallback(Action onCloseCallBack); + bool TryGetParent(out WindowConfig parent); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowData.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowData.cs.meta index ee2f270..d458c78 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowData.cs.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowData.cs.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: 926774881e24406f897093170f93071f +guid: 6e8b547639a62470db9def44e2333aa7 timeCreated: 1725455926 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowService.cs b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowService.cs index 97d3903..702288d 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowService.cs +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowService.cs @@ -1,9 +1,20 @@ -using RedCatEngine.Windows.Components.Windows; +using System; +using Infrastructure.Windows.Components.Windows; -namespace RedCatEngine.Windows.Interfaces +namespace Infrastructure.Windows.Interfaces { public interface IWindowService { - public void Open(BaseWindowConfig windowInfo, params object[] context); + bool IsOpen(WindowConfig windowConfig); + void Open(WindowConfig windowConfig, params object[] context); + + void OpenWithCallbacks( + WindowConfig windowConfig, + Action openCallback, + Action closeCallBack, + params object[] context + ); + + void Close(WindowConfig windowConfig); } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowService.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowService.cs.meta index 99550f9..822a621 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowService.cs.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowService.cs.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: 18e6c20b049a41a6b6be99c66098d63c +guid: ff885a4f2f63a45089ddc51bf0e44619 timeCreated: 1725453336 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowSettings.cs b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowSettings.cs deleted file mode 100644 index 18ce3d0..0000000 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowSettings.cs +++ /dev/null @@ -1,12 +0,0 @@ -using RedCatEngine.DependencyInjection.Containers.Interfaces.Application; - -namespace RedCatEngine.Windows.Interfaces -{ - public interface IWindowSettings - { - uint ID { get; } - WindowLayer Layer { get; } - - bool TryOpen(IApplicationContainer applicationContainer); - } -} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowSettings.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowSettings.cs.meta deleted file mode 100644 index 98b233a..0000000 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces/IWindowSettings.cs.meta +++ /dev/null @@ -1,3 +0,0 @@ -fileFormatVersion: 2 -guid: 31ffc326c3e7449a8ac18346a9080a44 -timeCreated: 1713125442 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/WindowLayer.cs b/RedCatEngineUnityProject/Packages/Windows/Interfaces/WindowLayer.cs index 7299817..5f50224 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces/WindowLayer.cs +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces/WindowLayer.cs @@ -1,9 +1,12 @@ -namespace RedCatEngine.Windows.Interfaces +namespace Infrastructure.Windows.Interfaces { public enum WindowLayer { + None = 0, Screen = 1, Popup = 15, - Warning = 31 + Messages = 30, + Warning = 31, + Phrase = 40 } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/WindowLayer.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Interfaces/WindowLayer.cs.meta index 1ed363b..2b601dd 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Interfaces/WindowLayer.cs.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces/WindowLayer.cs.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: faae96aa65594c178e0942373f756ffd +guid: 2835f2426d07c4305b333a67e1966dea timeCreated: 1713125524 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/WindowLayerConfig.cs b/RedCatEngineUnityProject/Packages/Windows/Interfaces/WindowLayerConfig.cs new file mode 100644 index 0000000..7c36de2 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces/WindowLayerConfig.cs @@ -0,0 +1,9 @@ +using RedCatEngine.Configs; + +namespace Infrastructure.Windows.Interfaces +{ + public class WindowLayerConfig : BaseConfig + { + + } +} \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Interfaces/WindowLayerConfig.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Interfaces/WindowLayerConfig.cs.meta new file mode 100644 index 0000000..57039f5 --- /dev/null +++ b/RedCatEngineUnityProject/Packages/Windows/Interfaces/WindowLayerConfig.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c81bbd221d5445b38ddb2e5c3d840a4d +timeCreated: 1744008203 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Services.meta b/RedCatEngineUnityProject/Packages/Windows/Services.meta index 28ebcc9..98e50dc 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Services.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Services.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: 66cc92bfe83d427a908bdb9a97b08d16 +guid: b1cb6df64864f438bba01260b4256bf0 timeCreated: 1725453329 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Services/WindowContainer.cs b/RedCatEngineUnityProject/Packages/Windows/Services/WindowContainer.cs index 3ca1427..f370cc1 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Services/WindowContainer.cs +++ b/RedCatEngineUnityProject/Packages/Windows/Services/WindowContainer.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; +using Infrastructure.Windows.Attributes; +using Infrastructure.Windows.Interfaces; using RedCatEngine.DependencyInjection.Containers.Attributes; using RedCatEngine.DependencyInjection.Containers.Interfaces.Unity; -using RedCatEngine.Windows.Interfaces; +using RedCatEngine.DependencyInjection.Specials; using UnityEngine; namespace RedCatEngine.Windows.Services @@ -11,6 +13,9 @@ public class WindowContainer : IWindowContainer { private readonly IUnityGameContainer _windowContainerImplementation; + public Injector Injector + => _windowContainerImplementation.Injector; + [Inject] public WindowContainer(IUnityGameContainer windowContainerImplementation) { @@ -22,6 +27,11 @@ public bool TryGetSingle(out T data) return _windowContainerImplementation.TryGetSingle(out data); } + public bool TryGetSingle(Type type, out object data) + { + return _windowContainerImplementation.TryGetSingle(type, out data); + } + public bool TryGetArray(out IEnumerable data) { return _windowContainerImplementation.TryGetArray(out data); @@ -54,96 +64,100 @@ public T Create(params object[] context) public GameObject Create( GameObject prefab, - Vector3 position = default, - Quaternion rotation = default, - Transform parent = null, - bool constructChildren = false, + Vector3 position, + Quaternion rotation, + Transform parent, params object[] context ) { - return _windowContainerImplementation.Create(prefab, + return _windowContainerImplementation.Create( + prefab, position, rotation, parent, - constructChildren, context); } public GameObject Create( GameObject prefab, - Transform parent = null, - bool constructChildren = false, + Transform parent, params object[] context ) { - return _windowContainerImplementation.Create(prefab, + return _windowContainerImplementation.Create( + prefab, parent, - constructChildren, context); } public TBindType CreateAndGetComponent( GameObject prefab, - Vector3 position = default, - Quaternion rotation = default, - Transform parent = null, - bool constructChildren = false, + Vector3 position, + Quaternion rotation, + Transform parent, params object[] context ) where TBindType : Component { - return _windowContainerImplementation.CreateAndGetComponent(prefab, + return _windowContainerImplementation.CreateAndGetComponent( + prefab, position, rotation, parent, - constructChildren, context); } public object CreateAndGetComponent( Type componentType, GameObject prefab, - Transform parent = null, - bool constructChildren = false, + Transform parent, params object[] context ) { - return _windowContainerImplementation.CreateAndGetComponent(componentType, + return _windowContainerImplementation.CreateAndGetComponent( + componentType, prefab, parent, - constructChildren, context); } public TBindType CreateAndGetComponent( GameObject prefab, Transform parent, - bool constructChildren = false, params object[] context ) where TBindType : Component { - return _windowContainerImplementation.CreateAndGetComponent(prefab, + return _windowContainerImplementation.CreateAndGetComponent( + prefab, parent, - constructChildren, context); } public object CreateAndGetComponent( Type componentType, GameObject prefab, - Vector3 position = default, - Quaternion rotation = default, - Transform parent = null, - bool constructChildren = false, + Vector3 position, + Quaternion rotation, + Transform parent, params object[] context ) { - return _windowContainerImplementation.CreateAndGetComponent(componentType, + return _windowContainerImplementation.CreateAndGetComponent( + componentType, prefab, position, rotation, parent, - constructChildren, context); } + + public IModel FillContextToModel(IModel model, params object[] context) + { + _windowContainerImplementation + .Injector + .InjectContextToMethodsWithAttribute( + model, + context); + return model; + } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Services/WindowContainer.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Services/WindowContainer.cs.meta index 7cab113..68fcf23 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Services/WindowContainer.cs.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Services/WindowContainer.cs.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: 6dd4f108d2ec429697161405e53e6578 +guid: 0987d06e7bf0a40daa38814060c661ac timeCreated: 1725462999 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Services/WindowService.cs b/RedCatEngineUnityProject/Packages/Windows/Services/WindowService.cs index 44c8a4e..fa38867 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Services/WindowService.cs +++ b/RedCatEngineUnityProject/Packages/Windows/Services/WindowService.cs @@ -1,35 +1,203 @@ +using System; using System.Collections.Generic; +using System.Linq; +using Infrastructure.Windows.Components.Windows; +using Infrastructure.Windows.Interfaces; +using RedCatEngine.CommonServices.Extensions; +using RedCatEngine.CommonServices.Services.Logs; using RedCatEngine.DependencyInjection.Containers.Attributes; -using RedCatEngine.Windows.Components.Windows; -using RedCatEngine.Windows.Interfaces; namespace RedCatEngine.Windows.Services { public class WindowService : IWindowService { private readonly IWindowContainer _windowContainer; - private readonly Dictionary _windowInfos; + private readonly ILogService _logService; + private readonly Dictionary _windowInfos; + private readonly Dictionary> _parentHierarchy; [Inject] - public WindowService(IWindowContainer windowContainer) + public WindowService(IWindowContainer windowContainer, ILogService logService) { _windowContainer = windowContainer; - _windowInfos = new Dictionary(); + _logService = logService.CreateTag(); + _windowInfos = new Dictionary(); + _parentHierarchy = new Dictionary>(); } - public void Open(BaseWindowConfig windowConfig, params object[] context) + public bool IsOpen(WindowConfig windowConfig) + => _windowInfos.TryGetValue(windowConfig, out var windowData) && windowData.IsOpen; + + public void Open(WindowConfig windowConfig, params object[] context) + { + _logService.LogFormat("Open window {0}", windowConfig.name); + var windowData = PrepareWindowData(windowConfig, context); + windowData.Open( + (IModel)_windowContainer.Create(windowConfig.ModelType, CreateContext(windowConfig, context)) + ); + } + + public void OpenWithCallbacks( + WindowConfig windowConfig, + Action openCallback, + Action closeCallBack, + params object[] context + ) + { + _logService.LogFormat("Open window {0} with callback", windowConfig.name); + var windowData = PrepareWindowData(windowConfig, context); + + openCallback?.Invoke(); + windowData.SetCloseCallback(closeCallBack); + windowData.Open( + (IModel)_windowContainer.Create(windowConfig.ModelType, CreateContext(windowConfig, context)) + ); + } + + private object[] CreateContext(WindowConfig windowConfig, object[] context) + => context.Attach(windowConfig, _logService); + + public void Close(WindowConfig windowConfig) + { + if (!_windowInfos.TryGetValue(windowConfig, out var info)) + return; + + _logService.LogFormat("Open window {0}", windowConfig); + info.Close(); + } + + public void CloseAll() + { + _logService.Log("Close all windows"); + foreach (var windowInfo in _windowInfos) + windowInfo.Value.Close(); + } + + private IWindowData PrepareWindowData(WindowConfig windowConfig, object[] context) + { + var windowData = GetWindowData(windowConfig, context); + var isHasParent = TryOpenParent( + windowConfig, + context, + windowData, + out var parent + ); + + var openedLayer = windowData.Layer; + IEnumerable> windowsForClose; + + if (isHasParent) + { + var parentHierarchy = GetSafeHierarchy(parent); + windowsForClose = _windowInfos.Where( + windowKeyValue + => + { + var tryCloseWindowConfig = windowKeyValue.Key; + var tryCloseWindowData = windowKeyValue.Value; + return tryCloseWindowConfig != windowConfig + && tryCloseWindowConfig != parent + && !parentHierarchy.Contains(tryCloseWindowConfig) + && tryCloseWindowData.Layer == openedLayer + && tryCloseWindowData.IsOpen; + } + ); + } + else + { + if (_parentHierarchy.Keys.Contains(windowConfig)) + { + windowsForClose = _windowInfos.Where( + windowKeyValue + => + { + var tryCloseWindowData = windowKeyValue.Value; + return tryCloseWindowData.Config != windowConfig + && tryCloseWindowData.Layer == openedLayer + && tryCloseWindowData.IsOpen + && !_parentHierarchy[windowConfig].Contains(windowKeyValue.Key); + } + ); + } + else + { + windowsForClose = _windowInfos.Where( + windowKeyValue + => + { + var tryCloseWindowData = windowKeyValue.Value; + return tryCloseWindowData.Config != windowConfig + && tryCloseWindowData.Layer == openedLayer + && tryCloseWindowData.IsOpen + && windowKeyValue.Key != windowConfig; + } + ).ToArray(); + } + } + + var sb = new System.Text.StringBuilder(); + sb.AppendLine( + string.Format("{1} Close {0} windows:", + windowsForClose.Count(), + windowConfig.name)); + foreach (var closeWindow in windowsForClose) + { + sb.AppendLine("\t" + closeWindow.Key.name); + } + _logService.Log(sb.ToString()); + + foreach (var windowKeyValue in windowsForClose) + windowKeyValue.Value.Close(); + + return windowData; + } + + private bool TryOpenParent( + WindowConfig windowConfig, + object[] context, + IWindowData windowData, + out WindowConfig parentWindowConfig + ) + { + var isHasParent = windowData.TryGetParent(out parentWindowConfig); + if (!isHasParent) + return false; + + var value = GetSafeHierarchy(parentWindowConfig); + if (!value.Contains(windowConfig)) + { + value.Add(windowConfig); + } + + Open(parentWindowConfig, context); + + return true; + } + + private List GetSafeHierarchy(WindowConfig parentWindowConfig) + { + if (_parentHierarchy.TryGetValue(parentWindowConfig, out var value)) + return value; + + value = new List(); + _parentHierarchy[parentWindowConfig] = value; + return value; + } + + private IWindowData GetWindowData(WindowConfig windowConfig, object[] context) { IWindowData windowData; - if (_windowInfos.ContainsKey(windowConfig.ID)) + if (_windowInfos.TryGetValue(windowConfig, out var info)) { - windowData = _windowInfos[windowConfig.ID]; + windowData = info; } else { - windowData = windowConfig.MakeWindowData(_windowContainer, context); - _windowInfos.Add(windowConfig.ID, windowData); + windowData = windowConfig.MakeWindowData(_windowContainer, CreateContext(windowConfig, context)); + _windowInfos.Add(windowConfig, windowData); } - windowData.Open(); + + return windowData; } } } \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Services/WindowService.cs.meta b/RedCatEngineUnityProject/Packages/Windows/Services/WindowService.cs.meta index d10fb22..759acac 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Services/WindowService.cs.meta +++ b/RedCatEngineUnityProject/Packages/Windows/Services/WindowService.cs.meta @@ -1,3 +1,3 @@ fileFormatVersion: 2 -guid: 66df02b2221a4d08bc6e55bc2e66c36c +guid: 9b9e97bfae8ab43d29b39f3a5b014548 timeCreated: 1725453344 \ No newline at end of file diff --git a/RedCatEngineUnityProject/Packages/Windows/Windows.asmdef b/RedCatEngineUnityProject/Packages/Windows/Windows.asmdef index c7c8646..d31afd9 100644 --- a/RedCatEngineUnityProject/Packages/Windows/Windows.asmdef +++ b/RedCatEngineUnityProject/Packages/Windows/Windows.asmdef @@ -3,7 +3,8 @@ "rootNamespace": "RedCatEngine.Windows", "references": [ "GUID:687b69a268bf4402bb854a43d7732d8a", - "GUID:bc1a77b6bbee94316b30d47e73c29c41" + "GUID:bc1a77b6bbee94316b30d47e73c29c41", + "GUID:b8800b26ba16516489a32c4ee4cd1d0f" ], "includePlatforms": [], "excludePlatforms": [], diff --git a/RedCatEngineUnityProject/Packages/Windows/package.json b/RedCatEngineUnityProject/Packages/Windows/package.json index a2b0b5f..1c51990 100644 --- a/RedCatEngineUnityProject/Packages/Windows/package.json +++ b/RedCatEngineUnityProject/Packages/Windows/package.json @@ -1,8 +1,8 @@ { "name": "com.boronnikov.games.red-cat-engine.windows", - "version": "1.0.0", + "version": "1.1.0", "displayName": "Red Cat Engine: Windows", - "description": "Simple window system, based on MVP", + "description": "Simple MVP system", "unity": "2021.3", "author": { "name": "Boronnikov Games", diff --git a/RedCatEngineUnityProject/Packages/Windows/package.json.meta b/RedCatEngineUnityProject/Packages/Windows/package.json.meta index 83acc0d..2198b60 100644 --- a/RedCatEngineUnityProject/Packages/Windows/package.json.meta +++ b/RedCatEngineUnityProject/Packages/Windows/package.json.meta @@ -1,3 +1,7 @@ fileFormatVersion: 2 -guid: 9a58cf63c62041f19362188386f23333 -timeCreated: 1713125223 \ No newline at end of file +guid: 90b5a373a3528994f888aa84de84df36 +PackageManifestImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/RedCatEngineUnityProject/Packages/manifest.json b/RedCatEngineUnityProject/Packages/manifest.json index 9d961fb..1bd3b75 100644 --- a/RedCatEngineUnityProject/Packages/manifest.json +++ b/RedCatEngineUnityProject/Packages/manifest.json @@ -1,12 +1,17 @@ { "dependencies": { - "com.elmortem.serializereferenceeditor": "https://github.com/elmortem/serializereferenceeditor.git", - "com.unity.addressables": "1.19.19", - "com.unity.feature.development": "1.0.1", - "com.unity.ide.rider": "3.0.28", + "com.elmortem.localization": "https://github.com/elmortem/localization.git?path=Packages/localization", + "com.elmortem.serializereferenceeditor": "https://github.com/elmortem/serializereferenceeditor.git?path=SerializeReferenceEditor/Assets/SREditor/Package", + "com.unity.addressables": "2.2.2", + "com.unity.textmeshpro": "3.0.6", + "com.unity.ai.navigation": "2.0.6", + "com.unity.feature.development": "1.0.2", + "com.unity.ide.rider": "3.0.31", "com.unity.ide.visualstudio": "2.0.22", "com.unity.ide.vscode": "1.2.5", - "com.unity.test-framework": "1.1.33", + "com.unity.multiplayer.center": "1.0.0", + "com.unity.test-framework": "1.4.6", + "com.unity.modules.accessibility": "1.0.0", "com.unity.modules.ai": "1.0.0", "com.unity.modules.androidjni": "1.0.0", "com.unity.modules.animation": "1.0.0", diff --git a/RedCatEngineUnityProject/Packages/packages-lock.json b/RedCatEngineUnityProject/Packages/packages-lock.json index 793a787..a9aec3b 100644 --- a/RedCatEngineUnityProject/Packages/packages-lock.json +++ b/RedCatEngineUnityProject/Packages/packages-lock.json @@ -1,5 +1,17 @@ { "dependencies": { + "com.boronnikov.games.red-cat-engine.aplication.runner": { + "version": "file:ApplicationRunner", + "depth": 0, + "source": "embedded", + "dependencies": {} + }, + "com.boronnikov.games.red-cat-engine.banchmark": { + "version": "file:Benchmark", + "depth": 0, + "source": "embedded", + "dependencies": {} + }, "com.boronnikov.games.red-cat-engine.conditions": { "version": "file:Conditions", "depth": 0, @@ -18,6 +30,18 @@ "source": "embedded", "dependencies": {} }, + "com.boronnikov.games.red-cat-engine.gamesettings": { + "version": "file:GameSettings", + "depth": 0, + "source": "embedded", + "dependencies": {} + }, + "com.boronnikov.games.red-cat-engine.pools": { + "version": "file:Pools", + "depth": 0, + "source": "embedded", + "dependencies": {} + }, "com.boronnikov.games.red-cat-engine.quests": { "version": "file:Quests", "depth": 0, @@ -36,6 +60,12 @@ "source": "embedded", "dependencies": {} }, + "com.boronnikov.games.red-cat-engine.services": { + "version": "file:UniversalServices", + "depth": 0, + "source": "embedded", + "dependencies": {} + }, "com.boronnikov.games.red-cat-engine.state-machine": { "version": "file:StateMachine", "depth": 0, @@ -54,27 +84,44 @@ "source": "embedded", "dependencies": {} }, + "com.elmortem.localization": { + "version": "https://github.com/elmortem/localization.git?path=Packages/localization", + "depth": 0, + "source": "git", + "dependencies": {}, + "hash": "f7942db8a7cb69d8fad218e30a1e252ca1987b17" + }, "com.elmortem.serializereferenceeditor": { - "version": "https://github.com/elmortem/serializereferenceeditor.git", + "version": "https://github.com/elmortem/serializereferenceeditor.git?path=SerializeReferenceEditor/Assets/SREditor/Package", "depth": 0, "source": "git", "dependencies": {}, - "hash": "655e2beec040cae85fc4a15f12db97bc89dcee49" + "hash": "874c391902ac80e89c6e8e9fc59e5f71956dcfb4" }, "com.unity.addressables": { - "version": "1.19.19", + "version": "2.2.2", "depth": 0, "source": "registry", "dependencies": { + "com.unity.profiling.core": "1.0.2", "com.unity.modules.assetbundle": "1.0.0", "com.unity.modules.jsonserialize": "1.0.0", "com.unity.modules.imageconversion": "1.0.0", "com.unity.modules.unitywebrequest": "1.0.0", - "com.unity.scriptablebuildpipeline": "1.19.6", + "com.unity.scriptablebuildpipeline": "2.1.4", "com.unity.modules.unitywebrequestassetbundle": "1.0.0" }, "url": "https://packages.unity.com" }, + "com.unity.ai.navigation": { + "version": "2.0.6", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.modules.ai": "1.0.0" + }, + "url": "https://packages.unity.com" + }, "com.unity.editorcoroutines": { "version": "1.0.0", "depth": 1, @@ -83,28 +130,27 @@ "url": "https://packages.unity.com" }, "com.unity.ext.nunit": { - "version": "1.0.6", + "version": "2.0.5", "depth": 1, "source": "registry", "dependencies": {}, "url": "https://packages.unity.com" }, "com.unity.feature.development": { - "version": "1.0.1", + "version": "1.0.2", "depth": 0, "source": "builtin", "dependencies": { - "com.unity.ide.visualstudio": "2.0.21", - "com.unity.ide.rider": "3.0.25", - "com.unity.ide.vscode": "1.2.5", + "com.unity.ide.visualstudio": "2.0.22", + "com.unity.ide.rider": "3.0.31", "com.unity.editorcoroutines": "1.0.0", - "com.unity.performance.profile-analyzer": "1.2.2", - "com.unity.test-framework": "1.1.33", - "com.unity.testtools.codecoverage": "1.2.4" + "com.unity.performance.profile-analyzer": "1.2.3", + "com.unity.test-framework": "1.4.6", + "com.unity.testtools.codecoverage": "1.2.6" } }, "com.unity.ide.rider": { - "version": "3.0.28", + "version": "3.0.31", "depth": 0, "source": "registry", "dependencies": { @@ -128,40 +174,55 @@ "dependencies": {}, "url": "https://packages.unity.com" }, + "com.unity.multiplayer.center": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.uielements": "1.0.0" + } + }, "com.unity.performance.profile-analyzer": { - "version": "1.2.2", + "version": "1.2.3", + "depth": 1, + "source": "registry", + "dependencies": {}, + "url": "https://packages.unity.com" + }, + "com.unity.profiling.core": { + "version": "1.0.2", "depth": 1, "source": "registry", "dependencies": {}, "url": "https://packages.unity.com" }, "com.unity.scriptablebuildpipeline": { - "version": "1.20.1", + "version": "2.1.4", "depth": 1, "source": "registry", "dependencies": {}, "url": "https://packages.unity.com" }, "com.unity.settings-manager": { - "version": "1.0.3", + "version": "2.0.1", "depth": 2, "source": "registry", "dependencies": {}, "url": "https://packages.unity.com" }, "com.unity.test-framework": { - "version": "1.1.33", + "version": "1.4.6", "depth": 0, "source": "registry", "dependencies": { - "com.unity.ext.nunit": "1.0.6", + "com.unity.ext.nunit": "2.0.3", "com.unity.modules.imgui": "1.0.0", "com.unity.modules.jsonserialize": "1.0.0" }, "url": "https://packages.unity.com" }, "com.unity.testtools.codecoverage": { - "version": "1.2.4", + "version": "1.2.6", "depth": 1, "source": "registry", "dependencies": { @@ -170,6 +231,29 @@ }, "url": "https://packages.unity.com" }, + "com.unity.textmeshpro": { + "version": "5.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.ugui": "2.0.0" + } + }, + "com.unity.ugui": { + "version": "2.0.0", + "depth": 1, + "source": "builtin", + "dependencies": { + "com.unity.modules.ui": "1.0.0", + "com.unity.modules.imgui": "1.0.0" + } + }, + "com.unity.modules.accessibility": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, "com.unity.modules.ai": { "version": "1.0.0", "depth": 0, @@ -217,6 +301,12 @@ "com.unity.modules.animation": "1.0.0" } }, + "com.unity.modules.hierarchycore": { + "version": "1.0.0", + "depth": 1, + "source": "builtin", + "dependencies": {} + }, "com.unity.modules.imageconversion": { "version": "1.0.0", "depth": 0, @@ -306,17 +396,7 @@ "com.unity.modules.ui": "1.0.0", "com.unity.modules.imgui": "1.0.0", "com.unity.modules.jsonserialize": "1.0.0", - "com.unity.modules.uielementsnative": "1.0.0" - } - }, - "com.unity.modules.uielementsnative": { - "version": "1.0.0", - "depth": 1, - "source": "builtin", - "dependencies": { - "com.unity.modules.ui": "1.0.0", - "com.unity.modules.imgui": "1.0.0", - "com.unity.modules.jsonserialize": "1.0.0" + "com.unity.modules.hierarchycore": "1.0.0" } }, "com.unity.modules.umbra": { diff --git a/RedCatEngineUnityProject/ProjectSettings/ProjectVersion.txt b/RedCatEngineUnityProject/ProjectSettings/ProjectVersion.txt index 9706d86..041b8c8 100644 --- a/RedCatEngineUnityProject/ProjectSettings/ProjectVersion.txt +++ b/RedCatEngineUnityProject/ProjectSettings/ProjectVersion.txt @@ -1,2 +1,2 @@ -m_EditorVersion: 2021.3.31f1 -m_EditorVersionWithRevision: 2021.3.31f1 (3409e2af086f) +m_EditorVersion: 6000.0.41f1 +m_EditorVersionWithRevision: 6000.0.41f1 (46e447368a18)