Repository navigation
Expand file tree
/
Copy pathAudioNavigationHandler.cs
More file actions
652 lines (563 loc) · 26.4 KB
/
Copy pathAudioNavigationHandler.cs
File metadata and controls
652 lines (563 loc) · 26.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
using Il2Cpp;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
namespace DigimonNOAccess
{
/// <summary>
/// Provides always-on audio navigation for blind players.
/// Plays simultaneous positional audio for each object type in range
/// (items, NPCs, enemies, transitions). No toggle keys, no speech - just audio cues.
/// </summary>
public class AudioNavigationHandler : IAccessibilityHandler
{
public int Priority => 999;
/// <summary>
/// Background handler - never owns the status announce.
/// </summary>
public bool IsOpen() => false;
/// <summary>
/// Background handler - never announces status.
/// </summary>
public void AnnounceStatus() { }
// All tunable values come from ModSettings (persisted to settings.json)
private static float ItemRange => ModSettings.ItemRange;
private static float NpcRange => ModSettings.NpcRange;
private static float EnemyRange => ModSettings.EnemyRange;
private static float TransitionRange => ModSettings.TransitionRange;
private static float FacilityRange => ModSettings.FacilityRange;
private static int MaxItemSounds => ModSettings.MaxItemSounds;
private static int MaxNpcSounds => ModSettings.MaxNpcSounds;
private static int MaxEnemySounds => ModSettings.MaxEnemySounds;
private static int MaxTransitionSounds => ModSettings.MaxTransitionSounds;
private static int MaxFacilitySounds => ModSettings.MaxFacilitySounds;
private static float NearestVolume => ModSettings.NearestVolume;
private static float BackgroundVolume => ModSettings.BackgroundVolume;
// Tracking settings
private const float TrackingUpdateInterval = 0.5f;
private float _lastTrackingScan = 0f;
// State
private bool _initialized = false;
// Cached references
private PlayerCtrl _playerCtrl;
private NpcManager _npcManager;
private EnemyManager _enemyManager;
private float _lastSearchTime = 0f;
// Per-target positional audio: every target in range gets its own audio
private Dictionary<GameObject, (PositionalAudio audio, PositionalAudio.SoundType type)> _navAudio = new Dictionary<GameObject, (PositionalAudio, PositionalAudio.SoundType)>();
// Compass direction (north angle per area, used for direction announcements)
private float _currentNorthAngle = 0f;
// Sound file path
private string _soundsPath;
private bool _facilityWavExists = false;
// Track control state for refresh on return
private bool _wasInControl;
// Map/area change detection for immediate rescan
private int _lastMapNo = -1;
private int _lastAreaNo = -1;
// Camera mode tracking for diagnostic logging
// Cooldown after training result to allow evolution detection
private const float PostTrainingCooldown = 0.5f;
private float _lastTrainingResultSeenTime = 0f;
public void Initialize()
{
if (_initialized) return;
try
{
// Set up sounds path for wall detection
string modPath = Path.GetDirectoryName(typeof(AudioNavigationHandler).Assembly.Location);
_soundsPath = Path.Combine(Path.GetDirectoryName(modPath), "sounds");
if (!Directory.Exists(_soundsPath))
{
_soundsPath = Path.Combine(modPath, "sounds");
}
// Check if facility.wav exists (no tone fallback for this type)
_facilityWavExists = File.Exists(Path.Combine(_soundsPath, "facility.wav"));
if (_facilityWavExists)
DebugLogger.Log("[AudioNav] facility.wav found - facility/fishing/toilet audio enabled");
_initialized = true;
DebugLogger.Log("[AudioNav] Initialized - always-on audio navigation");
}
catch (Exception ex)
{
DebugLogger.Log($"[AudioNav] Initialize error: {ex.Message}");
}
}
public void Update()
{
if (!_initialized)
{
Initialize();
}
// Find managers periodically
float currentTime = Time.time;
if (_playerCtrl == null || currentTime - _lastSearchTime > 2f)
{
_playerCtrl = UnityEngine.Object.FindObjectOfType<PlayerCtrl>();
_npcManager = UnityEngine.Object.FindObjectOfType<NpcManager>();
_enemyManager = UnityEngine.Object.FindObjectOfType<EnemyManager>();
_lastSearchTime = currentTime;
}
// Update object tracking
UpdatePositionalAudioTracking();
// Drive environmental audio simulation (occlusion)
UpdateEnvironmentSimulation();
}
private void UpdatePositionalAudioTracking()
{
// Stop if player is not in control
bool inControl = IsPlayerInControl();
if (!inControl)
{
_wasInControl = false;
StopAllAudio();
return;
}
// On return to control, refresh managers and force rescan.
// This handles map/area transitions where old references became stale.
if (!_wasInControl)
{
_wasInControl = true;
// Force immediate manager refresh so FindAllTargetsInRange uses valid references
_playerCtrl = UnityEngine.Object.FindObjectOfType<PlayerCtrl>();
_npcManager = UnityEngine.Object.FindObjectOfType<NpcManager>();
_enemyManager = UnityEngine.Object.FindObjectOfType<EnemyManager>();
_lastSearchTime = Time.time;
_lastTrackingScan = 0f; // Force immediate rescan
}
if (_playerCtrl == null) return;
try
{
Vector3 playerPos = _playerCtrl.transform.position;
// Use full camera orientation for audio (matching the game's AudioListener).
// Includes pitch and zoom so HRTF matches what the player perceives.
CameraOrientation.GetVectors(out Vector3 camFwd, out Vector3 camUp);
float currentTime = Time.time;
// Detect map/area change and force immediate rescan
var mgm = MainGameManager.m_instance;
if (mgm != null)
{
int mapNo = mgm.mapNo;
int areaNo = mgm.areaNo;
if (mapNo != _lastMapNo || areaNo != _lastAreaNo)
{
if (_lastMapNo >= 0)
{
StopAllAudio();
DebugLogger.Log($"[AudioNav] Area changed ({_lastMapNo}/{_lastAreaNo} -> {mapNo}/{areaNo}), refreshing managers");
// Force immediate manager refresh for the new scene
_playerCtrl = UnityEngine.Object.FindObjectOfType<PlayerCtrl>();
_npcManager = UnityEngine.Object.FindObjectOfType<NpcManager>();
_enemyManager = UnityEngine.Object.FindObjectOfType<EnemyManager>();
_lastSearchTime = Time.time;
}
_lastMapNo = mapNo;
_lastAreaNo = areaNo;
_lastTrackingScan = 0f; // Force immediate rescan
// Update north angle for compass direction announcements
_currentNorthAngle = GetNorthAngle(mapNo, areaNo);
}
}
// Rescan for targets periodically
if (currentTime - _lastTrackingScan >= TrackingUpdateInterval)
{
_lastTrackingScan = currentTime;
var targets = FindAllTargetsInRange(playerPos);
var currentTargets = new HashSet<GameObject>();
foreach (var (target, type, dist) in targets)
{
currentTargets.Add(target);
if (!_navAudio.ContainsKey(target))
{
// New target - create audio and start tracking
var audio = new PositionalAudio();
audio.UpdatePlayerPosition(
playerPos.x, playerPos.y, playerPos.z,
camFwd.x, camFwd.y, camFwd.z,
camUp.x, camUp.y, camUp.z);
Vector3 targetPos = target.transform.position;
audio.UpdateTargetPosition(targetPos.x, targetPos.y, targetPos.z);
audio.StartTracking(type, dist + 10f);
_navAudio[target] = (audio, type);
}
}
// Remove targets no longer in range
var toRemove = new List<GameObject>();
foreach (var kvp in _navAudio)
{
if (!currentTargets.Contains(kvp.Key))
toRemove.Add(kvp.Key);
}
foreach (var obj in toRemove)
{
_navAudio[obj].audio.Dispose();
_navAudio.Remove(obj);
}
}
// Update positions and collect distance info per type
var toClean = new List<GameObject>();
var distByType = new Dictionary<PositionalAudio.SoundType, List<(GameObject obj, float dist)>>();
foreach (var kvp in _navAudio)
{
var target = kvp.Key;
var (audio, type) = kvp.Value;
if (target == null || !target.activeInHierarchy)
{
audio.Stop();
toClean.Add(target);
continue;
}
if (!audio.IsPlaying) continue;
audio.UpdatePlayerPosition(
playerPos.x, playerPos.y, playerPos.z,
camFwd.x, camFwd.y, camFwd.z,
camUp.x, camUp.y, camUp.z);
Vector3 tPos = target.transform.position;
audio.UpdateTargetPosition(tPos.x, tPos.y, tPos.z);
float dist = Vector3.Distance(playerPos, tPos);
if (!distByType.ContainsKey(type))
distByType[type] = new List<(GameObject, float)>();
distByType[type].Add((target, dist));
}
// For each type: sort by distance, keep nearest N audible, silence the rest
foreach (var kv in distByType)
{
var type = kv.Key;
var list = kv.Value;
list.Sort((a, b) => a.dist.CompareTo(b.dist));
int maxSounds = type switch
{
PositionalAudio.SoundType.Item => MaxItemSounds,
PositionalAudio.SoundType.NPC => MaxNpcSounds,
PositionalAudio.SoundType.Enemy => MaxEnemySounds,
PositionalAudio.SoundType.Transition => MaxTransitionSounds,
PositionalAudio.SoundType.Facility => MaxFacilitySounds,
_ => 3
};
float typeVolume = type switch
{
PositionalAudio.SoundType.Item => ModSettings.ItemVolume,
PositionalAudio.SoundType.NPC => ModSettings.NpcVolume,
PositionalAudio.SoundType.Enemy => ModSettings.EnemyVolume,
PositionalAudio.SoundType.Transition => ModSettings.TransitionVolume,
PositionalAudio.SoundType.Facility => ModSettings.FacilityVolume,
_ => 1.0f
};
for (int i = 0; i < list.Count; i++)
{
var audio = _navAudio[list[i].obj].audio;
if (i >= maxSounds)
{
audio.SetMaxVolume(0f);
}
else if (i == 0)
{
audio.SetMaxVolume(NearestVolume * typeVolume);
}
else
{
audio.SetMaxVolume(BackgroundVolume * typeVolume);
}
}
}
// Clean up dead targets found during position updates
foreach (var obj in toClean)
{
if (_navAudio.ContainsKey(obj))
{
_navAudio[obj].audio.Dispose();
_navAudio.Remove(obj);
}
}
}
catch (Exception ex)
{
DebugLogger.Log($"[AudioNav] Update error: {ex.Message}");
}
}
/// <summary>
/// Find all targets of every sound type within range.
/// Each target gets its own positional audio so you hear everything around you.
/// </summary>
private List<(GameObject target, PositionalAudio.SoundType type, float distance)> FindAllTargetsInRange(Vector3 playerPos)
{
var results = new List<(GameObject, PositionalAudio.SoundType, float)>();
// Items
if (ModSettings.ItemsEnabled)
{
try
{
var itemManager = ItemPickPointManager.m_instance;
if (itemManager != null && itemManager.m_itemPickPoints != null)
{
foreach (var point in itemManager.m_itemPickPoints)
{
if (point == null || point.gameObject == null || !point.gameObject.activeInHierarchy)
continue;
float dist = Vector3.Distance(playerPos, point.transform.position);
if (dist < ItemRange && dist > 1f)
results.Add((point.gameObject, PositionalAudio.SoundType.Item, dist));
}
}
}
catch { }
}
// Transitions + Fishing spots + Toilets (all are MapTriggerScript subtypes)
if (ModSettings.TransitionsEnabled || ModSettings.FacilitiesEnabled)
{
try
{
var mapTriggers = UnityEngine.Object.FindObjectsOfType<MapTriggerScript>();
foreach (var trigger in mapTriggers)
{
if (trigger == null || trigger.gameObject == null || !trigger.gameObject.activeInHierarchy)
continue;
if (ModSettings.TransitionsEnabled && trigger.enterID == MapTriggerManager.EVENT.MapChange)
{
float dist = Vector3.Distance(playerPos, trigger.transform.position);
if (dist < TransitionRange && dist > 1f)
results.Add((trigger.gameObject, PositionalAudio.SoundType.Transition, dist));
}
else if (ModSettings.FacilitiesEnabled && _facilityWavExists &&
(trigger.enterID == MapTriggerManager.EVENT.Fishing ||
trigger.enterID == MapTriggerManager.EVENT.Toilet))
{
float dist = Vector3.Distance(playerPos, trigger.transform.position);
if (dist < FacilityRange && dist > 1f)
results.Add((trigger.gameObject, PositionalAudio.SoundType.Facility, dist));
}
}
}
catch { }
}
// Enemies
if (ModSettings.EnemiesEnabled)
{
try
{
if (_enemyManager != null && _enemyManager.m_EnemyCtrlArray != null)
{
foreach (var enemy in _enemyManager.m_EnemyCtrlArray)
{
if (!GameStateService.IsEnemyAlive(enemy))
continue;
float dist = Vector3.Distance(playerPos, enemy.transform.position);
if (dist < EnemyRange && dist > 1f)
results.Add((enemy.gameObject, PositionalAudio.SoundType.Enemy, dist));
}
}
}
catch { }
}
// NPCs
if (ModSettings.NpcsEnabled)
{
try
{
if (_npcManager != null && _npcManager.m_NpcCtrlArray != null)
{
foreach (var npc in _npcManager.m_NpcCtrlArray)
{
if (npc == null || npc.gameObject == null || !npc.gameObject.activeInHierarchy)
continue;
float dist = Vector3.Distance(playerPos, npc.transform.position);
if (dist < NpcRange && dist > 1f)
results.Add((npc.gameObject, PositionalAudio.SoundType.NPC, dist));
}
}
}
catch { }
}
// Facilities (training, shops, restaurants, storage, etc.)
if (ModSettings.FacilitiesEnabled && _facilityWavExists)
{
try
{
var mgm = MainGameManager.m_instance;
var eventTriggerMgr = mgm?.m_EventTriggerMgr;
if (eventTriggerMgr != null)
{
var triggerDict = eventTriggerMgr.m_TriggerDictionary;
var placementData = eventTriggerMgr.m_CsvbPlacementData;
if (triggerDict != null && placementData != null)
{
var enumerator = triggerDict.GetEnumerator();
while (enumerator.MoveNext())
{
var trigger = enumerator.Current.Value;
if (trigger == null || trigger.gameObject == null || !trigger.gameObject.activeInHierarchy)
continue;
try
{
uint placementId = enumerator.Current.Key;
var npcData = HashIdSearchClass<ParameterPlacementNpc>.GetParam(placementData, placementId);
if (npcData == null) continue;
var facilityType = (MainGameManager.Facility)npcData.m_Facility;
if (facilityType == MainGameManager.Facility.None) continue;
float dist = Vector3.Distance(playerPos, trigger.transform.position);
if (dist < FacilityRange && dist > 1f)
results.Add((trigger.gameObject, PositionalAudio.SoundType.Facility, dist));
}
catch { }
}
}
}
}
catch { }
}
return results;
}
private void StopAllAudio()
{
foreach (var kvp in _navAudio)
{
try { kvp.Value.audio.Dispose(); } catch { }
}
_navAudio.Clear();
}
/// <summary>
/// Get the north angle for the current map area from ParameterDigiviceAreaData.
/// Returns degrees (0 = +Z is north).
/// </summary>
private float GetNorthAngle(int mapNo, int areaNo)
{
try
{
var areaData = ParameterDigiviceAreaData.GetParam((AppInfo.MAP)mapNo, areaNo);
if (areaData != null)
{
float angle = areaData.m_fieldNorthAngle;
DebugLogger.Log($"[AudioNav] North angle for map {mapNo} area {areaNo}: {angle:F1}°");
return angle;
}
}
catch (Exception ex)
{
DebugLogger.Warning($"[AudioNav] GetNorthAngle error: {ex.Message}");
}
DebugLogger.Warning($"[AudioNav] No north angle for map {mapNo} area {areaNo}, defaulting to 0");
return 0f;
}
/// <summary>
/// Get the compass direction the camera is currently facing,
/// relative to the map's north angle.
/// </summary>
public string GetCameraCompassDirection()
{
try
{
CameraOrientation.GetVectors(out Vector3 camFwd, out Vector3 camUp);
// Project camera forward to horizontal plane
float fwdX = camFwd.x;
float fwdZ = camFwd.z;
float len = (float)Math.Sqrt(fwdX * fwdX + fwdZ * fwdZ);
if (len < 0.001f) return "unknown";
// World angle from +Z axis
float worldAngleDeg = (float)Math.Atan2(fwdX, fwdZ) * (180f / (float)Math.PI);
// Subtract north angle to get compass bearing
float compassDeg = worldAngleDeg - _currentNorthAngle;
compassDeg = ((compassDeg % 360f) + 360f) % 360f;
// 8-direction compass with 45-degree sectors
// N: 337.5-22.5, NE: 22.5-67.5, E: 67.5-112.5, etc.
if (compassDeg >= 337.5f || compassDeg < 22.5f) return "North";
if (compassDeg < 67.5f) return "Northeast";
if (compassDeg < 112.5f) return "East";
if (compassDeg < 157.5f) return "Southeast";
if (compassDeg < 202.5f) return "South";
if (compassDeg < 247.5f) return "Southwest";
if (compassDeg < 292.5f) return "West";
return "Northwest";
}
catch
{
return "unknown";
}
}
private void UpdateEnvironmentSimulation()
{
if (!SteamAudioEnvironment.IsInitialized) return;
try
{
// Check for area change and rebuild geometry
var mgm = MainGameManager.m_instance;
if (mgm != null)
{
SteamAudioEnvironment.CheckAreaChange(mgm.mapNo, mgm.areaNo);
}
// Update listener position for simulation
if (_playerCtrl != null)
{
Vector3 pos = _playerCtrl.transform.position;
CameraOrientation.GetVectors(out Vector3 envFwd, out Vector3 envUp);
SteamAudioEnvironment.UpdateListener(pos, envFwd, envUp);
}
// Run direct simulation for all registered sources
SteamAudioEnvironment.RunDirectSimulation();
}
catch (Exception ex)
{
DebugLogger.Error($"[AudioNav] Env simulation error: {ex.Message}");
}
}
private bool IsPlayerInControl()
{
try
{
if (_playerCtrl == null) return false;
// Field must be in a playable state (Main/Idle).
// Blocks during Start (loading), Warp, Evolution, RestartLose/Escape.
if (!GameStateService.IsFieldInPlayableState())
return false;
// actionState must be Idle (walking around). Everything else
// (Event, Battle, Care, Dead, etc.) = not in control.
if (_playerCtrl.actionState != UnitCtrlBase.ActionState.ActionState_Idle)
return false;
// Game step may still be Battle while actionState is already Idle
// (e.g. death recovery transition before teleport to town)
if (GameStateService.IsInBattlePhase())
return false;
// Pause is a system-level freeze that doesn't change actionState
if (GameStateService.IsGamePaused())
return false;
// Evolution keeps actionState as Idle but disables field objects.
// IsMenuOpen() checks EvolutionBase, training result, digivice, etc.
if (GameStateService.IsMenuOpen())
return false;
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Check if any menu is open. Delegates to GameStateService.IsMenuOpen()
/// but adds AudioNav-specific training result cooldown logic.
/// </summary>
private bool IsMenuOpen()
{
// Check the standard menu open states
if (GameStateService.IsMenuOpen())
{
// Track when we last saw the training result panel (for cooldown)
var resultPanel = UnityEngine.Object.FindObjectOfType<uTrainingPanelResult>();
if (resultPanel != null && resultPanel.gameObject.activeInHierarchy)
{
_lastTrainingResultSeenTime = Time.time;
}
return true;
}
// Cooldown period after training result closes
// This allows evolution to start before audio nav kicks in
if (Time.time - _lastTrainingResultSeenTime < PostTrainingCooldown)
return true;
return false;
}
public void Cleanup()
{
_initialized = false;
StopAllAudio();
}
}
}