| | | 1 | | using SwiftCollections; |
| | | 2 | | using System; |
| | | 3 | | using System.Collections.Generic; |
| | | 4 | | using System.Threading; |
| | | 5 | | |
| | | 6 | | namespace Trailblazer.Pathing; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Caches and reuses <see cref="ISurveyResult"/> instances to reduce allocation overhead |
| | | 10 | | /// and improve pathfinding performance. |
| | | 11 | | /// Supports LRU eviction and optional pooling of released guides. |
| | | 12 | | /// </summary> |
| | | 13 | | internal class ReusableSurveyResultCache<T> : IDisposable where T : SurveyResult |
| | | 14 | | { |
| | | 15 | | /// <summary> |
| | | 16 | | /// Maximum number of <see cref="SurveyResult"/>s allowed in the cache before eviction occurs. |
| | | 17 | | /// </summary> |
| | | 18 | | private const int MaxCacheSize = 128; |
| | | 19 | | |
| | | 20 | | /// <summary> |
| | | 21 | | /// Active <see cref="SurveyResult"/>s cache indexed by the request's cache key. |
| | | 22 | | /// </summary> |
| | 3856 | 23 | | private readonly SwiftDictionary<int, T> _cache = new(); |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Reverse lookup from chart key to cached request keys that reference the chart. |
| | | 27 | | /// </summary> |
| | 3856 | 28 | | private readonly SwiftDictionary<string, SwiftList<int>> _chartIndex = new(8, StringComparer.Ordinal); |
| | | 29 | | |
| | 3856 | 30 | | private readonly SwiftList<int> _staleKeys = new(MaxCacheSize); |
| | | 31 | | |
| | 3856 | 32 | | private readonly ReaderWriterLockSlim _lock = new(); |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// Gets the total number of cached and pooled <see cref="SurveyResult"/> instances. |
| | | 36 | | /// </summary> |
| | 15675 | 37 | | public int Count => _cache.Count; |
| | | 38 | | |
| | | 39 | | private int _countInUse; |
| | | 40 | | |
| | | 41 | | public int CountInUse |
| | | 42 | | { |
| | 4542 | 43 | | get => _countInUse; |
| | 6414 | 44 | | private set => _countInUse = Math.Max(0, value); |
| | | 45 | | } |
| | | 46 | | |
| | | 47 | | /// <summary> |
| | | 48 | | /// Attempts to retrieve a valid <see cref="SurveyResult"/> from the cache, |
| | | 49 | | /// or creates and initializes a new one if none are reusable. |
| | | 50 | | /// Evicts the least recently used guide if the cache is at capacity. |
| | | 51 | | /// </summary> |
| | | 52 | | /// <param name="request">The path request used as the cache key.</param> |
| | | 53 | | /// <param name="create">Factory method to create a new guide instance.</param> |
| | | 54 | | /// <param name="result">The resulting <see cref="SurveyResult"/> instance.</param> |
| | | 55 | | /// <returns>True if a valid <see cref="SurveyResult"/> was obtained; otherwise, false.</returns> |
| | | 56 | | public bool TryGetOrCreate(IPathRequest request, Func<T> create, out T result) |
| | | 57 | | { |
| | 729 | 58 | | int key = request.RequestCacheKey; |
| | | 59 | | |
| | 729 | 60 | | _lock.EnterUpgradeableReadLock(); |
| | | 61 | | try |
| | | 62 | | { |
| | 729 | 63 | | if (_cache.TryGetValue(key, out result) && result.HasPath) |
| | | 64 | | { |
| | 4 | 65 | | result.Context = request.Context; |
| | 4 | 66 | | CheckoutCachedResult(result); |
| | 4 | 67 | | return true; |
| | | 68 | | } |
| | | 69 | | |
| | 725 | 70 | | if (_cache.Count >= MaxCacheSize) |
| | | 71 | | { |
| | 6 | 72 | | if (TryGetLeastRecentlyUsedReusableEntry(out int evictKey, out T evictCandidate)) |
| | | 73 | | { |
| | 4 | 74 | | _lock.EnterWriteLock(); |
| | 16 | 75 | | try { RemoveCachedResult(evictKey, evictCandidate); } finally { _lock.ExitWriteLock(); } |
| | | 76 | | } |
| | | 77 | | } |
| | | 78 | | |
| | 725 | 79 | | result = create(); |
| | 725 | 80 | | if (result.HasPath) |
| | | 81 | | { |
| | 710 | 82 | | result.Context = request.Context; |
| | 710 | 83 | | _lock.EnterWriteLock(); |
| | | 84 | | try |
| | | 85 | | { |
| | 710 | 86 | | if (_cache.Count < MaxCacheSize) |
| | 708 | 87 | | AddCachedResult(key, result); |
| | | 88 | | |
| | 710 | 89 | | result.Checkout(); |
| | 710 | 90 | | CountInUse++; |
| | 710 | 91 | | } |
| | 1420 | 92 | | finally { _lock.ExitWriteLock(); } |
| | | 93 | | |
| | 710 | 94 | | return true; |
| | | 95 | | } |
| | | 96 | | |
| | 15 | 97 | | return false; |
| | | 98 | | } |
| | 1458 | 99 | | finally { _lock.ExitUpgradeableReadLock(); } |
| | 729 | 100 | | } |
| | | 101 | | |
| | | 102 | | /// <summary> |
| | | 103 | | /// Returns a <see cref="SurveyResult"/> to the pool or disposes it based on the given flag. |
| | | 104 | | /// Also removes invalid guides from the active cache. |
| | | 105 | | /// </summary> |
| | | 106 | | /// <param name="result">The <see cref="SurveyResult"/> to return.</param> |
| | | 107 | | /// <param name="dispose">Whether the <see cref="SurveyResult"/> should be disposed and not pooled.</param> |
| | | 108 | | public void Return(T result, bool dispose) |
| | | 109 | | { |
| | 2216 | 110 | | if (result == null) return; |
| | | 111 | | |
| | 2216 | 112 | | _lock.EnterWriteLock(); |
| | | 113 | | try |
| | | 114 | | { |
| | 2216 | 115 | | if (result.IsInUse) |
| | 2215 | 116 | | CountInUse--; |
| | | 117 | | |
| | 2216 | 118 | | if (result.HasPath && !dispose) |
| | | 119 | | { |
| | 2208 | 120 | | result.Release(); |
| | 2208 | 121 | | return; |
| | | 122 | | } |
| | | 123 | | |
| | 8 | 124 | | if (result.RequestHashKey >= 0 |
| | 8 | 125 | | && _cache.TryGetValue(result.RequestHashKey, out T cached) |
| | 8 | 126 | | && ReferenceEquals(cached, result)) |
| | | 127 | | { |
| | 2 | 128 | | RemoveCachedResult(result.RequestHashKey, result); |
| | | 129 | | } |
| | 8 | 130 | | } |
| | 4432 | 131 | | finally { _lock.ExitWriteLock(); } |
| | 2216 | 132 | | } |
| | | 133 | | |
| | | 134 | | /// <summary> |
| | | 135 | | /// Evicts <see cref="SurveyResult"/> from the cache that have not been used within the specified expiration window. |
| | | 136 | | /// <see cref="SurveyResult"/> that are not in use are optionally returned to the pool. |
| | | 137 | | /// </summary> |
| | | 138 | | /// <param name="currentFrame">The current simulation frame.</param> |
| | | 139 | | /// <param name="expiration">The number of frames after which a <see cref="SurveyResult"/> is considered stale.</par |
| | | 140 | | internal void EvictStaleEntries(int currentFrame, int expiration) |
| | | 141 | | { |
| | 58 | 142 | | _lock.EnterUpgradeableReadLock(); |
| | | 143 | | try |
| | | 144 | | { |
| | 58 | 145 | | _staleKeys.Clear(); |
| | 276 | 146 | | foreach (KeyValuePair<int, T> kvp in _cache) |
| | | 147 | | { |
| | 80 | 148 | | if (!kvp.Value.IsInUse && currentFrame - kvp.Value.LastUsedFrame > expiration) |
| | 33 | 149 | | _staleKeys.Add(kvp.Key); |
| | | 150 | | } |
| | | 151 | | |
| | 58 | 152 | | if (_staleKeys.Count == 0) |
| | 56 | 153 | | return; |
| | | 154 | | |
| | 2 | 155 | | _lock.EnterWriteLock(); |
| | | 156 | | try |
| | | 157 | | { |
| | 70 | 158 | | for (int i = 0; i < _staleKeys.Count; i++) |
| | | 159 | | { |
| | 33 | 160 | | int key = _staleKeys[i]; |
| | 33 | 161 | | if (_cache.TryGetValue(key, out T result)) |
| | 33 | 162 | | RemoveCachedResult(key, result); |
| | | 163 | | } |
| | 2 | 164 | | } |
| | 4 | 165 | | finally { _lock.ExitWriteLock(); } |
| | | 166 | | |
| | | 167 | | } |
| | | 168 | | finally |
| | | 169 | | { |
| | 58 | 170 | | _staleKeys.Clear(); |
| | 58 | 171 | | _lock.ExitUpgradeableReadLock(); |
| | 58 | 172 | | } |
| | 58 | 173 | | } |
| | | 174 | | |
| | | 175 | | /// <summary> |
| | | 176 | | /// Attempts to check out an existing cached result without invoking a creation callback. |
| | | 177 | | /// </summary> |
| | | 178 | | /// <param name="request">The path request used as the cache key.</param> |
| | | 179 | | /// <param name="result">The checked-out cached result.</param> |
| | | 180 | | /// <returns><c>true</c> when a valid cached result was found; otherwise, <c>false</c>.</returns> |
| | | 181 | | public bool TryCheckout(IPathRequest request, out T result) |
| | | 182 | | { |
| | 1696 | 183 | | int key = request.RequestCacheKey; |
| | | 184 | | |
| | 1696 | 185 | | _lock.EnterUpgradeableReadLock(); |
| | | 186 | | try |
| | | 187 | | { |
| | 1696 | 188 | | if (_cache.TryGetValue(key, out result) && result.HasPath) |
| | | 189 | | { |
| | 1552 | 190 | | result.Context = request.Context; |
| | 1552 | 191 | | CheckoutCachedResult(result); |
| | 1552 | 192 | | return true; |
| | | 193 | | } |
| | | 194 | | |
| | 144 | 195 | | result = null!; |
| | 144 | 196 | | return false; |
| | | 197 | | } |
| | 3392 | 198 | | finally { _lock.ExitUpgradeableReadLock(); } |
| | 1696 | 199 | | } |
| | | 200 | | |
| | | 201 | | /// <summary> |
| | | 202 | | /// Seeds a valid result directly into the cache for internal benchmark and test fixtures. |
| | | 203 | | /// </summary> |
| | | 204 | | /// <remarks> |
| | | 205 | | /// This intentionally does not evict entries; callers use it to create exact cache-pressure |
| | | 206 | | /// shapes and should choose unique request keys up to the cache capacity. |
| | | 207 | | /// </remarks> |
| | | 208 | | internal bool TrySeed(T result, bool checkout) |
| | | 209 | | { |
| | 149 | 210 | | if (result == null || !result.HasPath || result.RequestHashKey < 0 || result.Context == null) |
| | 4 | 211 | | return false; |
| | | 212 | | |
| | 145 | 213 | | int key = result.RequestHashKey; |
| | | 214 | | |
| | 145 | 215 | | _lock.EnterWriteLock(); |
| | | 216 | | try |
| | | 217 | | { |
| | 144 | 218 | | if (_cache.TryGetValue(key, out T existing)) |
| | | 219 | | { |
| | 2 | 220 | | if (existing.IsInUse) |
| | 2 | 221 | | CountInUse--; |
| | | 222 | | |
| | 2 | 223 | | RemoveCachedResult(key, existing); |
| | 2 | 224 | | if (!ReferenceEquals(existing, result)) |
| | 1 | 225 | | existing.Reset(); |
| | | 226 | | } |
| | 142 | 227 | | else if (_cache.Count >= MaxCacheSize) |
| | | 228 | | { |
| | 1 | 229 | | return false; |
| | | 230 | | } |
| | | 231 | | |
| | 143 | 232 | | if (result.IsInUse) |
| | 1 | 233 | | result.Release(); |
| | | 234 | | |
| | 143 | 235 | | if (checkout) |
| | | 236 | | { |
| | 3 | 237 | | result.Checkout(); |
| | 3 | 238 | | CountInUse++; |
| | | 239 | | } |
| | | 240 | | |
| | 143 | 241 | | AddCachedResult(key, result); |
| | 143 | 242 | | return true; |
| | | 243 | | } |
| | 288 | 244 | | finally { _lock.ExitWriteLock(); } |
| | 144 | 245 | | } |
| | | 246 | | |
| | | 247 | | internal int CountIndexedEntriesForChart(string chartKey) |
| | | 248 | | { |
| | 11 | 249 | | if (string.IsNullOrEmpty(chartKey)) |
| | 1 | 250 | | return 0; |
| | | 251 | | |
| | 10 | 252 | | _lock.EnterReadLock(); |
| | | 253 | | try |
| | | 254 | | { |
| | 10 | 255 | | return _chartIndex.TryGetValue(chartKey, out SwiftList<int> keys) |
| | 10 | 256 | | ? keys.Count |
| | 10 | 257 | | : 0; |
| | | 258 | | } |
| | 20 | 259 | | finally { _lock.ExitReadLock(); } |
| | 10 | 260 | | } |
| | | 261 | | |
| | | 262 | | /// <summary> |
| | | 263 | | /// Invalidates cached results that reference the specified chart key by using the chart reverse index. |
| | | 264 | | /// </summary> |
| | | 265 | | /// <param name="chartKey">The chart key whose dependent cached results should be removed.</param> |
| | | 266 | | public void InvalidateForChart(string chartKey) |
| | | 267 | | { |
| | 4932 | 268 | | if (string.IsNullOrEmpty(chartKey)) return; |
| | | 269 | | |
| | 4932 | 270 | | _lock.EnterUpgradeableReadLock(); |
| | | 271 | | try |
| | | 272 | | { |
| | 4932 | 273 | | if (!_chartIndex.TryGetValue(chartKey, out SwiftList<int> indexedKeys) |
| | 4932 | 274 | | || indexedKeys.Count == 0) |
| | | 275 | | { |
| | 4878 | 276 | | return; |
| | | 277 | | } |
| | | 278 | | |
| | 54 | 279 | | _lock.EnterWriteLock(); |
| | | 280 | | try |
| | | 281 | | { |
| | 240 | 282 | | while (_chartIndex.TryGetValue(chartKey, out indexedKeys) |
| | 240 | 283 | | && indexedKeys.Count > 0) |
| | | 284 | | { |
| | 186 | 285 | | int key = indexedKeys[indexedKeys.Count - 1]; |
| | 186 | 286 | | if (_cache.TryGetValue(key, out T result)) |
| | | 287 | | { |
| | 185 | 288 | | InvalidateCachedResult(key, result); |
| | | 289 | | } |
| | | 290 | | else |
| | | 291 | | { |
| | 1 | 292 | | indexedKeys.Remove(key); |
| | 1 | 293 | | if (indexedKeys.Count == 0) |
| | 1 | 294 | | _chartIndex.Remove(chartKey); |
| | | 295 | | } |
| | | 296 | | } |
| | 54 | 297 | | } |
| | 108 | 298 | | finally { _lock.ExitWriteLock(); } |
| | | 299 | | } |
| | 9864 | 300 | | finally { _lock.ExitUpgradeableReadLock(); } |
| | 4932 | 301 | | } |
| | | 302 | | |
| | | 303 | | public void InvalidateWhere(Func<T, bool> predicate) |
| | | 304 | | { |
| | 2 | 305 | | SwiftList<int> toRemove = new(); |
| | 2 | 306 | | _lock.EnterUpgradeableReadLock(); |
| | | 307 | | try |
| | | 308 | | { |
| | 8 | 309 | | foreach (KeyValuePair<int, T> kvp in _cache) |
| | | 310 | | { |
| | 2 | 311 | | if (kvp.Value == null || !predicate(kvp.Value)) |
| | | 312 | | continue; |
| | | 313 | | |
| | 2 | 314 | | toRemove.Add(kvp.Key); |
| | | 315 | | } |
| | | 316 | | |
| | 2 | 317 | | if (toRemove.Count == 0) |
| | 1 | 318 | | return; |
| | | 319 | | |
| | 1 | 320 | | _lock.EnterWriteLock(); |
| | | 321 | | try |
| | | 322 | | { |
| | 6 | 323 | | foreach (int key in toRemove) |
| | | 324 | | { |
| | 2 | 325 | | if (_cache.TryGetValue(key, out T result)) |
| | 2 | 326 | | InvalidateCachedResult(key, result); |
| | | 327 | | } |
| | | 328 | | } |
| | 2 | 329 | | finally { _lock.ExitWriteLock(); } |
| | | 330 | | } |
| | 4 | 331 | | finally { _lock.ExitUpgradeableReadLock(); } |
| | 2 | 332 | | } |
| | | 333 | | |
| | | 334 | | public void InvalidateAll() |
| | | 335 | | { |
| | 1915 | 336 | | _lock.EnterWriteLock(); |
| | | 337 | | try |
| | | 338 | | { |
| | 3982 | 339 | | foreach (KeyValuePair<int, T> kvp in _cache) |
| | | 340 | | { |
| | 76 | 341 | | if (kvp.Value == null) continue; |
| | | 342 | | |
| | 76 | 343 | | kvp.Value.Reset(); |
| | | 344 | | } |
| | | 345 | | |
| | 1915 | 346 | | _cache.Clear(); |
| | 1915 | 347 | | _chartIndex.Clear(); |
| | 1915 | 348 | | CountInUse = 0; |
| | 1915 | 349 | | } |
| | 3830 | 350 | | finally { _lock.ExitWriteLock(); } |
| | 1915 | 351 | | } |
| | | 352 | | |
| | | 353 | | private bool TryGetLeastRecentlyUsedReusableEntry(out int key, out T result) |
| | | 354 | | { |
| | 6 | 355 | | key = -1; |
| | 6 | 356 | | result = null!; |
| | | 357 | | |
| | 1548 | 358 | | foreach (KeyValuePair<int, T> kvp in _cache) |
| | | 359 | | { |
| | 768 | 360 | | T candidate = kvp.Value; |
| | 768 | 361 | | if (candidate == null || candidate.IsInUse) |
| | | 362 | | continue; |
| | | 363 | | |
| | 512 | 364 | | if (result == null || candidate.LastUsedFrame < result.LastUsedFrame) |
| | | 365 | | { |
| | 6 | 366 | | key = kvp.Key; |
| | 6 | 367 | | result = candidate; |
| | | 368 | | } |
| | | 369 | | } |
| | | 370 | | |
| | 6 | 371 | | return result != null; |
| | | 372 | | } |
| | | 373 | | |
| | | 374 | | private void AddCachedResult(int key, T result) |
| | | 375 | | { |
| | 852 | 376 | | if (_cache.TryGetValue(key, out T existing)) |
| | 1 | 377 | | RemoveFromChartIndex(key, existing.ChartsUtilized); |
| | | 378 | | |
| | 852 | 379 | | _cache[key] = result; |
| | 852 | 380 | | AddToChartIndex(key, result.ChartsUtilized); |
| | 852 | 381 | | } |
| | | 382 | | |
| | | 383 | | private void CheckoutCachedResult(T result) |
| | | 384 | | { |
| | 1556 | 385 | | _lock.EnterWriteLock(); |
| | | 386 | | try |
| | | 387 | | { |
| | 1556 | 388 | | result.Checkout(); |
| | 1556 | 389 | | CountInUse++; |
| | 1556 | 390 | | } |
| | 3112 | 391 | | finally { _lock.ExitWriteLock(); } |
| | 1556 | 392 | | } |
| | | 393 | | |
| | | 394 | | private void InvalidateCachedResult(int key, T result) |
| | | 395 | | { |
| | 187 | 396 | | if (result.IsInUse) |
| | 13 | 397 | | CountInUse--; |
| | | 398 | | |
| | 187 | 399 | | RemoveCachedResult(key, result); |
| | 187 | 400 | | result.Reset(); |
| | 187 | 401 | | } |
| | | 402 | | |
| | | 403 | | private void RemoveCachedResult(int key, T result) |
| | | 404 | | { |
| | 228 | 405 | | RemoveFromChartIndex(key, result.ChartsUtilized); |
| | 228 | 406 | | _cache.Remove(key); |
| | 228 | 407 | | } |
| | | 408 | | |
| | | 409 | | private void AddToChartIndex(int cacheKey, string[] chartKeys) |
| | | 410 | | { |
| | 852 | 411 | | if (chartKeys == null || chartKeys.Length == 0) |
| | 592 | 412 | | return; |
| | | 413 | | |
| | 1514 | 414 | | for (int i = 0; i < chartKeys.Length; i++) |
| | | 415 | | { |
| | 497 | 416 | | string chartKey = chartKeys[i]; |
| | 497 | 417 | | if (string.IsNullOrEmpty(chartKey) |
| | 497 | 418 | | || ContainsPriorChartKey(chartKeys, i, chartKey)) |
| | | 419 | | { |
| | | 420 | | continue; |
| | | 421 | | } |
| | | 422 | | |
| | 496 | 423 | | if (!_chartIndex.TryGetValue(chartKey, out SwiftList<int> keys)) |
| | | 424 | | { |
| | 235 | 425 | | keys = new SwiftList<int>(1); |
| | 235 | 426 | | _chartIndex[chartKey] = keys; |
| | | 427 | | } |
| | | 428 | | |
| | 496 | 429 | | keys.Add(cacheKey); |
| | | 430 | | } |
| | 260 | 431 | | } |
| | | 432 | | |
| | | 433 | | private void RemoveFromChartIndex(int cacheKey, string[] chartKeys) |
| | | 434 | | { |
| | 229 | 435 | | if (chartKeys == null || chartKeys.Length == 0) |
| | 38 | 436 | | return; |
| | | 437 | | |
| | 1040 | 438 | | for (int i = 0; i < chartKeys.Length; i++) |
| | | 439 | | { |
| | 329 | 440 | | string chartKey = chartKeys[i]; |
| | 329 | 441 | | if (string.IsNullOrEmpty(chartKey) |
| | 329 | 442 | | || ContainsPriorChartKey(chartKeys, i, chartKey)) |
| | | 443 | | { |
| | | 444 | | continue; |
| | | 445 | | } |
| | | 446 | | |
| | 328 | 447 | | if (!_chartIndex.TryGetValue(chartKey, out SwiftList<int> keys)) |
| | | 448 | | continue; |
| | | 449 | | |
| | 328 | 450 | | keys.Remove(cacheKey); |
| | 328 | 451 | | if (keys.Count == 0) |
| | 69 | 452 | | _chartIndex.Remove(chartKey); |
| | | 453 | | } |
| | 191 | 454 | | } |
| | | 455 | | |
| | | 456 | | private static bool ContainsPriorChartKey(string[] chartKeys, int exclusiveEnd, string chartKey) |
| | | 457 | | { |
| | 2724 | 458 | | for (int i = 0; i < exclusiveEnd; i++) |
| | | 459 | | { |
| | 538 | 460 | | if (string.Equals(chartKeys[i], chartKey, StringComparison.Ordinal)) |
| | 2 | 461 | | return true; |
| | | 462 | | } |
| | | 463 | | |
| | 824 | 464 | | return false; |
| | | 465 | | } |
| | | 466 | | |
| | 3855 | 467 | | public void Dispose() => _lock?.Dispose(); |
| | | 468 | | } |