using System; using System.Threading; using Code.Infrastructure.Camera; using Code.Infrastructure.Configs; using Code.Infrastructure.UI; using Cysharp.Text; using Cysharp.Threading.Tasks; using UnityEngine; using UnityEngine.AddressableAssets; using UnityEngine.Pool; using UnityEngine.ResourceManagement.AsyncOperations; namespace Code.Game.OfficeGame.Text { public interface IAnimatedTextService { UniTask CreateAnimatedText( string text, float letterLeadDuration, float letterDissolveDuration, float letterLifetime, Color color, Vector3 position, Quaternion rotation, TextAppearType appearType = TextAppearType.Dissolve, TextDisappearType disappearType = TextDisappearType.Dissolve, Vector2? textRectSize = null, float? letterDelay = null, TextBehaviourType behaviourType = TextBehaviourType.Steel, CancellationToken ct = default); // Zero-Allocation перегрузка для ZString (Utf16ValueStringBuilder) UniTask CreateAnimatedText( ref Utf16ValueStringBuilder textBuilder, float letterLeadDuration, float letterDissolveDuration, float letterLifetime, Color color, Vector3 position, Quaternion rotation, TextAppearType appearType = TextAppearType.Dissolve, TextDisappearType disappearType = TextDisappearType.Dissolve, Vector2? textRectSize = null, float? letterDelay = null, TextBehaviourType behaviourType = TextBehaviourType.Steel, CancellationToken ct = default); // Zero-Allocation перегрузка для форматирования (при желании легко расширить до T2, T3) UniTask CreateAnimatedTextFormat( string format, T1 arg1, float letterLeadDuration, float letterDissolveDuration, float letterLifetime, Color color, Vector3 position, Quaternion rotation, TextAppearType appearType = TextAppearType.Dissolve, TextDisappearType disappearType = TextDisappearType.Dissolve, Vector2? textRectSize = null, float? letterDelay = null, TextBehaviourType behaviourType = TextBehaviourType.Steel, CancellationToken ct = default); } public interface IAnimatedTextServiceInitializer { UniTask LoadConfigs(); } public class AnimatedTextService : IAnimatedTextService, IAnimatedTextServiceInitializer, IDisposable { private readonly IUIFactory _uiFactory; private readonly AssetReference _settingsReference; private readonly CancellationTokenSource _disposeCts = new(); private AsyncOperationHandle _settingsHandle; private AsyncOperationHandle _prefabHandle; private AnimatedTextSettings _settings; private AnimatedTextView _prefab; private ObjectPool _pool; private CameraStateMachine _cameraStateMachine; public AnimatedTextService(IUIFactory uiFactory, IConfigLocator configLocator, CameraStateMachine cameraStateMachine) { _cameraStateMachine = cameraStateMachine; _uiFactory = uiFactory; _settingsReference = configLocator.TryGetConfigAssetReference(); } // Вызывайте после UIFactoryInitializer.LoadConfigs(), когда GameplayCanvas уже создан public async UniTask LoadConfigs() { _settingsHandle = Addressables.LoadAssetAsync(_settingsReference); _settings = await _settingsHandle.ToUniTask(); _prefabHandle = Addressables.LoadAssetAsync(_settings.TextPrefab); var prefabGo = await _prefabHandle.ToUniTask(); _prefab = prefabGo.GetComponent(); _pool = new ObjectPool( createFunc: CreatePooledView, actionOnGet: view => view.gameObject.SetActive(true), actionOnRelease: view => { view.ResetState(); view.gameObject.SetActive(false); }, actionOnDestroy: view => { if (view) UnityEngine.Object.Destroy(view.gameObject); }, collectionCheck: false, defaultCapacity: _settings.InitialPoolCapacity, maxSize: _settings.MaxPoolSize); } public UniTask CreateAnimatedText( string text, float letterLeadDuration, float letterDissolveDuration, float letterLifetime, Color color, Vector3 position, Quaternion rotation, TextAppearType appearType = TextAppearType.Dissolve, TextDisappearType disappearType = TextDisappearType.Dissolve, Vector2? textRectSize = null, float? letterDelay = null, TextBehaviourType behaviourType = TextBehaviourType.Steel, CancellationToken ct = default) { var view = AcquireAndConfigureView(position, rotation, textRectSize); view.SetText(text); return RunAndReleaseAsync( view, letterLeadDuration, letterDissolveDuration, letterLifetime, letterDelay ?? _settings.DefaultLetterDelay, color, appearType, disappearType, behaviourType, ct); } // Без модификатора async: буфер ZString копируется в TMP_Text синхронно до старта ожидания, // поэтому вызывающий код может сразу освободить sb через using! public UniTask CreateAnimatedText( ref Utf16ValueStringBuilder textBuilder, float letterLeadDuration, float letterDissolveDuration, float letterLifetime, Color color, Vector3 position, Quaternion rotation, TextAppearType appearType = TextAppearType.Dissolve, TextDisappearType disappearType = TextDisappearType.Dissolve, Vector2? textRectSize = null, float? letterDelay = null, TextBehaviourType behaviourType = TextBehaviourType.Steel, CancellationToken ct = default) { var view = AcquireAndConfigureView(position, rotation, textRectSize); view.SetText(ref textBuilder); return RunAndReleaseAsync( view, letterLeadDuration, letterDissolveDuration, letterLifetime, letterDelay ?? _settings.DefaultLetterDelay, color, appearType, disappearType, behaviourType, ct); } public UniTask CreateAnimatedTextFormat( string format, T1 arg1, float letterLeadDuration, float letterDissolveDuration, float letterLifetime, Color color, Vector3 position, Quaternion rotation, TextAppearType appearType = TextAppearType.Dissolve, TextDisappearType disappearType = TextDisappearType.Dissolve, Vector2? textRectSize = null, float? letterDelay = null, TextBehaviourType behaviourType = TextBehaviourType.Steel, CancellationToken ct = default) { var view = AcquireAndConfigureView(position, rotation, textRectSize); view.SetTextFormat(format, arg1); return RunAndReleaseAsync( view, letterLeadDuration, letterDissolveDuration, letterLifetime, letterDelay ?? _settings.DefaultLetterDelay, color, appearType, disappearType, behaviourType, ct); } private AnimatedTextView AcquireAndConfigureView(Vector3 position, Quaternion rotation, Vector2? textRectSize) { var view = _pool.Get(); view.ConfigureTransform(position, rotation, textRectSize ?? _settings.DefaultRectSize); return view; } private async UniTask RunAndReleaseAsync( AnimatedTextView view, float letterLeadDuration, float letterDissolveDuration, float letterLifetime, float letterDelay, Color color, TextAppearType appearType, TextDisappearType disappearType, TextBehaviourType behaviourType, CancellationToken ct) { try { if (ct.CanBeCanceled) { using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(ct, _disposeCts.Token); await view.PlayAsync( letterLeadDuration, letterDissolveDuration, letterLifetime, letterDelay, color, appearType, disappearType, _settings.FallDistance, _settings.MaxFallRotationAngle, behaviourType, linkedCts.Token); } else { await view.PlayAsync( letterLeadDuration, letterDissolveDuration, letterLifetime, letterDelay, color, appearType, disappearType, _settings.FallDistance, _settings.MaxFallRotationAngle, behaviourType, _disposeCts.Token); } } finally { if (view) { _pool.Release(view); } } } private AnimatedTextView CreatePooledView() { var instance = UnityEngine.Object.Instantiate(_prefab, _uiFactory.GameplayCanvas.transform); instance.gameObject.SetActive(false); instance.SetTarget(_cameraStateMachine.Camera.transform); return instance; } public void Dispose() { _disposeCts.Cancel(); _disposeCts.Dispose(); _pool?.Clear(); if (_prefabHandle.IsValid()) Addressables.Release(_prefabHandle); if (_settingsHandle.IsValid()) Addressables.Release(_settingsHandle); } } }