Hi.Webapi/Services/RenderingService.cs
2025-08-25 18:49:43 +08:00

105 lines
3.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Hi.Disp;
using Hi.Geom;
using Hi.Native;
using System.Collections.Concurrent;
namespace Hi.Webapi.Services
{
/// <summary>
/// Singleton Service for managing <see cref="DispEngine"/>.
/// </summary>
public class RenderingService : IDisposable
{
/// <summary>
/// Engine Dictionary.
/// Key is sessionID.
/// </summary>
public ConcurrentDictionary<string, DispEngine> EngineDictionary { get; } = new();
ILogger<RenderingService> Logger { get; }
private bool disposedValue;
public RenderingService(ILogger<RenderingService> logger)
{
Logger = logger;
}
/// <summary>
/// 創建或獲取一個 DispEngine 實例
/// </summary>
public DispEngine GetOrCreateEngine(string sessionId)
{
return EngineDictionary.GetOrAdd(sessionId, id =>
{
Logger.LogInformation($"創建新的 DispEngineSessionId: {id}");
var engine = new DispEngine();
engine.BackgroundColor = new Vec3d(0.1, 0.1, 0.5);
engine.BackgroundOpacity = 0.1;
return engine;
});
}
/// <summary>
/// 移除指定的 DispEngine
/// </summary>
public bool RemoveEngine(string sessionId)
{
if (EngineDictionary.TryRemove(sessionId, out var engine))
{
Logger.LogInformation($"移除 DispEngineSessionId: {sessionId}");
try
{
// 停止渲染
engine.IsVisible = false;
// 釋放資源
engine.Dispose();
}
catch (Exception ex)
{
Logger.LogError(ex, $"清理 DispEngine 時發生錯誤SessionId: {sessionId}");
}
return true;
}
return false;
}
/// <summary>
/// 獲取當前活動的引擎數量
/// </summary>
public int GetActiveEngineCount() => EngineDictionary.Count;
/// <inheritdoc/>
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
foreach (var kvp in EngineDictionary)
{
try
{
kvp.Value.IsVisible = false;
kvp.Value.Dispose();
}
catch (Exception ex)
{
Logger.LogError(ex, $"Dispose 時清理引擎錯誤SessionId: {kvp.Key}");
}
}
EngineDictionary.Clear();
}
disposedValue = true;
}
}
/// <inheritdoc/>
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}