using System; using System.IO; using System.Runtime.InteropServices; using Harken; using Harken.Unity; using UnityEngine; [DisallowMultipleComponent] [RequireComponent(typeof(Rigidbody))] [DefaultExecutionOrder(-10001)] public sealed class HarkenBallAudio : MonoBehaviour { [SerializeField] private string pickupAction = string.Empty; [SerializeField] private string rollStartAction = string.Empty; [SerializeField] private string rollStopAction = string.Empty; [SerializeField] private string speedVariable = string.Empty; [SerializeField, Min(0.01f)] private float fullVolumeSpeed = 3f; [SerializeField, Min(0f)] private float speedSmoothTime = 0.1f; private const float StartSpeed = 0.15f; private const float StopSpeed = 0.08f; private const float SpeedTolerance = 0.001f; private const float RetryInterval = 0.1f; private static readonly uint VariableQuerySize = (uint)Marshal.SizeOf(); private static readonly uint VariableResultSize = (uint)Marshal.SizeOf(); private Rigidbody body; private HarkenAudioSystem audioSystem; private PackBootstrapSession session; private ActionPreparation preparation; private HarkenSpatialSource source; private ActionFiring rollingFiring; private string projectId; private bool rolling; private float smoothedSpeed; private float speedDampVelocity; private VnObjectId speedVariableId; private bool speedVariableResolved; private bool speedSyncFailed; private bool rollingFailed; private bool pickupFailed; private float nextRollingAttempt; private float nextInitializationAttempt; private VnResult speedResult; private VnResult rollingResult; private VnResult pickupResult; private VnResult initializationResult; private void Awake() { body = GetComponent(); SelectExportedPlatform(); } private void SelectExportedPlatform() { HarkenAudioSystem system = GetComponent(); if (system == null || system.State != HarkenRuntimeState.Stopped) return; HarkenProjectSettings settings = HarkenProjectSettings.Load(); if (settings == null || !string.IsNullOrEmpty(settings.PlatformName) || !string.IsNullOrEmpty(settings.PlatformId)) return; string platform = HarkenAudioSystem.CurrentPackBasePlatform(); if (string.IsNullOrEmpty(platform) || !PlatformCompanionExists(settings.PackDirectory, platform)) return; system.ConfigurePlatformBeforeStartup(string.Empty, platform); } private static bool PlatformCompanionExists(string packDirectory, string platform) { if (string.IsNullOrWhiteSpace(packDirectory)) return false; string normalized = packDirectory.Replace('\\', '/').Trim(); if (normalized.Length == 0 || Path.IsPathRooted(normalized) || normalized.Contains("..")) return false; string dataPath = Application.dataPath; if (string.IsNullOrEmpty(dataPath)) return false; string projectRoot = Path.GetDirectoryName(dataPath); if (string.IsNullOrEmpty(projectRoot)) return false; string root = Path.GetFullPath(Path.Combine(projectRoot, normalized)); string projectFull = Path.GetFullPath(projectRoot); string prefix = projectFull.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar; if (!root.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return false; if (File.Exists(Path.Combine(root, "Init.json"))) return false; string companion = Path.Combine(root, platform); return File.Exists(Path.Combine(companion, "Init.json")) && File.Exists(Path.Combine(companion, "Init.bytes")); } private void Update() { if (!TryInitialize()) return; Vector3 velocity = body.linearVelocity; float speed = new Vector2(velocity.x, velocity.z).magnitude; bool shouldRoll = rolling ? speed > StopSpeed : speed >= StartSpeed; float targetSpeed = shouldRoll ? Mathf.Clamp01(speed / fullVolumeSpeed) : 0f; smoothedSpeed = Mathf.SmoothDamp(smoothedSpeed, targetSpeed, ref speedDampVelocity, speedSmoothTime); if (Mathf.Abs(smoothedSpeed - targetSpeed) <= SpeedTolerance) smoothedSpeed = targetSpeed; SynchronizeSpeed(); if (rollingFailed || shouldRoll == rolling || Time.unscaledTime < nextRollingAttempt) return; string actionName = shouldRoll ? rollStartAction : rollStopAction; VnResult result = TryPlay(actionName, ref rollingResult, out ActionFiring firing); if (result != VnResult.VN_OK) { nextRollingAttempt = Time.unscaledTime + RetryInterval; if (!IsRetryable(result)) { rollingFailed = true; ReleaseResources(null, rollingFiring); rollingFiring = default; rolling = false; } return; } rolling = shouldRoll; rollingFiring = shouldRoll ? firing : default; } private void OnTriggerEnter(Collider other) { if (!isActiveAndEnabled || pickupFailed || !other.CompareTag("Pick Up")) return; if (!TryInitialize()) { if (enabled) Debug.LogWarning("HarkenBallAudio: 音频尚未就绪,本次拾取声音未播放。请检查启动状态后重新运行场景。", this); return; } VnResult result = TryPlay(pickupAction, ref pickupResult, out _); if (result != VnResult.VN_OK && !IsRetryable(result)) pickupFailed = true; } private bool TryInitialize() { if (audioSystem == null) audioSystem = HarkenAudioSystem.Instance; if (audioSystem == null) return Fail("请在场景中添加并启用一个 HarkenAudioSystem。"); if (audioSystem.State == HarkenRuntimeState.Failed) return Fail("音频运行时启动失败:" + audioSystem.LastResult); if (!audioSystem.IsPreparationComplete) return false; if (session != null && !ReferenceEquals(session, audioSystem.Session)) return Fail("音频运行时会话已改变,请重新启用此组件。"); if (source != null) return true; if (Time.unscaledTime < nextInitializationAttempt) return false; session = audioSystem.Session; projectId = session.ProjectId; if (string.IsNullOrWhiteSpace(projectId)) return Fail("当前音频会话缺少工程标识,请重新导出并配置 Pack。"); string[] actionNames = { pickupAction, rollStartAction, rollStopAction }; foreach (string actionName in actionNames) { if (string.IsNullOrWhiteSpace(actionName)) return Fail("请填写拾取、滚动开始和滚动停止的 Action 名称。"); } VnResult result; if (preparation != null && !preparation.IsPrepared) { result = preparation.Release(); if (result != VnResult.VN_OK) return HandleInitializationFailure("清理未完成的预加载资源失败", result); preparation = null; } if (preparation == null) { result = session.PrepareActions(actionNames, projectId, out preparation); if (result != VnResult.VN_OK) return HandleInitializationFailure("预加载 Action 资源失败", result); } result = audioSystem.CreateSpatialSource(transform, out source); if (result != VnResult.VN_OK) return HandleInitializationFailure("创建发声体失败", result); Debug.Log("HarkenBallAudio: ready.", this); return true; } private void SynchronizeSpeed() { if (speedSyncFailed) return; VnResult result; if (!speedVariableResolved) { result = Values.Resolve(speedVariable, out speedVariableId); if (result != VnResult.VN_OK) { ReportSpeedFailure(result); return; } speedVariableResolved = true; } VnVariableQueryDescV1 query = default; query.structSize = VariableQuerySize; query.variableId = speedVariableId; VnVariableQueryResultV1 state = default; state.structSize = VariableResultSize; result = Values.QueryVariable(in query, ref state); if (result != VnResult.VN_OK) { ReportSpeedFailure(result); return; } if (state.pendingCount != 0) return; if (state.currentValue == smoothedSpeed || (smoothedSpeed > 0f && smoothedSpeed < 1f && Mathf.Abs(state.currentValue - smoothedSpeed) <= SpeedTolerance)) { speedResult = VnResult.VN_OK; return; } result = Values.SetValue(speedVariableId, smoothedSpeed); if (result != VnResult.VN_OK) ReportSpeedFailure(result); else speedResult = VnResult.VN_OK; } private void ReportSpeedFailure(VnResult result) { ReportResult("同步速度变量失败:" + speedVariable, result, ref speedResult); if (!IsRetryable(result)) speedSyncFailed = true; } private VnResult TryPlay(string actionName, ref VnResult previous, out ActionFiring firing) { VnResult result = audioSystem.PlayAction(actionName, projectId, source, out firing); ReportResult("执行 Action 失败:" + actionName, result, ref previous); return result; } private static bool IsRetryable(VnResult result) => result == VnResult.VN_BACKPRESSURE || result == VnResult.VN_VARIABLE_TRANSACTION_EXHAUSTED || result == VnResult.VN_NO_ACTION || result == VnResult.VN_NO_VOICE || result == VnResult.VN_NO_EMITTER; private void ReportResult(string message, VnResult result, ref VnResult previous) { bool changed = result != previous; previous = result; if (result == VnResult.VN_OK || !changed) return; string diagnostic = "HarkenBallAudio: " + message + " / " + result; if (IsRetryable(result)) Debug.LogWarning(diagnostic + "。本次操作暂未完成,其他音频逻辑继续工作。", this); else Debug.LogError(diagnostic + "。此项功能停止自动尝试,其他音频逻辑继续工作。", this); } private bool HandleInitializationFailure(string message, VnResult result) { if (!IsRetryable(result)) return Fail(message + " / " + result); ReportResult(message, result, ref initializationResult); nextInitializationAttempt = Time.unscaledTime + RetryInterval; return false; } private void ReleaseResources(ActionPreparation resources, ActionFiring firing) { if (resources == null && !firing.IsValid) return; PackBootstrapSession ownerSession = session; VnResult result = TryRelease(); if (result == VnResult.VN_OK) return; Debug.LogWarning("HarkenBallAudio: 停止声音或释放资源暂未完成:" + result + "。将在音频运行时更新后重试。", audioSystem); audioSystem.OperationCompleted += RetryRelease; VnResult TryRelease() { if (ownerSession.IsActive && firing.IsValid) { VnResult stopped = firing.Stop(0); if (stopped != VnResult.VN_OK && stopped != VnResult.VN_STALE_HANDLE) return stopped; firing = default; } return resources?.Release() ?? VnResult.VN_OK; } void RetryRelease(HarkenAudioSystem owner, string operation, VnResult observed) { if (ownerSession.IsActive && operation != "HarkenEngine.Update") return; VnResult retried = TryRelease(); if (retried == VnResult.VN_OK) owner.OperationCompleted -= RetryRelease; else if (retried != result) Debug.LogWarning("HarkenBallAudio: 停止声音或释放资源仍未完成:" + retried, owner); result = retried; } } private bool Fail(string message) { Debug.LogError("HarkenBallAudio: " + message, this); enabled = false; return false; } private void OnDisable() { source?.EndFollow(); ReleaseResources(preparation, rollingFiring); preparation = null; source = null; session = null; audioSystem = null; rollingFiring = default; rolling = false; smoothedSpeed = 0f; speedDampVelocity = 0f; speedVariableId = default; speedVariableResolved = false; speedSyncFailed = false; rollingFailed = false; pickupFailed = false; nextRollingAttempt = 0f; nextInitializationAttempt = 0f; speedResult = VnResult.VN_OK; rollingResult = VnResult.VN_OK; pickupResult = VnResult.VN_OK; initializationResult = VnResult.VN_OK; } }